answer
stringlengths
17
10.2M
package com.xeiam.xchange.anx.v2; import java.io.IOException; import java.math.BigDecimal; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.xeiam.xchange.anx.v2.dto.trade.polling.*; import si.mazi.rescu.ParamsDigest; import com.xeiam.xchange.anx.v2.dto.ANXException; import com.xeiam.xchange.anx.v2.dto.account.polling.ANXAccountInfoWrapper; import com.xeiam.xchange.anx.v2.dto.account.polling.ANXBitcoinDepositAddressWrapper; import com.xeiam.xchange.anx.v2.dto.account.polling.ANXWalletHistoryWrapper; import com.xeiam.xchange.anx.v2.dto.account.polling.ANXWithdrawalResponseWrapper; import com.xeiam.xchange.anx.v2.dto.marketdata.ANXDepthWrapper; import com.xeiam.xchange.anx.v2.dto.marketdata.ANXDepthsWrapper; import com.xeiam.xchange.anx.v2.dto.marketdata.ANXTickerWrapper; import com.xeiam.xchange.anx.v2.dto.marketdata.ANXTickersWrapper; import com.xeiam.xchange.anx.v2.dto.marketdata.ANXTradesWrapper; /** * @author timmolter */ @Path("api/2") @Produces(MediaType.APPLICATION_JSON) public interface ANXV2 { @GET @Path("money/order/lag") ANXLagWrapper getLag() throws ANXException, IOException; @GET @Path("{ident}{currency}/money/ticker") ANXTickerWrapper getTicker(@PathParam("ident") String tradeableIdentifier, @PathParam("currency") String currency) throws ANXException, IOException; @GET @Path("{ident}{currency}/money/ticker") ANXTickersWrapper getTickers(@PathParam("ident") String tradeableIdentifier, @PathParam("currency") String currency, @QueryParam("extraCcyPairs") String extraCurrencyPairs) throws ANXException, IOException; @GET @Path("{ident}{currency}/money/depth/fetch") ANXDepthWrapper getPartialDepth(@PathParam("ident") String tradeableIdentifier, @PathParam("currency") String currency) throws ANXException, IOException; @GET @Path("{ident}{currency}/money/depth/full") ANXDepthWrapper getFullDepth(@PathParam("ident") String tradeableIdentifier, @PathParam("currency") String currency) throws ANXException, IOException; @GET @Path("{ident}{currency}/money/depth/full") ANXDepthsWrapper getFullDepths(@PathParam("ident") String tradeableIdentifier, @PathParam("currency") String currency, @QueryParam("extraCcyPairs") String extraCurrencyPairs) throws ANXException, IOException; @GET @Path("{ident}{currency}/money/trade/fetch") ANXTradesWrapper getTrades(@PathParam("ident") String tradeableIdentifier, @PathParam("currency") String currency, @QueryParam("since") long since) throws ANXException, IOException; // Account Info API @POST @Path("money/info") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXAccountInfoWrapper getAccountInfo(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce) throws ANXException, IOException; @POST @Path("money/{currency}/address") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXBitcoinDepositAddressWrapper requestDepositAddress(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @PathParam("currency") String currency) throws ANXException, IOException; @POST @Path("money/{currency}/send_simple") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXWithdrawalResponseWrapper withdrawBtc(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @PathParam("currency") String currency, @FormParam("address") String address, @FormParam("amount_int") int amount, @FormParam("fee_int") int fee, @FormParam("no_instant") boolean noInstant, @FormParam("green") boolean green) throws ANXException, IOException; // Trade API @POST @Path("money/orders") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXOpenOrderWrapper getOpenOrders(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce) throws ANXException, IOException; /** * List of executed trades * * @param apiKey * @param postBodySignatureCreator * @param nonce * @param from * @param to * @return * @throws ANXException * @throws IOException */ @POST @Path("money/trade/list") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXTradeResultWrapper getExecutedTrades(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @FormParam("from") long from, @FormParam("to") long to) throws ANXException, IOException; /** * List of executed trades * * @param apiKey * @param postBodySignatureCreator * @param nonce * @return * @throws ANXException * @throws IOException */ @POST @Path("money/trade/list") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXTradeResultWrapper getExecutedTrades(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce) throws ANXException, IOException; /** * Status of the order * * @param apiKey * @param postBodySignatureCreator * @param nonce * @param order * @param type * @return * @throws ANXException * @throws IOException */ @POST @Path("{tradeIdent}{currency}/money/order/result") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXOrderResultWrapper getOrderResult(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @FormParam("order") String order, @FormParam("type") String type) throws ANXException, IOException; /** * @param postBodySignatureCreator * @param amount can be omitted to place market order */ @POST @Path("{tradeIdent}{currency}/money/order/add") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXGenericResponse placeOrder(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @PathParam("tradeIdent") String tradableIdentifier, @PathParam("currency") String currency, @FormParam("type") String type, @FormParam("amount") BigDecimal amount, @FormParam("price") BigDecimal price) throws ANXException, IOException; /** * Note: I know it's weird to have BTCEUR hardcoded in the URL, but it really doesn't seems to matter. BTCUSD works too. * <p> * * @param apiKey * @param postBodySignatureCreator * @param nonce * @param orderId * @return */ @POST @Path("BTCEUR/money/order/cancel") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXGenericResponse cancelOrder(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @FormParam("oid") String orderId) throws ANXException, IOException; /** * Returns the History of the selected wallet * * @param apiKey * @param postBodySignatureCreator * @param nonce * @param currency * @param page to fetch (can be null for first page) * @return * @throws com.xeiam.xchange.anx.v2.dto.ANXException */ @POST @Path("money/wallet/history") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) ANXWalletHistoryWrapper getWalletHistory(@HeaderParam("Rest-Key") String apiKey, @HeaderParam("Rest-Sign") ParamsDigest postBodySignatureCreator, @FormParam("nonce") long nonce, @FormParam("currency") String currency, @FormParam("page") Integer page) throws ANXException, IOException; }
package com.xpn.xwiki.doc; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ecs.filter.CharacterFilter; import org.apache.velocity.VelocityContext; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.suigeneris.jrcs.diff.Diff; import org.suigeneris.jrcs.diff.DifferentiationFailedException; import org.suigeneris.jrcs.diff.Revision; import org.suigeneris.jrcs.diff.delta.Delta; import org.suigeneris.jrcs.rcs.Version; import org.suigeneris.jrcs.util.ToString; import org.xwiki.bridge.DocumentModelBridge; import org.xwiki.rendering.block.MacroBlock; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.parser.SyntaxFactory; import org.xwiki.rendering.renderer.DefaultWikiPrinter; import org.xwiki.rendering.renderer.PrintRendererFactory; import org.xwiki.rendering.renderer.PrintRendererType; import org.xwiki.rendering.renderer.WikiPrinter; import org.xwiki.rendering.transformation.TransformationManager; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConstant; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.DocumentSection; import com.xpn.xwiki.content.Link; import com.xpn.xwiki.content.parsers.DocumentParser; import com.xpn.xwiki.content.parsers.LinkParser; import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler; import com.xpn.xwiki.content.parsers.ReplacementResultCollection; import com.xpn.xwiki.criteria.impl.RevisionCriteria; import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo; import com.xpn.xwiki.notify.XWikiNotificationRule; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.ListProperty; import com.xpn.xwiki.objects.ObjectDiff; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.ListClass; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.objects.classes.StaticListClass; import com.xpn.xwiki.plugin.query.XWikiCriteria; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.store.XWikiAttachmentStoreInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.XWikiVersioningStoreInterface; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.validation.XWikiValidationInterface; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.EditForm; import com.xpn.xwiki.web.ObjectAddForm; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; public class XWikiDocument implements DocumentModelBridge { private static final Log log = LogFactory.getLog(XWikiDocument.class); /** THe default wiki name to use when one isn't specified. */ private static final String DEFAULT_WIKI_NAME = "xwiki"; /** * Regex Pattern to recognize if there's HTML code in a XWiki page. */ private static final Pattern HTML_TAG_PATTERN = Pattern.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|" + "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>"); private String title; private String parent; private String space; private String name; private String content; private String meta; private String format; private String creator; private String author; private String contentAuthor; private String customClass; private Date contentUpdateDate; private Date updateDate; private Date creationDate; private Version version; private long id = 0; private boolean mostRecent = true; private boolean isNew = true; private String template; private String language; private String defaultLanguage; private int translation; private String database; private BaseObject tags; /** * Comment on the latest modification. */ private String comment; /** * Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For * example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our * first need is to support the new rendering component. To use the old rendering implementation specify a * "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component. */ private String syntaxId; /** * Is latest modification a minor edit */ private boolean isMinorEdit = false; /** * Used to make sure the MetaData String is regenerated. */ private boolean isContentDirty = true; /** * Used to make sure the MetaData String is regenerated */ private boolean isMetaDataDirty = true; public static final int HAS_ATTACHMENTS = 1; public static final int HAS_OBJECTS = 2; public static final int HAS_CLASS = 4; private int elements = HAS_OBJECTS | HAS_ATTACHMENTS; /** * Separator string between database name and space name. */ public static final String DB_SPACE_SEP = ":"; /** * Separator string between space name and page name. */ public static final String SPACE_NAME_SEP = "."; // Meta Data private BaseClass xWikiClass; private String xWikiClassXML; /** * Map holding document objects grouped by classname (className -> Vector of objects). The map is not synchronized, * and uses a TreeMap implementation to preserve className ordering (consistent sorted order for output to XML, * rendering in velocity, etc.) */ private Map<String, Vector<BaseObject>> xWikiObjects = new TreeMap<String, Vector<BaseObject>>(); private List<XWikiAttachment> attachmentList; // Caching private boolean fromCache = false; private ArrayList<BaseObject> objectsToRemove = new ArrayList<BaseObject>(); // Template by default assign to a view private String defaultTemplate; private String validationScript; private Object wikiNode; // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) private SoftReference<XWikiDocumentArchive> archive; private XWikiStoreInterface store; /** * This is a copy of this XWikiDocument before any modification was made to it. It is reset to the actual values * when the document is saved in the database. This copy is used for finding out differences made to this document * (useful for example to send the correct notifications to document change listeners). */ private XWikiDocument originalDocument; public XWikiStoreInterface getStore(XWikiContext context) { return context.getWiki().getStore(); } public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context) { return context.getWiki().getAttachmentStore(); } public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context) { return context.getWiki().getVersioningStore(); } public XWikiStoreInterface getStore() { return this.store; } public void setStore(XWikiStoreInterface store) { this.store = store; } public long getId() { if ((this.language == null) || this.language.trim().equals("")) { this.id = getFullName().hashCode(); } else { this.id = (getFullName() + ":" + this.language).hashCode(); } // if (log.isDebugEnabled()) // log.debug("ID: " + getFullName() + " " + language + ": " + id); return this.id; } public void setId(long id) { this.id = id; } /** * @return the name of the space of the document */ public String getSpace() { return this.space; } public void setSpace(String space) { this.space = space; } public String getVersion() { return getRCSVersion().toString(); } public void setVersion(String version) { if (version != null && !"".equals(version)) { this.version = new Version(version); } } public Version getRCSVersion() { if (this.version == null) { return new Version("1.1"); } return this.version; } public void setRCSVersion(Version version) { this.version = version; } public XWikiDocument() { this("Main", "WebHome"); } /** * Constructor that specifies the local document identifier: space name, document name. {@link #setDatabase(String)} * must be called afterwards to specify the wiki name. * * @param web The space this document belongs to. * @param name The name of the document. */ public XWikiDocument(String space, String name) { this(null, space, name); } /** * Constructor that specifies the full document identifier: wiki name, space name, document name. * * @param wiki The wiki this document belongs to. * @param web The space this document belongs to. * @param name The name of the document. */ public XWikiDocument(String wiki, String web, String name) { setDatabase(wiki); setSpace(web); int i1 = name.indexOf("."); if (i1 == -1) { setName(name); } else { setSpace(name.substring(0, i1)); setName(name.substring(i1 + 1)); } this.updateDate = new Date(); this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000); this.contentUpdateDate = new Date(); this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000); this.creationDate = new Date(); this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000); this.parent = ""; this.content = "\n"; this.format = ""; this.author = ""; this.language = ""; this.defaultLanguage = ""; this.attachmentList = new ArrayList<XWikiAttachment>(); this.customClass = ""; this.comment = ""; this.syntaxId = "xwiki/1.0"; // Note: As there's no notion of an Empty document we don't set the original document // field. Thus getOriginalDocument() may return null. } /** * @return the copy of this XWikiDocument instance before any modification was made to it. * @see #originalDocument */ public XWikiDocument getOriginalDocument() { return this.originalDocument; } /** * @param originalDocument the original document representing this document instance before any change was made to * it, prior to the last time it was saved * @see #originalDocument */ public void setOriginalDocument(XWikiDocument originalDocument) { this.originalDocument = originalDocument; } public XWikiDocument getParentDoc() { return new XWikiDocument(getSpace(), getParent()); } public String getParent() { return this.parent != null ? this.parent : ""; } public void setParent(String parent) { if (parent != null && !parent.equals(this.parent)) { setMetaDataDirty(true); } this.parent = parent; } public String getContent() { return this.content; } public void setContent(String content) { if (content == null) { content = ""; } if (!content.equals(this.content)) { setContentDirty(true); setWikiNode(null); } this.content = content; } public String getRenderedContent(XWikiContext context) throws XWikiException { String renderedContent; // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context); } else { renderedContent = getRenderedContentUsingNewRenderingModule(this.content); } return renderedContent; } /** * @param text the text to render * @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0") * @param context the XWiki Context object * @return the given text rendered in the context of this document using the passed Syntax * @since 1.6M1 */ public String getRenderedContent(String text, String syntaxId, XWikiContext context) { String result; HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (syntaxId.equalsIgnoreCase("xwiki/1.0")) { result = context.getWiki().getRenderingEngine().renderText(text, this, context); } else { result = getRenderedContentUsingNewRenderingModule(text); } } catch (XWikiException e) { // Failed to render for some reason. This method should normally throw an exception but this // requires changing the signature of calling methods too. log.warn(e); result = ""; } finally { restoreContext(backup, context); } return result; } /** * @param text the text to render * @param context the XWiki Context object * @return the given text rendered in the context of this document * @deprecated since 1.6M1 use {@link #getRenderedContent(String, String, com.xpn.xwiki.XWikiContext)} */ @Deprecated public String getRenderedContent(String text, XWikiContext context) { return getRenderedContent(text, "xwiki/1.0", context); } /** * Renders the passed content using the new Rendering architecture. */ private String getRenderedContentUsingNewRenderingModule(String content) throws XWikiException { TransformationManager transformations = (TransformationManager) Utils.getComponent(TransformationManager.ROLE); XDOM dom; try { Parser parser = (Parser) Utils.getComponent(Parser.ROLE, getSyntaxId()); dom = parser.parse(new StringReader(content)); SyntaxFactory syntaxFactory = (SyntaxFactory) Utils.getComponent(SyntaxFactory.ROLE); transformations.performTransformations(dom, syntaxFactory.createSyntaxFromIdString(getSyntaxId())); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to render content using new rendering system", e); } PrintRendererFactory factory = (PrintRendererFactory) Utils.getComponent(PrintRendererFactory.ROLE); WikiPrinter printer = new DefaultWikiPrinter(); dom.traverse(factory.createRenderer(PrintRendererType.XHTML, printer)); return printer.toString(); } public String getEscapedContent(XWikiContext context) throws XWikiException { CharacterFilter filter = new CharacterFilter(); return filter.process(getTranslatedContent(context)); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getFullName() { StringBuffer buf = new StringBuffer(); buf.append(getSpace()); buf.append("."); buf.append(getName()); return buf.toString(); } public void setFullName(String name) { setFullName(name, null); } /** * {@inheritDoc} * * @see DocumentModelBridge#getWikiName() */ public String getWikiName() { return StringUtils.isEmpty(getDatabase()) ? DEFAULT_WIKI_NAME : getDatabase(); } public String getTitle() { return (this.title != null) ? this.title : ""; } /** * @param context the XWiki context used to get acces to the XWikiRenderingEngine object * @return the document title. If a title has not been provided, look for a section title in the document's content * and if not found return the page name. The returned title is also interpreted which means it's allowed to * use Velocity, Groovy, etc syntax within a title. */ public String getDisplayTitle(XWikiContext context) { // 1) Check if the user has provided a title String title = getTitle(); // 2) If not, then try to extract the title from the first document section title if (title.length() == 0) { title = extractTitle(); } // 3) Last if a title has been found renders it as it can contain macros, velocity code, // groovy, etc. if (title.length() > 0) { // This will not completely work for scriting code in title referencing variables // defined elsewhere. In that case it'll only work if those variables have been // parsed and put in the corresponding scripting context. This will not work for // breadcrumbs for example. title = context.getWiki().getRenderingEngine().interpretText(title, this, context); } else { // 4) No title has been found, return the page name as the title title = getName(); } return title; } /** * @return the first level 1 or level 1.1 title text in the document's content or "" if none are found * @todo this method has nothing to do in this class and should be moved elsewhere */ public String extractTitle() { try { String content = getContent(); int i1 = 0; int i2; while (true) { i2 = content.indexOf("\n", i1); String title = ""; if (i2 != -1) { title = content.substring(i1, i2).trim(); } else { title = content.substring(i1).trim(); } if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) { return title.substring(title.indexOf(" ")).trim(); } if (i2 == -1) { break; } i1 = i2 + 1; } } catch (Exception e) { } return ""; } public void setTitle(String title) { if (title != null && !title.equals(this.title)) { setContentDirty(true); } this.title = title; } public String getFormat() { return this.format != null ? this.format : ""; } public void setFormat(String format) { this.format = format; if (!format.equals(this.format)) { setMetaDataDirty(true); } } public String getAuthor() { return this.author != null ? this.author.trim() : ""; } public String getContentAuthor() { return this.contentAuthor != null ? this.contentAuthor.trim() : ""; } public void setAuthor(String author) { if (!getAuthor().equals(author)) { setMetaDataDirty(true); } this.author = author; } public void setContentAuthor(String contentAuthor) { if (!getContentAuthor().equals(contentAuthor)) { setMetaDataDirty(true); } this.contentAuthor = contentAuthor; } public String getCreator() { return this.creator != null ? this.creator.trim() : ""; } public void setCreator(String creator) { if (!getCreator().equals(creator)) { setMetaDataDirty(true); } this.creator = creator; } public Date getDate() { if (this.updateDate == null) { return new Date(); } else { return this.updateDate; } } public void setDate(Date date) { if ((date != null) && (!date.equals(this.updateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.updateDate = date; } public Date getCreationDate() { if (this.creationDate == null) { return new Date(); } else { return this.creationDate; } } public void setCreationDate(Date date) { if ((date != null) && (!date.equals(this.creationDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.creationDate = date; } public Date getContentUpdateDate() { if (this.contentUpdateDate == null) { return new Date(); } else { return this.contentUpdateDate; } } public void setContentUpdateDate(Date date) { if ((date != null) && (!date.equals(this.contentUpdateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.contentUpdateDate = date; } public String getMeta() { return this.meta; } public void setMeta(String meta) { if (meta == null) { if (this.meta != null) { setMetaDataDirty(true); } } else if (!meta.equals(this.meta)) { setMetaDataDirty(true); } this.meta = meta; } public void appendMeta(String meta) { StringBuffer buf = new StringBuffer(this.meta); buf.append(meta); buf.append("\n"); this.meta = buf.toString(); setMetaDataDirty(true); } public boolean isContentDirty() { return this.isContentDirty; } public void incrementVersion() { if (this.version == null) { this.version = new Version("1.1"); } else { if (isMinorEdit()) { this.version = this.version.next(); } else { this.version = this.version.getBranchPoint().next().newBranch(1); } } } public void setContentDirty(boolean contentDirty) { this.isContentDirty = contentDirty; } public boolean isMetaDataDirty() { return this.isMetaDataDirty; } public void setMetaDataDirty(boolean metaDataDirty) { this.isMetaDataDirty = metaDataDirty; } public String getAttachmentURL(String filename, XWikiContext context) { return getAttachmentURL(filename, "download", context); } public String getAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return url.toString(); } public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String params, boolean redirect, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context); if (redirect) { if (url == null) { return null; } else { return url.toString(); } } else { return context.getURLFactory().getURL(url, context); } } public String getURL(String action, boolean redirect, XWikiContext context) { return getURL(action, null, redirect, context); } public String getURL(String action, XWikiContext context) { return getURL(action, false, context); } public String getURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory() .createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String querystring, String anchor, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, anchor, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalURL(String action, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context); return url.toString(); } public String getExternalURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return url.toString(); } public String getParentURL(XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.setFullName(getParent(), context); URL url = context.getURLFactory().createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException { loadArchive(context); return getDocumentArchive(); } /** * Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from * scripting. * * @param customClassName the name of the custom {@link com.xpn.xwiki.api.Document} class of the object to create. * @param context the XWiki context. * @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context) { if (!((customClassName == null) || (customClassName.equals("")))) { try { return newDocument(Class.forName(customClassName), context); } catch (ClassNotFoundException e) { log.error("Failed to get java Class object from class name", e); } } return new com.xpn.xwiki.api.Document(this, context); } /** * Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from * scripting. * * @param customClass the custom {@link com.xpn.xwiki.api.Document} class the object to create. * @param context the XWiki context. * @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(Class< ? > customClass, XWikiContext context) { if (customClass != null) { try { Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class}; Object[] args = new Object[] {this, context}; return (com.xpn.xwiki.api.Document) customClass.getConstructor(classes).newInstance(args); } catch (Exception e) { log.error("Failed to create a custom Document object", e); } } return new com.xpn.xwiki.api.Document(this, context); } public com.xpn.xwiki.api.Document newDocument(XWikiContext context) { String customClass = getCustomClass(); return newDocument(customClass, context); } public void loadArchive(XWikiContext context) throws XWikiException { if (this.archive == null || this.archive.get() == null) { XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context); // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during // the request) this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public XWikiDocumentArchive getDocumentArchive() { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (this.archive == null) { return null; } else { return this.archive.get(); } } public void setDocumentArchive(XWikiDocumentArchive arch) { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (arch != null) { this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public void setDocumentArchive(String sarch) throws XWikiException { XWikiDocumentArchive xda = new XWikiDocumentArchive(getId()); xda.setArchive(sarch); setDocumentArchive(xda); } public Version[] getRevisions(XWikiContext context) throws XWikiException { return getVersioningStore(context).getXWikiDocVersions(this, context); } public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException { try { Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context); int length = nb; // 0 means all revisions if (nb == 0) { length = revisions.length; } if (revisions.length < length) { length = revisions.length; } String[] recentrevs = new String[length]; for (int i = 1; i <= length; i++) { recentrevs[i - 1] = revisions[revisions.length - i].toString(); } return recentrevs; } catch (Exception e) { return new String[0]; } } /** * Get document versions matching criterias like author, minimum creation date, etc. * * @param criteria criteria used to match versions * @return a list of matching versions */ public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException { List<String> results = new ArrayList<String>(); Version[] revisions = getRevisions(context); XWikiRCSNodeInfo nextNodeinfo = null; XWikiRCSNodeInfo nodeinfo = null; for (int i = 0; i < revisions.length; i++) { nodeinfo = nextNodeinfo; nextNodeinfo = getRevisionInfo(revisions[i].toString(), context); if (nodeinfo == null) { continue; } // Minor/Major version matching if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) { // Author matching if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching if (nodeinfo.getDate().after(criteria.getMinDate()) && nodeinfo.getDate().before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } } nodeinfo = nextNodeinfo; if (nodeinfo != null) { if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching if (nodeinfo.getDate().after(criteria.getMinDate()) && nodeinfo.getDate().before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } return criteria.getRange().subList(results); } public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException { return getDocumentArchive(context).getNode(new Version(version)); } /** * @return Is this version the most recent one. False if and only if there are newer versions of this document in * the database. */ public boolean isMostRecent() { return this.mostRecent; } /** * must not be used unless in store system. * * @param mostRecent - mark document as most recent. */ public void setMostRecent(boolean mostRecent) { this.mostRecent = mostRecent; } public BaseClass getxWikiClass() { if (this.xWikiClass == null) { this.xWikiClass = new BaseClass(); this.xWikiClass.setName(getFullName()); } return this.xWikiClass; } public void setxWikiClass(BaseClass xWikiClass) { this.xWikiClass = xWikiClass; } public Map<String, Vector<BaseObject>> getxWikiObjects() { return this.xWikiObjects; } public void setxWikiObjects(Map<String, Vector<BaseObject>> xWikiObjects) { this.xWikiObjects = xWikiObjects; } public BaseObject getxWikiObject() { return getObject(getFullName()); } public List<BaseClass> getxWikiClasses(XWikiContext context) { List<BaseClass> list = new ArrayList<BaseClass>(); // xWikiObjects is a TreeMap, with elements sorted by className for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = null; Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { bclass = obj.getxWikiClass(context); if (bclass != null) { break; } } } if (bclass != null) { list.add(bclass); } } return list; } public int createNewObject(String classname, XWikiContext context) throws XWikiException { BaseObject object = BaseClass.newCustomClassInstance(classname, context); object.setName(getFullName()); object.setClassName(classname); Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } objects.add(object); int nb = objects.size() - 1; object.setNumber(nb); setContentDirty(true); return nb; } public int getObjectNumbers(String classname) { try { return getxWikiObjects().get(classname).size(); } catch (Exception e) { return 0; } } public Vector<BaseObject> getObjects(String classname) { if (classname == null) { return new Vector<BaseObject>(); } if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname); } public void setObjects(String classname, Vector<BaseObject> objects) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } getxWikiObjects().put(classname, objects); } public BaseObject getObject(String classname) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } Vector<BaseObject> objects = getxWikiObjects().get(classname); if (objects == null) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { return obj; } } return null; } public BaseObject getObject(String classname, int nb) { try { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname).get(nb); } catch (Exception e) { return null; } } public BaseObject getObject(String classname, String key, String value) { return getObject(classname, key, value, false); } public BaseObject getObject(String classname, String key, String value, boolean failover) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } try { if (value == null) { if (failover) { return getObject(classname); } else { return null; } } Vector<BaseObject> objects = getxWikiObjects().get(classname); if ((objects == null) || (objects.size() == 0)) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { if (value.equals(obj.getStringValue(key))) { return obj; } } } if (failover) { return getObject(classname); } else { return null; } } catch (Exception e) { if (failover) { return getObject(classname); } e.printStackTrace(); return null; } } public void addObject(String classname, BaseObject object) { if (object != null) { object.setName(getFullName()); } Vector<BaseObject> vobj = getObjects(classname); if (vobj == null) { setObject(classname, 0, object); } else { setObject(classname, vobj.size(), object); } setContentDirty(true); } public void setObject(String classname, int nb, BaseObject object) { if (object != null) { object.setName(getFullName()); } Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } if (nb >= objects.size()) { objects.setSize(nb + 1); } objects.set(nb, object); object.setNumber(nb); setContentDirty(true); } /** * @return true if the document is a new one (ie it has never been saved) or false otherwise */ public boolean isNew() { return this.isNew; } public void setNew(boolean aNew) { this.isNew = aNew; } public void mergexWikiClass(XWikiDocument templatedoc) { BaseClass bclass = getxWikiClass(); BaseClass tbclass = templatedoc.getxWikiClass(); if (tbclass != null) { if (bclass == null) { setxWikiClass((BaseClass) tbclass.clone()); } else { getxWikiClass().merge((BaseClass) tbclass.clone()); } } setContentDirty(true); } public void mergexWikiObjects(XWikiDocument templatedoc) { // TODO: look for each object if it already exist and add it if it doesn't for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> myObjects = getxWikiObjects().get(name); if (myObjects == null) { myObjects = new Vector<BaseObject>(); } for (BaseObject otherObject : templatedoc.getxWikiObjects().get(name)) { if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); myObjects.add(myObject); myObject.setNumber(myObjects.size() - 1); } } getxWikiObjects().put(name, myObjects); } setContentDirty(true); } public void clonexWikiObjects(XWikiDocument templatedoc) { for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> tobjects = templatedoc.getObjects(name); Vector<BaseObject> objects = new Vector<BaseObject>(); objects.setSize(tobjects.size()); for (int i = 0; i < tobjects.size(); i++) { BaseObject otherObject = tobjects.get(i); if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); objects.set(i, myObject); } } getxWikiObjects().put(name, objects); } } public String getTemplate() { return StringUtils.defaultString(this.template); } public void setTemplate(String template) { this.template = template; setMetaDataDirty(true); } public String displayPrettyName(String fieldname, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayPrettyName(fieldname, showMandatory, before, object, context); } catch (Exception e) { return ""; } } public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, false, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String dprettyName = ""; if (showMandatory) { dprettyName = context.getWiki().addMandatory(context); } if (before) { return dprettyName + pclass.getPrettyName(context); } else { return pclass.getPrettyName(context) + dprettyName; } } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayTooltip(fieldname, object, context); } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String tooltip = pclass.getTooltip(context); if ((tooltip != null) && (!tooltip.trim().equals(""))) { String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) + "\" class=\"tooltip_image\" align=\"middle\" />"; return context.getWiki().addTooltip(img, tooltip, context); } else { return ""; } } catch (Exception e) { return ""; } } public String display(String fieldname, String type, BaseObject obj, XWikiContext context) { return display(fieldname, type, "", obj, context); } public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context) { HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); type = type.toLowerCase(); StringBuffer result = new StringBuffer(); PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String prefix = pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_"; if (pclass.isCustomDisplayed(context)) { pclass.displayCustom(result, fieldname, prefix, type, obj, context); } else if (type.equals("view")) { pclass.displayView(result, fieldname, prefix, obj, context); } else if (type.equals("rendered")) { String fcontent = pclass.displayView(fieldname, prefix, obj, context); // This mode is deprecated for the new rendering and should also be removed for the old rendering // since the way to implement this now is to choose the type of rendering to do in the class itself. // Thus for the new renderinfg we simply make this mode work like the "view" mode. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append(getRenderedContent(fcontent, getSyntaxId(), context)); } else { result.append(fcontent); } } else if (type.equals("edit")) { context.addDisplayedField(fieldname); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append("{pre}"); } pclass.displayEdit(result, fieldname, prefix, obj, context); if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append("{/pre}"); } } else if (type.equals("hidden")) { // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append("{pre}"); } pclass.displayHidden(result, fieldname, prefix, obj, context); if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append("{/pre}"); } } else if (type.equals("search")) { // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append("{pre}"); } prefix = obj.getxWikiClass(context).getName() + "_"; pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context); if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { result.append("{/pre}"); } } else { pclass.displayView(result, fieldname, prefix, obj, context); } return result.toString(); } catch (Exception ex) { // TODO: It would better to check if the field exists rather than catching an exception // raised by a NPE as this is currently the case here... log.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object [" + (obj == null ? "NULL" : obj.getName()) + "]"); return ""; } finally { restoreContext(backup, context); } } public String display(String fieldname, BaseObject obj, XWikiContext context) { String type = null; try { type = (String) context.get("display"); } catch (Exception e) { } if (type == null) { type = "view"; } return display(fieldname, type, obj, context); } public String display(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return display(fieldname, object, context); } catch (Exception e) { return ""; } } public String display(String fieldname, String mode, XWikiContext context) { return display(fieldname, mode, "", context); } public String display(String fieldname, String mode, String prefix, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } if (object == null) { return ""; } else { return display(fieldname, mode, prefix, object, context); } } catch (Exception e) { return ""; } } public String displayForm(String className, String header, String format, XWikiContext context) { return displayForm(className, header, format, true, context); } public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (format.endsWith("\\n")) { linebreak = true; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); Collection fields = bclass.getFieldList(); if (fields.size() == 0) { return ""; } StringBuffer result = new StringBuffer(); VelocityContext vcontext = new VelocityContext(); for (Iterator it = fields.iterator(); it.hasNext();) { PropertyClass pclass = (PropertyClass) it.next(); vcontext.put(pclass.getName(), pclass.getPrettyName()); } result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } // display each line for (int i = 0; i < objects.size(); i++) { vcontext.put("id", new Integer(i + 1)); BaseObject object = objects.get(i); if (object != null) { for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) { String name = (String) it.next(); vcontext.put(name, display(name, object, context)); } result.append(XWikiVelocityRenderer .evaluate(format, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } } } return result.toString(); } public String displayForm(String className, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return ""; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); Collection fields = bclass.getFieldList(); if (fields.size() == 0) { return ""; } StringBuffer result = new StringBuffer(); result.append("{table}\n"); boolean first = true; for (Iterator it = fields.iterator(); it.hasNext();) { if (first == true) { first = false; } else { result.append("|"); } PropertyClass pclass = (PropertyClass) it.next(); result.append(pclass.getPrettyName()); } result.append("\n"); for (int i = 0; i < objects.size(); i++) { BaseObject object = objects.get(i); if (object != null) { first = true; for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) { if (first == true) { first = false; } else { result.append("|"); } String data = display((String) it.next(), object, context); data = data.trim(); data = data.replaceAll("\n", " "); if (data.length() == 0) { result.append("&nbsp;"); } else { result.append(data); } } result.append("\n"); } } result.append("{table}\n"); return result.toString(); } public boolean isFromCache() { return this.fromCache; } public void setFromCache(boolean fromCache) { this.fromCache = fromCache; } public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String defaultLanguage = eform.getDefaultLanguage(); if (defaultLanguage != null) { setDefaultLanguage(defaultLanguage); } String defaultTemplate = eform.getDefaultTemplate(); if (defaultTemplate != null) { setDefaultTemplate(defaultTemplate); } String creator = eform.getCreator(); if ((creator != null) && (!creator.equals(getCreator()))) { if ((getCreator().equals(context.getUser())) || (context.getWiki().getRightService().hasAdminRights(context))) { setCreator(creator); } } String parent = eform.getParent(); if (parent != null) { setParent(parent); } // Read the comment from the form String comment = eform.getComment(); if (comment != null) { setComment(comment); } // Read the minor edit checkbox from the form setMinorEdit(eform.isMinorEdit()); String tags = eform.getTags(); if (tags != null) { setTags(tags, context); } // Set the Syntax id if defined String syntaxId = eform.getSyntaxId(); if (syntaxId != null) { setSyntaxId(syntaxId); } } /** * add tags to the document. */ public void setTags(String tags, XWikiContext context) throws XWikiException { loadTags(context); StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS); tagProp.fromString(tags); this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags)); setMetaDataDirty(true); } public String getTags(XWikiContext context) { ListProperty prop = (ListProperty) getTagProperty(context); if (prop != null) { return prop.getTextValue(); } return null; } public List getTagsList(XWikiContext context) { List tagList = null; BaseProperty prop = getTagProperty(context); if (prop != null) { tagList = (List) prop.getValue(); } return tagList; } private BaseProperty getTagProperty(XWikiContext context) { loadTags(context); return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)); } private void loadTags(XWikiContext context) { if (this.tags == null) { this.tags = getObject(XWikiConstant.TAG_CLASS, true, context); } } public List getTagsPossibleValues(XWikiContext context) { loadTags(context); String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS)) .getValues(); return ListClass.getListFromString(possibleValues); // ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString(); } public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String content = eform.getContent(); if (content != null) { // Cleanup in case we use HTMLAREA // content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", // content); content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content); setContent(content); } String title = eform.getTitle(); if (title != null) { setTitle(title); } } public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException { for (String name : getxWikiObjects().keySet()) { Vector<BaseObject> oldObjects = getObjects(name); Vector<BaseObject> newObjects = new Vector<BaseObject>(); newObjects.setSize(oldObjects.size()); for (int i = 0; i < oldObjects.size(); i++) { BaseObject oldobject = oldObjects.get(i); if (oldobject != null) { BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); newObjects.set(newobject.getNumber(), newobject); } } getxWikiObjects().put(name, newObjects); } setContentDirty(true); } public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException { readDocMetaFromForm(eform, context); readTranslationMetaFromForm(eform, context); readObjectsFromForm(eform, context); } public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException { String template = eform.getTemplate(); readFromTemplate(template, context); } public void readFromTemplate(String template, XWikiContext context) throws XWikiException { if ((template != null) && (!template.equals(""))) { String content = getContent(); if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) { Object[] args = {getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY, "Cannot add a template to document {0} because it already has content", null, args); } else { if (template.indexOf('.') == -1) { template = getSpace() + "." + template; } XWiki xwiki = context.getWiki(); XWikiDocument templatedoc = xwiki.getDocument(template, context); if (templatedoc.isNew()) { Object[] args = {template, getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST, "Template document {0} does not exist when adding to document {1}", null, args); } else { setTemplate(template); setContent(templatedoc.getContent()); if ((getParent() == null) || (getParent().equals(""))) { String tparent = templatedoc.getParent(); if (tparent != null) { setParent(tparent); } } if (isNew()) { // We might have received the object from the cache // and the template objects might have been copied already // we need to remove them setxWikiObjects(new TreeMap<String, Vector<BaseObject>>()); } // Merge the external objects // Currently the choice is not to merge the base class and object because it is // not // the prefered way of using external classes and objects. mergexWikiObjects(templatedoc); } } } setContentDirty(true); } public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event, XWikiContext context) { // Do nothing for the moment.. // A usefull thing here would be to look at any instances of a Notification Object // with email addresses and send an email to warn that the document has been modified.. } /** * Use the document passsed as parameter as the new identity for the current document. * * @param document the document containing the new identity * @throws XWikiException in case of error */ private void clone(XWikiDocument document) throws XWikiException { setDatabase(document.getDatabase()); setRCSVersion(document.getRCSVersion()); setDocumentArchive(document.getDocumentArchive()); setAuthor(document.getAuthor()); setContentAuthor(document.getContentAuthor()); setContent(document.getContent()); setContentDirty(document.isContentDirty()); setCreationDate(document.getCreationDate()); setDate(document.getDate()); setCustomClass(document.getCustomClass()); setContentUpdateDate(document.getContentUpdateDate()); setTitle(document.getTitle()); setFormat(document.getFormat()); setFromCache(document.isFromCache()); setElements(document.getElements()); setId(document.getId()); setMeta(document.getMeta()); setMetaDataDirty(document.isMetaDataDirty()); setMostRecent(document.isMostRecent()); setName(document.getName()); setNew(document.isNew()); setStore(document.getStore()); setTemplate(document.getTemplate()); setSpace(document.getSpace()); setParent(document.getParent()); setCreator(document.getCreator()); setDefaultLanguage(document.getDefaultLanguage()); setDefaultTemplate(document.getDefaultTemplate()); setValidationScript(document.getValidationScript()); setLanguage(document.getLanguage()); setTranslation(document.getTranslation()); setxWikiClass((BaseClass) document.getxWikiClass().clone()); setxWikiClassXML(document.getxWikiClassXML()); setComment(document.getComment()); setMinorEdit(document.isMinorEdit()); setSyntaxId(document.getSyntaxId()); setSyntaxId(document.getSyntaxId()); clonexWikiObjects(document); copyAttachments(document); this.elements = document.elements; this.originalDocument = document.originalDocument; } @Override public Object clone() { XWikiDocument doc = null; try { doc = getClass().newInstance(); doc.setDatabase(getDatabase()); // use version field instead of getRCSVersion because it returns "1.1" if version==null. doc.version = this.version; doc.setDocumentArchive(getDocumentArchive()); doc.setAuthor(getAuthor()); doc.setContentAuthor(getContentAuthor()); doc.setContent(getContent()); doc.setContentDirty(isContentDirty()); doc.setCreationDate(getCreationDate()); doc.setDate(getDate()); doc.setCustomClass(getCustomClass()); doc.setContentUpdateDate(getContentUpdateDate()); doc.setTitle(getTitle()); doc.setFormat(getFormat()); doc.setFromCache(isFromCache()); doc.setElements(getElements()); doc.setId(getId()); doc.setMeta(getMeta()); doc.setMetaDataDirty(isMetaDataDirty()); doc.setMostRecent(isMostRecent()); doc.setName(getName()); doc.setNew(isNew()); doc.setStore(getStore()); doc.setTemplate(getTemplate()); doc.setSpace(getSpace()); doc.setParent(getParent()); doc.setCreator(getCreator()); doc.setDefaultLanguage(getDefaultLanguage()); doc.setDefaultTemplate(getDefaultTemplate()); doc.setValidationScript(getValidationScript()); doc.setLanguage(getLanguage()); doc.setTranslation(getTranslation()); doc.setxWikiClass((BaseClass) getxWikiClass().clone()); doc.setxWikiClassXML(getxWikiClassXML()); doc.setComment(getComment()); doc.setMinorEdit(isMinorEdit()); doc.setSyntaxId(getSyntaxId()); doc.clonexWikiObjects(this); doc.copyAttachments(this); doc.elements = this.elements; doc.originalDocument = this.originalDocument; } catch (Exception e) { // This should not happen log.error("Exception while doc.clone", e); } return doc; } public void copyAttachments(XWikiDocument xWikiSourceDocument) { getAttachmentList().clear(); Iterator<XWikiAttachment> attit = xWikiSourceDocument.getAttachmentList().iterator(); while (attit.hasNext()) { XWikiAttachment attachment = attit.next(); XWikiAttachment newattachment = (XWikiAttachment) attachment.clone(); newattachment.setDoc(this); if (newattachment.getAttachment_content() != null) { newattachment.getAttachment_content().setContentDirty(true); } getAttachmentList().add(newattachment); } setContentDirty(true); } public void loadAttachments(XWikiContext context) throws XWikiException { for (XWikiAttachment attachment : getAttachmentList()) { attachment.loadContent(context); attachment.loadArchive(context); } } @Override public boolean equals(Object object) { XWikiDocument doc = (XWikiDocument) object; if (!getName().equals(doc.getName())) { return false; } if (!getSpace().equals(doc.getSpace())) { return false; } if (!getAuthor().equals(doc.getAuthor())) { return false; } if (!getContentAuthor().equals(doc.getContentAuthor())) { return false; } if (!getParent().equals(doc.getParent())) { return false; } if (!getCreator().equals(doc.getCreator())) { return false; } if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) { return false; } if (!getLanguage().equals(doc.getLanguage())) { return false; } if (getTranslation() != doc.getTranslation()) { return false; } if (getDate().getTime() != doc.getDate().getTime()) { return false; } if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) { return false; } if (getCreationDate().getTime() != doc.getCreationDate().getTime()) { return false; } if (!getFormat().equals(doc.getFormat())) { return false; } if (!getTitle().equals(doc.getTitle())) { return false; } if (!getContent().equals(doc.getContent())) { return false; } if (!getVersion().equals(doc.getVersion())) { return false; } if (!getTemplate().equals(doc.getTemplate())) { return false; } if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) { return false; } if (!getValidationScript().equals(doc.getValidationScript())) { return false; } if (!getComment().equals(doc.getComment())) { return false; } if (isMinorEdit() != doc.isMinorEdit()) { return false; } if (!getSyntaxId().equals(doc.getSyntaxId())) { return false; } if (!getxWikiClass().equals(doc.getxWikiClass())) { return false; } Set<String> myObjectClassnames = getxWikiObjects().keySet(); Set<String> otherObjectClassnames = doc.getxWikiObjects().keySet(); if (!myObjectClassnames.equals(otherObjectClassnames)) { return false; } for (String name : myObjectClassnames) { Vector<BaseObject> myObjects = getObjects(name); Vector<BaseObject> otherObjects = doc.getObjects(name); if (myObjects.size() != otherObjects.size()) { return false; } for (int i = 0; i < myObjects.size(); i++) { if ((myObjects.get(i) == null) && (otherObjects.get(i) != null)) { return false; } if (!myObjects.get(i).equals(otherObjects.get(i))) { return false; } } } // We consider that 2 documents are still equal even when they have different original // documents (see getOriginalDocument() for more details as to what is an original // document). return true; } public String toXML(Document doc, XWikiContext context) { OutputFormat outputFormat = new OutputFormat("", true); if ((context == null) || (context.getWiki() == null)) { outputFormat.setEncoding("UTF-8"); } else { outputFormat.setEncoding(context.getWiki().getEncoding()); } StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String getXMLContent(XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(context); Document doc = tdoc.toXMLDocument(true, true, false, false, context); return toXML(doc, context); } public String toXML(XWikiContext context) throws XWikiException { Document doc = toXMLDocument(context); return toXML(doc, context); } public String toFullXML(XWikiContext context) throws XWikiException { return toXML(true, false, true, true, context); } public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException { try { String zipname = getSpace() + "/" + getName(); String language = getLanguage(); if ((language != null) && (!language.equals(""))) { zipname += "." + language; } ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); zos.write(toXML(true, false, true, withVersions, context).getBytes()); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException { addToZip(zos, true, context); } public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = toXMLDocument(bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context); return toXML(doc, context); } public Document toXMLDocument(XWikiContext context) throws XWikiException { return toXMLDocument(true, false, false, false, context); } public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = new DOMDocument(); Element docel = new DOMElement("xwikidoc"); doc.setRootElement(docel); Element el = new DOMElement("web"); el.addText(getSpace()); docel.add(el); el = new DOMElement("name"); el.addText(getName()); docel.add(el); el = new DOMElement("language"); el.addText(getLanguage()); docel.add(el); el = new DOMElement("defaultLanguage"); el.addText(getDefaultLanguage()); docel.add(el); el = new DOMElement("translation"); el.addText("" + getTranslation()); docel.add(el); el = new DOMElement("parent"); el.addText(getParent()); docel.add(el); el = new DOMElement("creator"); el.addText(getCreator()); docel.add(el); el = new DOMElement("author"); el.addText(getAuthor()); docel.add(el); el = new DOMElement("customClass"); el.addText(getCustomClass()); docel.add(el); el = new DOMElement("contentAuthor"); el.addText(getContentAuthor()); docel.add(el); long d = getCreationDate().getTime(); el = new DOMElement("creationDate"); el.addText("" + d); docel.add(el); d = getDate().getTime(); el = new DOMElement("date"); el.addText("" + d); docel.add(el); d = getContentUpdateDate().getTime(); el = new DOMElement("contentUpdateDate"); el.addText("" + d); docel.add(el); el = new DOMElement("version"); el.addText(getVersion()); docel.add(el); el = new DOMElement("title"); el.addText(getTitle()); docel.add(el); el = new DOMElement("template"); el.addText(getTemplate()); docel.add(el); el = new DOMElement("defaultTemplate"); el.addText(getDefaultTemplate()); docel.add(el); el = new DOMElement("validationScript"); el.addText(getValidationScript()); docel.add(el); el = new DOMElement("comment"); el.addText(getComment()); docel.add(el); el = new DOMElement("minorEdit"); el.addText(String.valueOf(isMinorEdit())); docel.add(el); el = new DOMElement("syntaxId"); el.addText(getSyntaxId()); docel.add(el); for (XWikiAttachment attach : getAttachmentList()) { docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context)); } if (bWithObjects) { // Add Class BaseClass bclass = getxWikiClass(); if (bclass.getFieldList().size() > 0) { // If the class has fields, add class definition and field information to XML docel.add(bclass.toXML(null)); } // Add Objects (THEIR ORDER IS MOLDED IN STONE!) for (Vector<BaseObject> objects : getxWikiObjects().values()) { for (BaseObject obj : objects) { if (obj != null) { BaseClass objclass = null; if (StringUtils.equals(getFullName(), obj.getClassName())) { objclass = bclass; } else { objclass = obj.getxWikiClass(context); } docel.add(obj.toXML(objclass)); } } } } // Add Content el = new DOMElement("content"); // Filter filter = new CharacterFilter(); // String newcontent = filter.process(getContent()); // String newcontent = encodedXMLStringAsUTF8(getContent()); String newcontent = this.content; el.addText(newcontent); docel.add(el); if (bWithRendering) { el = new DOMElement("renderedcontent"); try { el.addText(getRenderedContent(context)); } catch (XWikiException e) { el.addText("Exception with rendering content: " + e.getFullMessage()); } docel.add(el); } if (bWithVersions) { el = new DOMElement("versions"); try { el.addText(getDocumentArchive(context).getArchive(context)); docel.add(el); } catch (XWikiException e) { log.error("Document [" + this.getFullName() + "] has malformed history"); } } return doc; } protected String encodedXMLStringAsUTF8(String xmlString) { if (xmlString == null) { return ""; } int length = xmlString.length(); char character; StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { character = xmlString.charAt(i); switch (character) { case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '\n': result.append("\n"); break; case '\r': result.append("\r"); break; case '\t': result.append("\t"); break; default: if (character < 0x20) { } else if (character > 0x7F) { result.append("& result.append(Integer.toHexString(character).toUpperCase()); result.append(";"); } else { result.append(character); } break; } } return result.toString(); } protected String getElement(Element docel, String name) { Element el = docel.element(name); if (el == null) { return ""; } else { return el.getText(); } } public void fromXML(String xml) throws XWikiException { fromXML(xml, false); } public void fromXML(InputStream is) throws XWikiException { fromXML(is, false); } public void fromXML(String xml, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { StringReader in = new StringReader(xml); domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(InputStream in, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(Document domdoc, boolean withArchive) throws XWikiException { Element docel = domdoc.getRootElement(); setName(getElement(docel, "name")); setSpace(getElement(docel, "web")); setParent(getElement(docel, "parent")); setCreator(getElement(docel, "creator")); setAuthor(getElement(docel, "author")); setCustomClass(getElement(docel, "customClass")); setContentAuthor(getElement(docel, "contentAuthor")); if (docel.element("version") != null) { setVersion(getElement(docel, "version")); } setContent(getElement(docel, "content")); setLanguage(getElement(docel, "language")); setDefaultLanguage(getElement(docel, "defaultLanguage")); setTitle(getElement(docel, "title")); setDefaultTemplate(getElement(docel, "defaultTemplate")); setValidationScript(getElement(docel, "validationScript")); setComment(getElement(docel, "comment")); String minorEdit = getElement(docel, "minorEdit"); setMinorEdit(Boolean.valueOf(minorEdit).booleanValue()); String strans = getElement(docel, "translation"); if ((strans == null) || strans.equals("")) { setTranslation(0); } else { setTranslation(Integer.parseInt(strans)); } String archive = getElement(docel, "versions"); if (withArchive && archive != null && archive.length() > 0) { setDocumentArchive(archive); } String sdate = getElement(docel, "date"); if (!sdate.equals("")) { Date date = new Date(Long.parseLong(sdate)); setDate(date); } String scdate = getElement(docel, "creationDate"); if (!scdate.equals("")) { Date cdate = new Date(Long.parseLong(scdate)); setCreationDate(cdate); } String syntaxId = getElement(docel, "syntaxId"); if ((syntaxId == null) || (syntaxId.length() == 0)) { setSyntaxId("xwiki/1.0"); } else { setSyntaxId(syntaxId); } List atels = docel.elements("attachment"); for (int i = 0; i < atels.size(); i++) { Element atel = (Element) atels.get(i); XWikiAttachment attach = new XWikiAttachment(); attach.setDoc(this); attach.fromXML(atel); getAttachmentList().add(attach); } Element cel = docel.element("class"); BaseClass bclass = new BaseClass(); if (cel != null) { bclass.fromXML(cel); setxWikiClass(bclass); } List objels = docel.elements("object"); for (int i = 0; i < objels.size(); i++) { Element objel = (Element) objels.get(i); BaseObject bobject = new BaseObject(); bobject.fromXML(objel); addObject(bobject.getClassName(), bobject); } // We have been reading from XML so the document does not need a new version when saved setMetaDataDirty(false); setContentDirty(false); // Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to // have an original document for a de-serialized object. } /** * Check if provided xml document is a wiki document. * * @param domdoc the xml document. * @return true if provided xml document is a wiki document. */ public static boolean containsXMLWikiDocument(Document domdoc) { return domdoc.getRootElement().getName().equals("xwikidoc"); } public void setAttachmentList(List<XWikiAttachment> list) { this.attachmentList = list; } public List<XWikiAttachment> getAttachmentList() { return this.attachmentList; } public void saveAllAttachments(XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), context); } } public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), updateParent, transaction, context); } } public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { saveAttachmentContent(attachment, true, true, context); } protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } // We need to make sure there is a version upgrade setMetaDataDirty(true); context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context, bTransaction); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true); } finally { if (database != null) { context.setDatabase(database); } } } public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException { deleteAttachment(attachment, true, context); } public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } try { // We need to make sure there is a version upgrade setMetaDataDirty(true); if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) { context.getWiki().getAttachmentRecycleBinStore().saveToRecycleBin(attachment, context.getUser(), new Date(), context, true); } context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } } finally { if (database != null) { context.setDatabase(database); } } } public List getBacklinks(XWikiContext context) throws XWikiException { return getStore(context).loadBacklinks(getFullName(), context, true); } public List getLinks(XWikiContext context) throws XWikiException { return getStore(context).loadLinks(getId(), context, true); } public void renameProperties(String className, Map fieldsToRename) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return; } for (BaseObject bobject : objects) { if (bobject == null) { continue; } for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) { String origname = (String) renameit.next(); String newname = (String) fieldsToRename.get(origname); BaseProperty origprop = (BaseProperty) bobject.safeget(origname); if (origprop != null) { BaseProperty prop = (BaseProperty) origprop.clone(); bobject.removeField(origname); prop.setName(newname); bobject.addField(newname, prop); } } } setContentDirty(true); } public void addObjectsToRemove(BaseObject object) { getObjectsToRemove().add(object); setContentDirty(true); } public ArrayList<BaseObject> getObjectsToRemove() { return this.objectsToRemove; } public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove) { this.objectsToRemove = objectsToRemove; setContentDirty(true); } public List<String> getIncludedPages(XWikiContext context) { if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { return getIncludedPagesForXWiki10Syntax(context); } else { // Find all include macros listed on the page XDOM dom; try { Parser parser = (Parser) Utils.getComponent(Parser.ROLE, getSyntaxId()); dom = parser.parse(new StringReader(getContent())); } catch (Exception e) { log.error("Failed to find included pages for [" + getFullName() + "]", e); return Collections.EMPTY_LIST; } List<String> result = new ArrayList<String>(); for (MacroBlock macroBlock : dom.getChildrenByType(MacroBlock.class, true)) { if (macroBlock.getName().equalsIgnoreCase("include")) { String documentName = macroBlock.getParameters().get("document"); if (documentName.indexOf(".") == -1) { documentName = getSpace() + "." + documentName; } result.add(documentName); } } return result; } } private List<String> getIncludedPagesForXWiki10Syntax(XWikiContext context) { try { String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)"; List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 2); for (int i = 0; i < list.size(); i++) { try { String name = list.get(i); if (name.indexOf(".") == -1) { list.set(i, getSpace() + "." + name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return list; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public List<String> getIncludedMacros(XWikiContext context) { return context.getWiki().getIncludedMacros(getSpace(), getContent(), context); } public List<String> getLinkedPages(XWikiContext context) { try { String pattern = "\\[(.*?)\\]"; List<String> newlist = new ArrayList<String>(); List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 1); for (String name : list) { try { int i1 = name.indexOf(">"); if (i1 != -1) { name = name.substring(i1 + 1); } i1 = name.indexOf("&gt;"); if (i1 != -1) { name = name.substring(i1 + 4); } i1 = name.indexOf(" if (i1 != -1) { name = name.substring(0, i1); } i1 = name.indexOf("?"); if (i1 != -1) { name = name.substring(0, i1); } // Let's get rid of anything that's not a real link if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf(": || (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1) || (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) { continue; } // generate the link String newname = StringUtils.replace(Util.noaccents(name), " ", ""); // If it is a local link let's add the space if (newname.indexOf(".") == -1) { newname = getSpace() + "." + name; } if (context.getWiki().exists(newname, context)) { name = newname; } else { // If it is a local link let's add the space if (name.indexOf(".") == -1) { name = getSpace() + "." + name; } } // Let's finally ignore the autolinks if (!name.equals(getFullName())) { newlist.add(name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return newlist; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) throws XWikiException { String result = pclass.displayView(pclass.getName(), prefix, object, context); return getRenderedContent(result, context); } public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context); } public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context); } public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context); } public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context) { return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context); } public XWikiAttachment getAttachment(String filename) { for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().equals(filename)) { return attach; } } for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().startsWith(filename + ".")) { return attach; } } return null; } public BaseObject getFirstObject(String fieldname) { // Keeping this function with context null for compatibilit reasons // It should not be used, since it would miss properties which are only defined in the class // and not present in the object because the object was not updated return getFirstObject(fieldname, null); } public BaseObject getFirstObject(String fieldname, XWikiContext context) { Collection<Vector<BaseObject>> objectscoll = getxWikiObjects().values(); if (objectscoll == null) { return null; } for (Vector<BaseObject> objects : objectscoll) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); if (bclass != null) { Set set = bclass.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } Set set = obj.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } } } return null; } public void setProperty(String className, String fieldName, BaseProperty value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.safeput(fieldName, value); setContentDirty(true); } public int getIntValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getIntValue(fieldName); } public long getLongValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getLongValue(fieldName); } public String getStringValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return ""; } String result = obj.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public int getIntValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getIntValue(fieldName); } } public long getLongValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getLongValue(fieldName); } } public String getStringValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return ""; } String result = object.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public void setStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringValue(fieldName, value); setContentDirty(true); } public List getListValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return new ArrayList(); } return obj.getListValue(fieldName); } public List getListValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return new ArrayList(); } return object.getListValue(fieldName); } public void setStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringListValue(fieldName, value); setContentDirty(true); } public void setDBStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setDBStringListValue(fieldName, value); setContentDirty(true); } public void setLargeStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setLargeStringValue(fieldName, value); setContentDirty(true); } public void setIntValue(String className, String fieldName, int value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setIntValue(fieldName, value); setContentDirty(true); } public String getDatabase() { return this.database; } public void setDatabase(String database) { this.database = database; } public void setFullName(String fullname, XWikiContext context) { if (fullname == null) { return; } int i0 = fullname.lastIndexOf(":"); int i1 = fullname.lastIndexOf("."); if (i0 != -1) { setDatabase(fullname.substring(0, i0)); setSpace(fullname.substring(i0 + 1, i1)); setName(fullname.substring(i1 + 1)); } else { if (i1 == -1) { try { setSpace(context.getDoc().getSpace()); } catch (Exception e) { setSpace("XWiki"); } setName(fullname); } else { setSpace(fullname.substring(0, i1)); setName(fullname.substring(i1 + 1)); } } if (getName().equals("")) { setName("WebHome"); } setContentDirty(true); } public String getLanguage() { if (this.language == null) { return ""; } else { return this.language.trim(); } } public void setLanguage(String language) { this.language = language; } public String getDefaultLanguage() { if (this.defaultLanguage == null) { return ""; } else { return this.defaultLanguage.trim(); } } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; setMetaDataDirty(true); } public int getTranslation() { return this.translation; } public void setTranslation(int translation) { this.translation = translation; setMetaDataDirty(true); } public String getTranslatedContent(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedContent(language, context); } public String getTranslatedContent(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(language, context); String rev = (String) context.get("rev"); if ((rev == null) || (rev.length() == 0)) { return tdoc.getContent(); } XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context); return cdoc.getContent(); } public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedDocument(language, context); } public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = this; if (!((language == null) || (language.equals("")) || language.equals(this.defaultLanguage))) { tdoc = new XWikiDocument(getSpace(), getName()); tdoc.setLanguage(language); String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } tdoc = getStore(context).loadXWikiDoc(tdoc, context); if (tdoc.isNew()) { tdoc = this; } } catch (Exception e) { tdoc = this; } finally { context.setDatabase(database); } } return tdoc; } public String getRealLanguage(XWikiContext context) throws XWikiException { return getRealLanguage(); } public String getRealLanguage() { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public List<String> getTranslationList(XWikiContext context) throws XWikiException { return getStore().getTranslationList(this, context); } public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)), ToString.stringToArray(toDoc .toXML(context)))); } public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()), ToString.stringToArray(toDoc .getContent()))); } public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getContentDiff(fromDoc, toDoc, context); } public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getContentDiff(revdoc, this, context); } public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException { Version version = getRCSVersion(); try { String prev = getDocumentArchive(context).getPrevVersion(version).toString(); XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context); return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()), ToString .stringToArray(getContent()))); } catch (Exception ex) { log.debug("Exception getting differences from previous version: " + ex.getMessage()); } return new ArrayList<Delta>(); } public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { String originalContent, newContent; originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context); newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context); return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent))); } public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getRenderedContentDiff(fromDoc, toDoc, context); } public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getRenderedContentDiff(revdoc, this, context); } protected List<Delta> getDeltas(Revision rev) { List<Delta> list = new ArrayList<Delta>(); for (int i = 0; i < rev.size(); i++) { list.add(rev.getDelta(i)); } return list; } public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getMetaDataDiff(fromDoc, toDoc, context); } public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getMetaDataDiff(revdoc, this, context); } public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<MetaDataDiff> list = new ArrayList<MetaDataDiff>(); if ((fromDoc == null) || (toDoc == null)) { return list; } if (!fromDoc.getParent().equals(toDoc.getParent())) { list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent())); } if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) { list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor())); } if (!fromDoc.getSpace().equals(toDoc.getSpace())) { list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace())); } if (!fromDoc.getName().equals(toDoc.getName())) { list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName())); } if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) { list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage())); } if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) { list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage())); } return list; } public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getObjectDiff(fromDoc, toDoc, context); } public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getObjectDiff(revdoc, this, context); } /** * Return the object differences between two document versions. There is no hard requirement on the order of the two * versions, but the results are semantically correct only if the two versions are given in the right order. * * @param fromDoc The old ('before') version of the document. * @param toDoc The new ('after') version of the document. * @param context The {@link com.xpn.xwiki.XWikiContext context}. * @return The object differences. The returned list's elements are other lists, one for each changed object. The * inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object. * Additionally, if the object was added or removed, then the first entry in the list will be an * "object-added" or "object-removed" marker. * @throws XWikiException If there's an error computing the differences. */ public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); // Since objects could have been deleted or added, we iterate on both the old and the new // object collections. // First, iterate over the old objects. for (Vector<BaseObject> objects : fromDoc.getxWikiObjects().values()) { for (BaseObject originalObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (originalObj != null) { BaseObject newObj = toDoc.getObject(originalObj.getClassName(), originalObj.getNumber()); List<ObjectDiff> dlist; if (newObj == null) { // The object was deleted. dlist = new BaseObject().getDiff(originalObj, context); ObjectDiff deleteMarker = new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), "object-removed", "", "", ""); dlist.add(0, deleteMarker); } else { // The object exists in both versions, but might have been changed. dlist = newObj.getDiff(originalObj, context); } if (dlist.size() > 0) { difflist.add(dlist); } } } } // Second, iterate over the objects which are only in the new version. for (Vector<BaseObject> objects : toDoc.getxWikiObjects().values()) { for (BaseObject newObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (newObj != null) { BaseObject originalObj = fromDoc.getObject(newObj.getClassName(), newObj.getNumber()); if (originalObj == null) { // Only consider added objects, the other case was treated above. originalObj = new BaseObject(); originalObj.setClassName(newObj.getClassName()); originalObj.setNumber(newObj.getNumber()); List<ObjectDiff> dlist = newObj.getDiff(originalObj, context); ObjectDiff addMarker = new ObjectDiff(newObj.getClassName(), newObj.getNumber(), "object-added", "", "", ""); dlist.add(0, addMarker); if (dlist.size() > 0) { difflist.add(dlist); } } } } } return difflist; } public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); BaseClass oldClass = fromDoc.getxWikiClass(); BaseClass newClass = toDoc.getxWikiClass(); if ((newClass == null) && (oldClass == null)) { return difflist; } List<ObjectDiff> dlist = newClass.getDiff(oldClass, context); if (dlist.size() > 0) { difflist.add(dlist); } return difflist; } /** * @param fromDoc * @param toDoc * @param context * @return * @throws XWikiException */ public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>(); for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) { String fileName = origAttach.getFilename(); XWikiAttachment newAttach = toDoc.getAttachment(fileName); if (newAttach == null) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null)); } else { if (!origAttach.getVersion().equals(newAttach.getVersion())) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion())); } } } for (XWikiAttachment newAttach : toDoc.getAttachmentList()) { String fileName = newAttach.getFilename(); XWikiAttachment origAttach = fromDoc.getAttachment(fileName); if (origAttach == null) { difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion())); } } return difflist; } /** * Rename the current document and all the backlinks leading to it. See * {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details. * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, XWikiContext context) throws XWikiException { rename(newDocumentName, getBacklinks(context), context); } /** * Rename the current document and all the links pointing to it in the list of passed backlink documents. The * renaming algorithm takes into account the fact that there are several ways to write a link to a given page and * all those forms need to be renamed. For example the following links all point to the same page: * <ul> * <li>[Page]</li> * <li>[Page?param=1]</li> * <li>[currentwiki:Page]</li> * <li>[CurrentSpace.Page]</li> * </ul> * <p> * Note: links without a space are renamed with the space added. * </p> * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the * new renamed document. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context) throws XWikiException { // TODO: Do all this in a single DB transaction as otherwise the state will be unknown if // something fails in the middle... if (isNew()) { return; } // This link handler recognizes that 2 links are the same when they point to the same // document (regardless of query string, target or alias). It keeps the query string, // target and alias from the link being replaced. RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler(); // Transform string representation of old and new links so that they can be manipulated. Link oldLink = new LinkParser().parse(getFullName()); Link newLink = new LinkParser().parse(newDocumentName); // Verify if the user is trying to rename to the same name... In that case, simply exits // for efficiency. if (linkHandler.compare(newLink, oldLink)) { return; } // Step 1: Copy the document and all its translations under a new name context.getWiki().copyDocument(getFullName(), newDocumentName, false, context); // Step 2: For each backlink to rename, parse the backlink document and replace the links // with the new name. // Note: we ignore invalid links here. Invalid links should be shown to the user so // that they fix them but the rename feature ignores them. DocumentParser documentParser = new DocumentParser(); for (String backlinkDocumentName : backlinkDocumentNames) { XWikiDocument backlinkDocument = context.getWiki().getDocument(backlinkDocumentName, context); // Note: Here we cannot do a simple search/replace as there are several ways to point // to the same document. For example [Page], [Page?param=1], [currentwiki:Page], // [CurrentSpace.Page] all point to the same document. Thus we have to parse the links // to recognize them and do the replace. ReplacementResultCollection result = documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler, getSpace()); backlinkDocument.setContent((String) result.getModifiedContent()); context.getWiki() .saveDocument( backlinkDocument, context.getMessageTool().get("core.comment.renameLink", Arrays.asList(new String[] {newDocumentName})), true, context); } // Step 3: Delete the old document context.getWiki().deleteDocument(this, context); // Step 4: The current document needs to point to the renamed document as otherwise it's // pointing to an invalid XWikiDocument object as it's been deleted... clone(context.getWiki().getDocument(newDocumentName, context)); } public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException { String oldname = getFullName(); loadAttachments(context); loadArchive(context); /* * if (oldname.equals(docname)) return this; */ XWikiDocument newdoc = (XWikiDocument) clone(); newdoc.setFullName(newDocumentName, context); newdoc.setContentDirty(true); newdoc.getxWikiClass().setName(newDocumentName); Vector<BaseObject> objects = newdoc.getObjects(oldname); if (objects != null) { for (BaseObject object : objects) { object.setName(newDocumentName); } } XWikiDocumentArchive archive = newdoc.getDocumentArchive(); if (archive != null) { newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context)); } return newdoc; } public XWikiLock getLock(XWikiContext context) throws XWikiException { XWikiLock theLock = getStore(context).loadLock(getId(), context, true); if (theLock != null) { int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context); if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) { getStore(context).deleteLock(theLock, context, true); theLock = null; } } return theLock; } public void setLock(String userName, XWikiContext context) throws XWikiException { XWikiLock lock = new XWikiLock(getId(), userName); getStore(context).saveLock(lock, context, true); } public void removeLock(XWikiContext context) throws XWikiException { XWikiLock lock = getStore(context).loadLock(getId(), context, true); if (lock != null) { getStore(context).deleteLock(lock, context, true); } } public void insertText(String text, String marker, XWikiContext context) throws XWikiException { setContent(StringUtils.replaceOnce(getContent(), marker, text + marker)); context.getWiki().saveDocument(this, context); } public Object getWikiNode() { return this.wikiNode; } public void setWikiNode(Object wikiNode) { this.wikiNode = wikiNode; } public String getxWikiClassXML() { return this.xWikiClassXML; } public void setxWikiClassXML(String xWikiClassXML) { this.xWikiClassXML = xWikiClassXML; } public int getElements() { return this.elements; } public void setElements(int elements) { this.elements = elements; } public void setElement(int element, boolean toggle) { if (toggle) { this.elements = this.elements | element; } else { this.elements = this.elements & (~element); } } public boolean hasElement(int element) { return ((this.elements & element) == element); } public String getDefaultEditURL(XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); if (getContent().indexOf("includeForm(") != -1) { return getEditURL("inline", "", context); } else { String editor = xwiki.getEditorPreference(context); return getEditURL("edit", editor, context); } } public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); String language = ""; XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); String realLang = tdoc.getRealLanguage(context); if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) { language = realLang; } return getEditURL(action, mode, language, context); } public String getEditURL(String action, String mode, String language, XWikiContext context) { StringBuffer editparams = new StringBuffer(); if (!mode.equals("")) { editparams.append("xpage="); editparams.append(mode); } if (!language.equals("")) { if (!mode.equals("")) { editparams.append("&"); } editparams.append("language="); editparams.append(language); } return getURL(action, editparams.toString(), context); } public String getDefaultTemplate() { if (this.defaultTemplate == null) { return ""; } else { return this.defaultTemplate; } } public void setDefaultTemplate(String defaultTemplate) { this.defaultTemplate = defaultTemplate; setMetaDataDirty(true); } public Vector<BaseObject> getComments() { return getComments(true); } /** * {@inheritDoc} * * @see org.xwiki.bridge.DocumentModelBridge#getSyntaxId() */ public String getSyntaxId() { String result; if ((this.syntaxId == null) || (this.syntaxId.length() == 0)) { result = "xwiki/1.0"; } else { result = this.syntaxId; } return result; } /** * @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc) * @see #getSyntaxId() */ public void setSyntaxId(String syntaxId) { this.syntaxId = syntaxId; } public Vector<BaseObject> getComments(boolean asc) { if (asc) { return getObjects("XWiki.XWikiComments"); } else { Vector<BaseObject> list = getObjects("XWiki.XWikiComments"); if (list == null) { return list; } Vector<BaseObject> newlist = new Vector<BaseObject>(); for (int i = list.size() - 1; i >= 0; i newlist.add(list.get(i)); } return newlist; } } public boolean isCurrentUserCreator(XWikiContext context) { return isCreator(context.getUser()); } public boolean isCreator(String username) { if (username.equals("XWiki.XWikiGuest")) { return false; } return username.equals(getCreator()); } public boolean isCurrentUserPage(XWikiContext context) { String username = context.getUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public boolean isCurrentLocalUserPage(XWikiContext context) { String username = context.getLocalUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(getFullName(), context); if (hasVersioning) { getVersioningStore(context).resetRCSArchive(this, true, context); } } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException { // Read info in object ObjectAddForm form = new ObjectAddForm(); form.setRequest((HttpServletRequest) context.getRequest()); form.readRequest(); String className = form.getClassName(); int nb = createNewObject(className, context); BaseObject oldobject = getObject(className, nb); BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(form.getObject(className), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", 0, context); } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, prefix, 0, context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(addObjectFromRequest(className, pref, num, context)); } } } return objects; } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", num, context); } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb = createNewObject(className, context); BaseObject oldobject = getObject(className, nb); BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + num), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, "", context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, prefix, 0, context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb; BaseObject oldobject = getObject(className, num); if (oldobject == null) { nb = createNewObject(className, context); oldobject = getObject(className, nb); } else { nb = oldobject.getNumber(); } BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public List updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(updateObjectFromRequest(className, pref, num, context)); } } } return objects; } public boolean isAdvancedContent() { String[] matches = {"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content", "/* Programmatic content */", "## Programmatic content"}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } if (HTML_TAG_PATTERN.matcher(content2).find()) { return true; } return false; } public boolean isProgrammaticContent() { String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()", "$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content", "$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup", "$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } return false; } public boolean removeObject(BaseObject bobj) { Vector<BaseObject> objects = getObjects(bobj.getClassName()); if (objects == null) { return false; } if (objects.elementAt(bobj.getNumber()) == null) { return false; } objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); return true; } /** * Remove all the objects of a given type (XClass) from the document. * * @param className The class name of the objects to be removed. */ public boolean removeObjects(String className) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return false; } Iterator<BaseObject> it = objects.iterator(); while (it.hasNext()) { BaseObject bobj = it.next(); if (bobj != null) { objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); } } return true; } /** * @return the sections in the current document */ public List<DocumentSection> getSections() { return getSplitSectionsAccordingToTitle(); } /** * This method to split section according to title. * * @return the sections in the current document * @throws XWikiException * @deprecated use {@link #getSections()} instead, since 1.6M1 */ @Deprecated public List<DocumentSection> getSplitSectionsAccordingToTitle() { // Pattern to match the title. Matches only level 1 and level 2 headings. Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE); Matcher matcher = headingPattern.matcher(getContent()); List<DocumentSection> splitSections = new ArrayList<DocumentSection>(); int sectionNumber = 0; // find title to split while (matcher.find()) { ++sectionNumber; String sectionLevel = matcher.group(1); String sectionTitle = matcher.group(3); int sectionIndex = matcher.start(); // Initialize a documentSection object. DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle); // Add the document section to list. splitSections.add(docSection); } return splitSections; } // This function to return a Document section with parameter is sectionNumber public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException { // return a document section according to section number return getSplitSectionsAccordingToTitle().get(sectionNumber - 1); } // This method to return the content of a section public String getContentOfSection(int sectionNumber) throws XWikiException { List<DocumentSection> splitSections = getSplitSectionsAccordingToTitle(); int indexEnd = 0; // get current section DocumentSection section = splitSections.get(sectionNumber - 1); int indexStart = section.getSectionIndex(); String sectionLevel = section.getSectionLevel(); // Determine where this section ends, which is at the start of the next section of the // same or a higher level. for (int i = sectionNumber; i < splitSections.size(); i++) { DocumentSection nextSection = splitSections.get(i); String nextLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) { indexEnd = nextSection.getSectionIndex(); break; } } String sectionContent = null; if (indexStart < 0) { indexStart = 0; } if (indexEnd == 0) { sectionContent = getContent().substring(indexStart); } else { sectionContent = getContent().substring(indexStart, indexEnd); } return sectionContent; } // This function to update a section content in document public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException { StringBuffer newContent = new StringBuffer(); // get document section that will be edited DocumentSection docSection = getDocumentSection(sectionNumber); int numberOfSections = getSplitSectionsAccordingToTitle().size(); int indexSection = docSection.getSectionIndex(); if (numberOfSections == 1) { // there is only a sections in document String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else if (sectionNumber == numberOfSections) { // edit lastest section that doesn't contain subtitle String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else { String sectionLevel = docSection.getSectionLevel(); int nextSectionIndex = 0; // get index of next section for (int i = sectionNumber; i < numberOfSections; i++) { DocumentSection nextSection = getDocumentSection(i + 1); // get next section String nextSectionLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextSectionLevel)) { nextSectionIndex = nextSection.getSectionIndex(); break; } else if (sectionLevel.length() > nextSectionLevel.length()) { nextSectionIndex = nextSection.getSectionIndex(); break; } } if (nextSectionIndex == 0) {// edit the last section newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent); return newContent.toString(); } else { String contentAfter = getContent().substring(nextSectionIndex); String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter); } return newContent.toString(); } } /** * Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO: * cache the hash value, update only on modification. */ public String getVersionHashCode(XWikiContext context) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { log.error("Cannot create MD5 object", ex); return this.hashCode() + ""; } try { String valueBeforeMD5 = toXML(true, false, true, false, context); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception ex) { log.error("Exception while computing document hash", ex); } return this.hashCode() + ""; } public static String getInternalPropertyName(String propname, XWikiContext context) { XWikiMessageTool msg = context.getMessageTool(); String cpropname = StringUtils.capitalize(propname); return (msg == null) ? cpropname : msg.get(cpropname); } public String getInternalProperty(String propname) { String methodName = "get" + StringUtils.capitalize(propname); try { Method method = getClass().getDeclaredMethod(methodName, (Class[]) null); return (String) method.invoke(this, (Object[]) null); } catch (Exception e) { return null; } } public String getCustomClass() { if (this.customClass == null) { return ""; } return this.customClass; } public void setCustomClass(String customClass) { this.customClass = customClass; setMetaDataDirty(true); } public void setValidationScript(String validationScript) { this.validationScript = validationScript; setMetaDataDirty(true); } public String getValidationScript() { if (this.validationScript == null) { return ""; } else { return this.validationScript; } } public String getComment() { if (this.comment == null) { return ""; } return this.comment; } public void setComment(String comment) { this.comment = comment; } public boolean isMinorEdit() { return this.isMinorEdit; } public void setMinorEdit(boolean isMinor) { this.isMinorEdit = isMinor; } // methods for easy table update. It is need only for hibernate. // when hibernate update old database without minorEdit field, hibernate will create field with // null in despite of notnull in hbm. // so minorEdit will be null for old documents. But hibernate can't convert null to boolean. // so we need convert Boolean to boolean protected Boolean getMinorEdit1() { return Boolean.valueOf(this.isMinorEdit); } protected void setMinorEdit1(Boolean isMinor) { this.isMinorEdit = (isMinor != null && isMinor.booleanValue()); } public BaseObject newObject(String classname, XWikiContext context) throws XWikiException { int nb = createNewObject(classname, context); return getObject(classname, nb); } public BaseObject getObject(String classname, boolean create, XWikiContext context) { try { BaseObject obj = getObject(classname); if ((obj == null) && create) { return newObject(classname, context); } if (obj == null) { return null; } else { return obj; } } catch (Exception e) { return null; } } public boolean validate(XWikiContext context) throws XWikiException { return validate(null, context); } public boolean validate(String[] classNames, XWikiContext context) throws XWikiException { boolean isValid = true; if ((classNames == null) || (classNames.length == 0)) { for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = context.getWiki().getClass(classname, context); Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { isValid &= bclass.validateObject(obj, context); } } } } else { for (int i = 0; i < classNames.length; i++) { Vector<BaseObject> objects = getObjects(classNames[i]); if (objects != null) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); isValid &= bclass.validateObject(obj, context); } } } } } String validationScript = ""; XWikiRequest req = context.getRequest(); if (req != null) { validationScript = req.get("xvalidation"); } if ((validationScript == null) || (validationScript.trim().equals(""))) { validationScript = getValidationScript(); } if ((validationScript != null) && (!validationScript.trim().equals(""))) { isValid &= executeValidationScript(context, validationScript); } return isValid; } private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException { try { XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context); return validObject.validateDocument(this, context); } catch (Throwable e) { XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context); return false; } } public static void backupContext(HashMap<String, Object> backup, XWikiContext context) { backup.put("doc", context.getDoc()); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); if (vcontext != null) { backup.put("vdoc", vcontext.get("doc")); backup.put("vcdoc", vcontext.get("cdoc")); backup.put("vtdoc", vcontext.get("tdoc")); } Map gcontext = (Map) context.get("gcontext"); if (gcontext != null) { backup.put("gdoc", gcontext.get("doc")); backup.put("gcdoc", gcontext.get("cdoc")); backup.put("gtdoc", gcontext.get("tdoc")); } } public static void restoreContext(HashMap<String, Object> backup, XWikiContext context) { context.setDoc((XWikiDocument) backup.get("doc")); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { if (backup.get("vdoc") != null) { vcontext.put("doc", backup.get("vdoc")); } if (backup.get("vcdoc") != null) { vcontext.put("cdoc", backup.get("vcdoc")); } if (backup.get("vtdoc") != null) { vcontext.put("tdoc", backup.get("vtdoc")); } } if (gcontext != null) { if (backup.get("gdoc") != null) { gcontext.put("doc", backup.get("gdoc")); } if (backup.get("gcdoc") != null) { gcontext.put("cdoc", backup.get("gcdoc")); } if (backup.get("gtdoc") != null) { gcontext.put("tdoc", backup.get("gtdoc")); } } } public void setAsContextDoc(XWikiContext context) { try { context.setDoc(this); com.xpn.xwiki.api.Document apidoc = this.newDocument(context); com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument(); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { vcontext.put("doc", apidoc); vcontext.put("tdoc", tdoc); } if (gcontext != null) { gcontext.put("doc", apidoc); gcontext.put("tdoc", tdoc); } } catch (XWikiException ex) { log.warn("Unhandled exception setting context", ex); } } public String getPreviousVersion() { return getDocumentArchive().getPrevVersion(this.version).toString(); } @Override public String toString() { return getFullName(); } }
package org.lockss.test; import java.util.*; /** <code>SimpleBinarySemaphore</code> allows one thread to wait for another * thread to complete some operation, with an optional timeout. * The semaphore is initially empty; * <code>give()</code> fills it, <code>take()</code> waits for it to be full, * then empties it and returns. */ public class SimpleBinarySemaphore { private volatile boolean state = false; /** Wait until the semaphore is full. * If the semaphore is already full, return immediately. * Always leaves the semaphore empty. * @return true if <code>take()</code> was successful (semaphore was or * became full), else false (call was interrupted) */ synchronized public boolean take() { while (!state) { try { this.wait(); } catch (InterruptedException e) { if (state) { break; } else { return false; } } } state = false; return true; } /** Wait until the semaphore is full or the timeout elapses. * If the semaphore is already full, return immediately. * Always leaves the semaphore empty. * @param timeout maximum milliseconds to wait. Zero causes immediate * return (<code>true</code> iff semaphore was already full). * @return true if <code>take()</code> was successful (semaphore was or * became full), else false (timeout elapsed or call was interrupted). */ synchronized public boolean take(long timeout) { long expMS = System.currentTimeMillis() + timeout; while (!state) { long nowMS = System.currentTimeMillis(); if (nowMS >= expMS) { break; } try { this.wait(expMS - nowMS); } catch (InterruptedException e) { break; } } if (state) { state = false; return true; } else { return false; } } /** Fill the semaphore. If another thread is waiting for the * semaphore to be full, it will proceed. If multiple threads are waiting, * one of them will proceed. */ synchronized public void give() { state = true; this.notifyAll(); } }
package jcavern; import java.util.*; import java.awt.Rectangle; /** * a World is a rectangular grid of Locations, some of which contain Things. * * @author Bill Walker * @version $Id$ */ public class World extends Observable { /** * The usual fraction of trees in the world. */ private static final double kTreeFraction = 17.0 / 100.0; /** * The usual fraction of castles in the world. */ private static final double kCastleFraction = 0.4 / 100.0; /** * The bounds of the world */ private static final Rectangle kBounds = new Rectangle(21, 21); /** * A dictionary mapping from locations to things */ private Hashtable mLocationsToThings; /** * A dictionary mapping from things to their locations */ private Hashtable mThingsToLocations; /** * Creates a new, empty world. */ public World() { removeAll(); } /** * Empties out the dictionaries that map things to locations and locations to things. */ public void removeAll() { mLocationsToThings = new Hashtable(); mThingsToLocations = new Hashtable(); } public void populateFor(Player aPlayer) throws JCavernInternalError { try { // Remove all the stuff from the World removeAll(); // Get rid of that pesky castle the player is probably carrying aPlayer.setCastle(null); // Place trees placeRandomTrees(); // Place castles int castles = placeRandomCastles(); // Place treasure chests placeRandomTreasureChests(aPlayer); // Place monsters // orignally: Num_Monster := 3*Mis_quota + 2*Random(Mis_Quota); int quota = aPlayer.getMission().getQuota(); int desiredPopulation = (int) (3 * quota + 2 * Math.random() * quota); placeRandom(aPlayer.getMission().getTarget(), quota); placeWorthyOpponents(aPlayer, desiredPopulation - quota); // Put the player in the world place(getRandomEmptyLocation(), aPlayer); JCavernApplet.current().log("You will have " + castles + " magic castles to help you"); } catch (ThingCollisionException tce) { throw new JCavernInternalError("trouble creating a world " + tce); } } /** * Places random trees using the default fraction. */ public int placeRandomTrees() throws ThingCollisionException { return placeRandom(new Tree(), kTreeFraction); } /** * Places random trees using the default fraction. */ public int placeRandomCastles() throws ThingCollisionException { return placeRandom(new Castle(), kCastleFraction); } /** * Places random TreasureChests. The number of TreasureChests is based on the * number of monsters to be killed in the given Players mission quota. */ public int placeRandomTreasureChests(Player aPlayer) throws ThingCollisionException { int chestCount = aPlayer.getMission().getQuota() / 2; System.out.println("Place " + chestCount + " Random Treasure Chests"); for (int index = 0; index < chestCount; index++) { place(getRandomEmptyLocation(), TreasureChest.createRandom()); } return chestCount; } /** * Places random trees according to the fraction passed in. */ public int placeRandom(Thing aThingPrototype, double fraction) throws ThingCollisionException { int numberOfThings = (int) (getBounds().width * getBounds().height * fraction); System.out.println("Place fraction " + fraction + " Random " + aThingPrototype); placeRandom(aThingPrototype, numberOfThings); return numberOfThings; } /** * Places random trees according to the fraction passed in. */ public void placeRandom(Thing aThingPrototype, int numberOfThings) throws ThingCollisionException { System.out.println("Place " + numberOfThings + " Random " + aThingPrototype); for (int index = 0; index < numberOfThings; index++) { place(getRandomEmptyLocation(), (Thing) aThingPrototype.clone()); } } /** * Places appropriate opponents on the board, based on the prowess of the given player. */ public void placeWorthyOpponents(Player aPlayer, int numberOfMonsters) throws ThingCollisionException { System.out.println("Place " + numberOfMonsters + " Worthy Opponents"); for (int index = 0; index < numberOfMonsters; index++) { place(getRandomEmptyLocation(), MonsterFactory.getWorthyOpponent(aPlayer)); } } /** * Returns a random location within the bounds of this world. */ public Location getRandomLocation() { int x = (int) (Math.random() * kBounds.width); int y = (int) (Math.random() * kBounds.height); return new Location(x, y); } /** * Returns a random, empty location within the bounds of this world. */ public Location getRandomEmptyLocation() { Location emptyLocation = getRandomLocation(); while (! isEmpty(emptyLocation)) { emptyLocation = getRandomLocation(); } return emptyLocation; } /** * Returns the bounds of this world. */ public Rectangle getBounds() { return kBounds; } /** * Returns the Thing in the given direction from the given Thing. * The seearch proceeds outward from the given Thing, until it encounters another Thing, * or the edge of the world. */ public Thing getThingToward(Thing attacker, int aDirection) throws JCavernInternalError, IllegalLocationException { //System.out.println("attack(" + attacker + ", " + Location.directionToString(aDirection) + ")"); if (! mThingsToLocations.containsKey(attacker)) { throw new JCavernInternalError("There's no " + attacker + " to attack"); } Location attackerLocation = (Location) mThingsToLocations.get(attacker); Location attackeeLocation = attackerLocation.getNeighbor(aDirection); while (isEmpty(attackeeLocation)) { if (! attackeeLocation.inBounds(kBounds)) { throw new IllegalLocationException("Ranged attack hit nothing"); } JCavernApplet.current().log(attackeeLocation.toString()); attackeeLocation = attackeeLocation.getNeighbor(aDirection); } try { return getThing(attackeeLocation); } catch (EmptyLocationException ele) { throw new JCavernInternalError("World says location isn't empty, but throws EmptyLocationException"); } } public Thing getNeighboring(Location aLocation, Thing aPrototype) throws JCavernInternalError { try { Vector neighbors = aLocation.getNeighbors(); for (int index = 0; index < neighbors.size(); index++) { try { Location neighbor = (Location) neighbors.elementAt(index); if ((! isEmpty(neighbor)) && (getThing(neighbor).getClass().equals(aPrototype.getClass()))) { return getThing(neighbor); } } catch (IllegalLocationException ile) { } } } catch (EmptyLocationException ele) { throw new JCavernInternalError("tried to find neighbors, got unexpected empty location exception " + ele); } throw new IllegalArgumentException("Can't find neighboring " + aPrototype); } /** * Moves the given thing in the given direction. */ public void move(Combatant aThing, int direction) throws ThingCollisionException, JCavernInternalError, IllegalLocationException { if (! mThingsToLocations.containsKey(aThing)) { throw new JCavernInternalError("There's no " + aThing + " in this world to move"); } Location oldLocation = (Location) mThingsToLocations.get(aThing); Location newLocation = oldLocation.getNeighbor(direction); if (! newLocation.inBounds(kBounds)) { throw new IllegalLocationException(aThing + " moved outside the world"); } if (isEmpty(newLocation)) // no collision on move { remove(oldLocation); place(newLocation, aThing); } else // collision on move, find out what's currently there { try { Thing currentOccupant = getThing(newLocation); throw new ThingCollisionException(aThing, currentOccupant, aThing.getName() + " collided with " + currentOccupant.getName()); } catch (EmptyLocationException ele) { throw new JCavernInternalError("World says location isn't empty, but throws EmptyLocationException!"); } } } /** * Finds the direction between two things. */ public int getDirectionToward(Thing aThing, Thing anotherThing) throws JCavernInternalError { if (! mThingsToLocations.containsKey(aThing)) { throw new JCavernInternalError("There's no " + aThing + " in this world"); } if (! mThingsToLocations.containsKey(anotherThing)) { throw new JCavernInternalError("There's no " + anotherThing + " in this world"); } Location location1 = getLocation(aThing); Location location2 = getLocation(anotherThing); return location1.getDirectionToward(location2); } /** * Finds the distance between two things. */ public int getDistanceBetween(Thing aThing, Thing anotherThing) throws JCavernInternalError { if (! mThingsToLocations.containsKey(aThing)) { throw new JCavernInternalError("There's no " + aThing + " in this world"); } if (! mThingsToLocations.containsKey(anotherThing)) { throw new JCavernInternalError("There's no " + anotherThing + " in this world"); } Location location1 = getLocation(aThing); Location location2 = getLocation(anotherThing); return location1.distanceTo(location2); } /** * Retrieves the thing at the given location. */ public Thing getThing(Location aLocation) throws EmptyLocationException, IllegalLocationException { if (mLocationsToThings.containsKey(aLocation)) { return (Thing) mLocationsToThings.get(aLocation); } else if (! aLocation.inBounds(getBounds())) { throw new IllegalLocationException(aLocation + " is not in bounds"); } else { throw new EmptyLocationException("There's nothing at " + aLocation); } } public Player getPlayer() { Enumeration theThings = mThingsToLocations.keys(); while (theThings.hasMoreElements()) { Thing aThing = (Thing) theThings.nextElement(); if (aThing instanceof Player) { return (Player) aThing; } } return null; } public void doTurn() throws JCavernInternalError { Enumeration theThings = mThingsToLocations.keys(); while (theThings.hasMoreElements()) { ((Thing) theThings.nextElement()).doTurn(this); } } /** * Answers whether there is any thing at the given location. */ public boolean isEmpty(Location aLocation) { if (mLocationsToThings.containsKey(aLocation)) { return false; } else { return true; } } /** * Places a Thing at the given location. */ public void place(Location aLocation, Thing aThing) throws ThingCollisionException { if (mLocationsToThings.containsKey(aLocation)) { throw new ThingCollisionException(aThing, "There's already " + aThing + " at " + aLocation); } mLocationsToThings.put(aLocation, aThing); mThingsToLocations.put(aThing, aLocation); setChanged(); notifyObservers(); } /** * Retrieves the location of the given thing. */ public Location getLocation(Thing aThing) throws JCavernInternalError { if (! mThingsToLocations.containsKey(aThing)) { throw new JCavernInternalError("There's no " + aThing + " in this world to locate"); } return (Location) mThingsToLocations.get(aThing); } /** * Remove the thing at the given location from the world. */ public void remove(Location locationToRemove) throws JCavernInternalError { Thing thingToRemove = (Thing) mLocationsToThings.get(locationToRemove); if (thingToRemove == null) { throw new JCavernInternalError("There's no " + thingToRemove + " in this world to remove"); } mLocationsToThings.remove(locationToRemove); mThingsToLocations.remove(thingToRemove); setChanged(); notifyObservers(); } /** * Remove the given thing from the world. */ public void remove(Thing thingToRemove) throws JCavernInternalError { Location locationToRemove = (Location) mThingsToLocations.get(thingToRemove); if (locationToRemove == null) { throw new JCavernInternalError("There's no " + thingToRemove + " in this world to remove"); } mLocationsToThings.remove(locationToRemove); mThingsToLocations.remove(thingToRemove); setChanged(); notifyObservers(); } }
package scalac; import java.io.*; import java.util.*; import scalac.util.*; import scalac.ast.*; import scalac.ast.parser.*; import scalac.symtab.Definitions; import scalac.ast.printer.*; import scalac.backend.Primitives; // !!! <<< Interpreter stuff import scalac.symtab.Kinds; import scalac.symtab.Type; import scalac.symtab.Symbol; import scalac.symtab.Scope; // !!! >>> Interpreter stuff /** The global environment of a compiler run * * @author Matthias Zenger * @version 1.0 */ public class Global { public static Global instance; /** global options */ public final boolean noimports; public final boolean nopredefs; //public final boolean optimize; public final boolean debug; public final boolean uniqid; public final boolean printtypes; public final boolean printtokens; public final String outpath; public final String target; public final String jacoDebug; /** the message reporter */ public final Reporter reporter; /** a stack for maintaining timestamps */ private final Stack startTimes = new Stack(); /** all compilation units */ public Unit[] units; /** the class path */ public final ClassPath classPath; /** the global tree factory */ public final TreeFactory make; /** the fresh name creator */ public final FreshNameCreator freshNameCreator; /** the tree generator */ public final TreeGen treeGen; /** the unique-id generator */ public final UniqueID uniqueID; /** the global tree printer */ public final TreePrinter printer; public OutputStream printStream; public final TreePrinter debugPrinter; /** the current phase */ public PhaseDescriptor currentPhase; /** the global definitions */ public Definitions definitions; /** the global primitives */ public Primitives primitives; /** compilation phases. */ public final PhaseRepository PHASE; public final PhaseDescriptor[] phases; public final int POST_ANALYZER_PHASE_ID = 3; /** compilation targets */ public static final String TARGET_INT; public static final String TARGET_JAVA; public static final String TARGET_JVM; public static final String TARGET_MSIL; public static final String[] TARGETS = new String[] { TARGET_INT = "int".intern(), TARGET_JAVA = "java".intern(), TARGET_JVM = "jvm".intern(), TARGET_MSIL = "msil".intern(), }; /** tree printers */ public static final String PRINTER_TEXT; public static final String PRINTER_HTML; public static final String[] PRINTERS = new String[] { PRINTER_TEXT = "text".intern(), PRINTER_HTML = "html".intern(), }; public Global(CompilerCommand args) { this(args, false); } public Global(CompilerCommand args, boolean interpret) { if (Global.instance != null) { // jaco bug: can't use assert here new Error("Duplicate creation of Global").printStackTrace(); System.exit(1); }; Global.instance = this; this.reporter = args.reporter(); this.start(); // timestamp to compute the total time this.noimports = args.noimports.value; this.nopredefs = args.nopredefs.value; //this.optimize = args.optimize.optimize; this.debug = args.debug.value; this.uniqid = args.uniqid.value; this.printtypes = args.types.value; this.printtokens = args.print.tokens; this.classPath = args.classpath(); this.outpath = args.outpath(); this.target = interpret ? TARGET_INT : args.target.value.intern(); this.jacoDebug = args.jaco.value; this.uniqueID = new UniqueID(); String printFile = args.printfile.value; try { this.printStream = "-".equals(printFile) ? System.out : new FileOutputStream(printFile); } catch (FileNotFoundException e) { error("unable to open file " + printFile + ". Printing on console"); this.printStream = System.out; } String printerName = args.printer.value.intern(); if (printerName == PRINTER_TEXT) this.printer = new TextTreePrinter(printStream); else this.printer = new HTMLTreePrinter(printStream); this.debugPrinter = new TextTreePrinter(System.err, true); this.freshNameCreator = new FreshNameCreator(); this.make = new TreeCreator(); this.currentPhase = PhaseDescriptor.INITIAL; this.definitions = new Definitions(this); this.primitives = new Primitives(this); this.treeGen = new TreeGen(this, make); this.PHASE = args.phases; List phases = new ArrayList(); phases.add(PHASE.INITIAL); phases.add(PHASE.PARSER); phases.add(PHASE.ANALYZER); phases.add(PHASE.REFCHECK); phases.add(PHASE.UNCURRY); /* if (optimize) { phases.add(PHASE.OPTIMIZE); } */ phases.add(PHASE.TRANSMATCH); phases.add(PHASE.LAMBDALIFT); phases.add(PHASE.EXPLICITOUTER); phases.add(PHASE.ADDACCESSORS); phases.add(PHASE.ADDINTERFACES); phases.add(PHASE.EXPANDMIXIN); phases.add(PHASE.ERASURE); if (target == TARGET_INT || target == TARGET_MSIL || target == TARGET_JVM) { phases.add(PHASE.ADDCONSTRUCTORS); } /* if (target == TARGET_JAVA) phases.add(PHASE.GENJAVA); if (target == TARGET_MSIL) phases.add(PHASE.GENMSIL); */ if (target == TARGET_JVM) phases.add(PHASE.GENJVM); phases.add(PHASE.TERMINAL); this.phases = new PhaseDescriptor[phases.size()]; for (int i = 0; i < phases.size(); i++) { PhaseDescriptor phase = (PhaseDescriptor)phases.get(i); this.phases[i] = phase; if (i > 0) this.phases[i - 1].flags |= phase.flags >>> 16; phase.initialize(this, i); assert phase.id == i; } assert PHASE.ANALYZER.id + 1 == POST_ANALYZER_PHASE_ID; } /** Move to next phase */ public void nextPhase() { currentPhase = phases[currentPhase.id + 1]; } /** Move to previous phase */ public void prevPhase() { currentPhase = phases[currentPhase.id - 1]; } /** the top-level compilation process */ public void compile(String[] files, boolean console) { reporter.resetCounters(); // parse files List units = new ArrayList(files.length); for (int i = 0; i < files.length; i++) { String file = files[i]; try { units.add(new Unit(this, new Sourcefile(file), console)); } catch (FileNotFoundException e) { error("file " + file + " not found"); } catch (IOException e) { error(e.toString()); } } this.units = (Unit[])units.toArray(new Unit[units.size()]); compile(); } /** the top-level compilation process */ public void compile(String input, boolean console) { reporter.resetCounters(); Sourcefile source = new Sourcefile(input.getBytes()); units = new Unit[]{new Unit(this, source, console)}; compile(); } /** compile all compilation units */ private void compile() { printer.begin(); // apply successive phases and pray that it works for (int i = 0; i < phases.length && reporter.errors() == 0; ++i) { currentPhase = phases[i]; if ((currentPhase.flags & PhaseDescriptor.SKIP) != 0) { operation("skipping phase " + currentPhase.name()); } else { currentPhase.apply(this); } if ((currentPhase.flags & PhaseDescriptor.PRINT) != 0) currentPhase.print(this); if ((currentPhase.flags & PhaseDescriptor.GRAPH) != 0) currentPhase.graph(this); if ((currentPhase.flags & PhaseDescriptor.CHECK) != 0) currentPhase.check(this); if ((currentPhase.flags & PhaseDescriptor.STOP) != 0) { operation("stopped after phase " + currentPhase.name()); break; } if (currentPhase == PHASE.PARSER) fix1(); if (currentPhase == PHASE.ANALYZER) fix2(); } if (reporter.errors() != 0) imports.clear(); printer.end(); } // !!! <<< Interpreter stuff public static final String CONSOLE_S = "$console$"; private static final Name INTERPRETER_N = Name.fromString("Interpreter"), SCALA_INTERPRETER_N = Name.fromString("scala.Interpreter"), SHOW_DEFINITION_N = Name.fromString("showDefinition"), SHOW_VALUE_DEFINITION_N = Name.fromString("showValueDefinition"), SHOW_VALUE_N = Name.fromString("showValue"); private Symbol INTERPRETER; private Symbol SHOW_VALUE; private Symbol SHOW_DEFINITION; private Symbol SHOW_VALUE_DEFINITION; private Symbol INTERPRETER() { if (INTERPRETER == null) INTERPRETER = definitions.getModule(SCALA_INTERPRETER_N); return INTERPRETER; } private Symbol SHOW_VALUE() { if (SHOW_VALUE == null) SHOW_VALUE = INTERPRETER().lookup(SHOW_VALUE_N); return SHOW_VALUE; } private Symbol SHOW_DEFINITION() { if (SHOW_DEFINITION == null) SHOW_DEFINITION = INTERPRETER().lookup(SHOW_DEFINITION_N); return SHOW_DEFINITION; } private Symbol SHOW_VALUE_DEFINITION() { if (SHOW_VALUE_DEFINITION == null) SHOW_VALUE_DEFINITION = INTERPRETER().lookup(SHOW_VALUE_DEFINITION_N); return SHOW_VALUE_DEFINITION; } private int module = 0; private List imports = new ArrayList(); private void fix1() { for (int i = 0; i < units.length; i++) { if (units[i].console) fix1(units[i]); } for (int i = 0; i < imports.size(); i++) { Symbol module = (Symbol)imports.get(i); PHASE.ANALYZER.addConsoleImport(this, module); } } private void fix1(Unit unit) { // make sure that Interpreter.scala is compiled SHOW_DEFINITION(); unit.body = new Tree[] { make.ModuleDef(0, 0, Name.fromString(CONSOLE_S+module), Tree.Empty, make.Template(0, new Tree[]{ make.Select(0, make.Ident(0, Names.scala), Names.Object.toConstrName())}, unit.body))}; module++; } private void fix2() { for (int i = 0; i < units.length; i++) { if (units[i].console) fix2(units[i]); } } private void fix2(Unit unit) { imports.clear(); for (int i = 0; i < unit.body.length; i++) { switch (unit.body[i]) { case ModuleDef(_, Name name, _, Tree.Template impl): if (!name.toString().startsWith(CONSOLE_S)) break; if (impl.body.length <= 0) break; imports.add(unit.body[i].symbol()); Tree last = impl.body[impl.body.length - 1]; if (last.isTerm()) { impl.body[impl.body.length - 1] = treeGen.Apply( treeGen.Select( treeGen.mkRef(0, INTERPRETER()), SHOW_VALUE()), new Tree[] { last, make.Literal(0, show(last.type())).setType( definitions.JAVA_STRING_TYPE)}); } TreeList body = new TreeList(); for (int j = 0; j < impl.body.length; j++) fix2(body, impl.body[j]); impl.body = body.toArray(); break; } } } private void fix2(TreeList body, Tree tree) { body.append(tree); switch (tree) { case PatDef(_, _, _): // !!! impossible (removed by analyzer) assert false : Debug.show(tree); return; case ClassDef(_, _, _, _, _, _): case PackageDef(_, _): case ModuleDef(_, _, _, _): case DefDef(_, _, _, _, _, _): case TypeDef(_, _,_ ): if (!mustShow(tree.symbol())) return; body.append( treeGen.Apply( treeGen.Select( treeGen.mkRef(0, INTERPRETER()), SHOW_DEFINITION()), new Tree[] { make.Literal(0, show(tree.symbol())).setType( definitions.JAVA_STRING_TYPE)})); return; case ValDef(_, _, _, _): if (!mustShow(tree.symbol())) return; body.append( treeGen.Apply( treeGen.Select( treeGen.mkRef(0, INTERPRETER()), SHOW_VALUE_DEFINITION()), new Tree[] { make.Literal(0, show(tree.symbol())).setType( definitions.JAVA_STRING_TYPE), treeGen.Ident(tree.symbol())})); return; default: return; } } private boolean mustShow(Symbol symbol) { return !symbol.isAccessor(); } private String show(Symbol symbol) { return appendMember(new StringBuffer(), symbol).toString(); } private StringBuffer appendMember(StringBuffer buffer, Symbol symbol) { buffer.append(symbol.defKeyword()).append(' '); String name = symbol.nameString(); int index = name.indexOf('$'); if (index > 0) name = name.substring(0, index); buffer.append(name).append(inner(symbol)); if (symbol.isInitializedMethod()) appendDefInfo(buffer, symbol.info()); else append(buffer, symbol.info()); return buffer; } private String show(Type type) { return append(new StringBuffer(), type).toString(); } private String inner(Symbol symbol) { switch (symbol.kind) { case Kinds.CLASS: return " extends "; case Kinds.ALIAS: return " = "; case Kinds.TYPE : return " <: "; case Kinds.VAL : return symbol.isModule() ? "extends" : symbol.isInitializedMethod() ? "" : ": "; default : throw Debug.abort("illegal case: " + symbol.kind); } } private StringBuffer appendDefInfo(StringBuffer buffer, Type type) { switch (type) { case MethodType(Symbol[] vparams, Type result): append(buffer, Symbol.type(vparams), "(", ",", ")"); return appendDefInfo(buffer, result); case PolyType(Symbol[] tparams, Type result): if (tparams.length == 0) return appendDefInfo(buffer, result); append(buffer, Symbol.type(tparams), "[", ",", "]"); return appendDefInfo(buffer, result); default: buffer.append(": "); return append(buffer, type); } } private StringBuffer appendPrefix(StringBuffer buffer, Type prefix) { if (prefix.isSameAs(definitions.ROOT_TYPE)) return buffer; if (prefix.isSameAs(definitions.SCALA_TYPE)) return buffer; return append(buffer, prefix).append('.'); } private StringBuffer appendSymbol(StringBuffer buffer, Symbol symbol) { return buffer.append(symbol.nameString()); } private StringBuffer append(StringBuffer buffer, Type type) { switch (type) { case ErrorType: return buffer.append("<error>"); case AnyType: return buffer.append("<any type>"); case NoType: return buffer.append("<notype>"); case ThisType(Symbol sym): appendSymbol(buffer, sym); return buffer; case TypeRef(Type pre, Symbol sym, Type[] args): appendPrefix(buffer, pre); appendSymbol(buffer, sym); if (args.length > 0) append(buffer, args, "[", ",", "]"); return buffer; case SingleType(Type pre, Symbol sym): appendPrefix(buffer, pre); appendSymbol(buffer, sym); return buffer; case CompoundType(Type[] parts, Scope members): append(buffer, parts, "", " with ", ""); append(buffer, members.elements(), " {", ", ", "}"); return buffer; case MethodType(Symbol[] vparams, Type result): append(buffer, Symbol.type(vparams), "(", ",", ")"); return append(buffer, result); case PolyType(Symbol[] tparams, Type result): if (tparams.length == 0) return append(buffer, result); append(buffer, Symbol.type(tparams), "[", ",", "]"); return append(buffer, result); case OverloadedType(_, Type[] alttypes): return append(buffer, alttypes, "", " & ", ""); case CovarType(Type tp): return append(buffer.append('+'), tp); case LazyType(): case TypeVar(_, _): case UnboxedType(_): case UnboxedArrayType(_): throw Debug.abort("illegal case", type); default: throw Debug.abort("illegal case", type); } } private StringBuffer append(StringBuffer buffer, Type[] types, String prefix, String infix, String suffix) { buffer.append(prefix); for (int i = 0; i < types.length; i++) append(i > 0 ? buffer.append(infix) : buffer, types[i]); buffer.append(suffix); return buffer; } private StringBuffer append(StringBuffer buffer, Symbol[] types, String prefix, String infix, String suffix) { buffer.append(prefix); for (int i = 0; i < types.length; i++) appendMember(i > 0 ? buffer.append(infix) : buffer, types[i]); buffer.append(suffix); return buffer; } // !!! >>> Interpreter stuff /** stop the compilation process immediately */ public Error fail() { throw new ApplicationError(); } /** stop the compilation process immediately */ public Error fail(String message) { throw new ApplicationError(message); } /** stop the compilation process immediately */ public Error fail(String message, Object object) { throw new ApplicationError(message, object); } /** stop the compilation process immediately */ public Error fail(Object value) { throw new ApplicationError(value); } /** issue a global error */ public void error(String message) { reporter.error("error: " + message); } /** issue a global warning */ public void warning(String message) { reporter.warning("warning: " + message); } /** issue a global note (if in verbose mode) */ public void note(String message) { reporter.note("note: " + message); } /** issue an operation note */ public void operation(String message) { reporter.inform("[" + message + "]"); } /** issue a debug message from currentPhase */ // the boolean return value is here to let one write "assert log( ... )" public boolean log(String message) { if (log()) { reporter.report("[log " + currentPhase.name() + "] " + message); } return true; } /** return true if logging is switched on for the current phase */ public boolean log() { return (currentPhase.flags & PhaseDescriptor.LOG) != 0; } /** start a new timer */ public void start() { startTimes.push(new Long(System.currentTimeMillis())); } /** issue timing information */ public void stop(String message) { long start = ((Long)startTimes.pop()).longValue(); reporter.inform("[" + message + " in " + (System.currentTimeMillis() - start) + "ms]"); } }
package reflect; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.Map; import java.util.Vector; public abstract class SourceCodeParamsHint implements ParamsHint { private String m_package; private Vector<ClassHint> m_hints; private Vector<String> m_imports = new Vector<String>(); private static Map<String, String> s_builtins = new HashMap<String, String>(); static { s_builtins.put("boolean", "Z"); s_builtins.put("byte", "B"); s_builtins.put("char", "C"); s_builtins.put("short", "S"); s_builtins.put("int", "I"); s_builtins.put("long", "J"); s_builtins.put("float", "F"); s_builtins.put("double", "D"); s_builtins.put("void", "V"); } protected abstract File getSourceRoot(String className); static class Tokenizer { private StreamTokenizer m_st; private static Map<String, Integer> s_ignore = new HashMap<String, Integer>(); static { s_ignore.put("native", 0); s_ignore.put("private", 0); s_ignore.put("protected", 0); s_ignore.put("public", 0); s_ignore.put("static", 0); s_ignore.put("final", 0); s_ignore.put("abstract", 0); s_ignore.put("transient", 0); s_ignore.put("volatile", 0); s_ignore.put("synchronized", 0); }; Tokenizer(FileReader rd) throws IOException { m_st = new StreamTokenizer(rd); //m_st.parseNumbers(); m_st.wordChars('_', '_'); m_st.ordinaryChars(0, ' '); m_st.slashSlashComments(true); m_st.slashStarComments(true); } String nextToken() throws IOException { int token = m_st.nextToken(); switch (token) { case StreamTokenizer.TT_NUMBER: double num = m_st.nval; if (num > -0.01 && num < 0.01) return "."; return String.valueOf(num); case StreamTokenizer.TT_WORD: String word = m_st.sval; if (word.trim().length() == 0) return nextToken(); if (s_ignore.containsKey(word)) return nextToken(); return word; case '"': String dquoteVal = m_st.sval; return "\"" + dquoteVal + "\""; case '\'': String squoteVal = m_st.sval; return "\'" + squoteVal + "\'"; case StreamTokenizer.TT_EOF: return null; default: char ch = (char) m_st.ttype; if (Character.isWhitespace(ch)) return nextToken(); return String.valueOf(ch); } } void pushBack() { m_st.pushBack(); } } static class StringPair { String value; String nextToken; StringPair(String val, String t) { value = val; nextToken = t; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(value); sb.append(" "); sb.append(nextToken); return sb.toString(); } } private static void skipTo(Tokenizer tokenizer, String tok) throws IOException { String t = tokenizer.nextToken(); while (t != null && !t.equals(tok)) t = tokenizer.nextToken(); } private static void skipBlocksTo(Tokenizer tokenizer, String tok) throws IOException { String t = tokenizer.nextToken(); while (t != null && !t.equals(tok)) { if (t.equals("{") && skipBlock(tokenizer)) return; if (t.equals("<") && skipGenerics(tokenizer)) return; t = tokenizer.nextToken(); } } static String ignoreAnnotation(Tokenizer tok) throws IOException { tok.nextToken(); String t = tok.nextToken(); if (t.equals("(")) { skipTo(tok, ")"); if (t != null) t = tok.nextToken(); } return t; } private boolean readPackage(Tokenizer tok) throws IOException { m_package = tok.nextToken(); if (m_package == null || m_package.equals(";")) { m_package = null; return false; } skipTo(tok, ";"); System.out.println("Package: " + m_package); return true; } public void addImport(String imp) { if (imp == null) return; m_imports.add(imp); System.out.println("Import: " + imp); } private boolean readImport(Tokenizer tok) throws IOException { final String imp = tok.nextToken(); if (imp == null || imp.equals(";")) return false; addImport(imp); skipTo(tok, ";"); return true; } private static boolean skipBlock(Tokenizer tok, String open, String close) throws IOException { int depth = 1; String t = tok.nextToken(); while (t != null) { if (t.equals(open)) ++depth; if (t.equals(close)) { if (--depth == 0) return true; } t = tok.nextToken(); } return false; } private static boolean skipBlock(Tokenizer tok) throws IOException { return skipBlock(tok, "{", "}"); } private static boolean skipGenerics(Tokenizer tok) throws IOException { return skipBlock(tok, "<", ">"); } private static boolean skipIndex(Tokenizer tok) throws IOException { return skipBlock(tok, "[", "]"); } class GenericsReader { protected Tokenizer m_tok; protected String m_ctor; protected String m_type; protected Map<String, String> m_aliases = null; GenericsReader(Tokenizer tok, String ctor, String type) { m_tok = tok; m_ctor = ctor; m_type = type; } private String tryClassName(String className) { try { Class<?> cand = Class.forName(className); if (cand != null) return "L" + cand.getName() + ";"; } catch (ClassNotFoundException e) { } return null; } private String tryImport(String typeName) { typeName = "." + typeName; //System.out.println("Trying " + typeName + " with imports"); for (String imp: m_imports) { //System.out.println(" > Trying " + imp); if (imp.endsWith(typeName)) // TODO: "import pa.cka.ge.Class;" and "Class.Subclass" case missing { String quick = tryClassName(imp); if (quick != null) { //System.out.println(" ! Found " + quick); return quick; } //now, where is the package, and where are the classes... //System.out.println(" ? Found " + imp); return "L" + imp + ";"; // TODO: temp; } if (imp.endsWith(".*")) { String cand = tryClassName(imp.substring(0, imp.length()-2) + typeName); if (cand != null) return cand; } } return null; } protected String resolve(String typeName) { if (s_builtins.containsKey(typeName)) return s_builtins.get(typeName); if (m_aliases != null && m_aliases.containsKey(typeName)) return m_aliases.get(typeName); String cand = null; if (typeName.equals(m_ctor)) cand = m_type; if (cand == null) cand = tryClassName(typeName); if (cand == null) cand = tryClassName(m_package + "." + typeName); if (cand == null) cand = tryClassName("java.lang." + typeName); if (cand == null) cand = tryImport(typeName); if (cand == null) { System.err.flush(); System.out.flush(); System.err.println("Could not resolve " + typeName); } return cand; } protected void setAlias(String generic, String resolved) { if (m_aliases == null) m_aliases = new HashMap<String, String>(); m_aliases.put(generic, resolved); } public boolean readGenerics() throws IOException { String t = m_tok.nextToken(); while (t != null) { if (t.equals(">")) return true; String alias = t; t = m_tok.nextToken(); // ">" "," "extends" if (t.equals("extends")) { t = m_tok.nextToken(); final String resolved = resolve(t); setAlias(alias, resolved == null ? "?" + t : resolved); t = m_tok.nextToken(); } else { setAlias(alias, "Ljava/lang/Object;"); } if (t.equals(",")) t = m_tok.nextToken(); if (t.equals(">")) return true; t = m_tok.nextToken(); } return false; } } private class MethodReader extends GenericsReader { private ClassHint m_parent; private String m_indent; MethodReader(Tokenizer tok, ClassHint parent, String ctor, String type, String indent, GenericsReader parent_reader) { super(tok, ctor, type); m_parent = parent; if (parent_reader.m_aliases != null) { for (Map.Entry<String, String> e: parent_reader.m_aliases.entrySet()) setAlias(e.getKey(), e.getValue()); } m_indent = indent; } public StringPair readType(String firstToken, String nextToken) throws IOException { if (nextToken.equals("<")) { if (!skipGenerics(m_tok)) return new StringPair(null, null); nextToken = m_tok.nextToken(); } String resolved = resolve(firstToken); StringBuilder sb = new StringBuilder(); if (resolved == null) sb.append("?"); while (nextToken != null && nextToken.equals("[")) { sb.append("["); if (!skipIndex(m_tok)) return new StringPair(null, null); nextToken = m_tok.nextToken(); } int dots = 0; // the StreamTokenizer will convert a "lone" dot into a 0.0 number while (nextToken != null && (nextToken.equals(".") || nextToken.equals("0.0"))) { ++dots; nextToken = m_tok.nextToken(); } if (dots != 0 && dots != 3) return new StringPair(null, null); if (dots == 3) // the "T... param" becomes "[T" sb.append("["); sb.append(resolved == null ? firstToken : resolved); return new StringPair(sb.toString(), nextToken); } public StringPair readType(String firstToken) throws IOException { String t = m_tok.nextToken(); if (t.equals("<") || t.equals("[")) return readType(firstToken, t); int dots = 0; if (firstToken.endsWith("...")) { if (firstToken.endsWith("....")) return new StringPair(null, null); dots = 3; firstToken = firstToken.substring(0, firstToken.length()-3); } String resolved = resolve(firstToken); if (resolved == null) resolved = "?"+(dots == 3 ? "[" + firstToken : firstToken); else if (dots == 3) resolved = "[" + resolved; return new StringPair(resolved, t); } public StringPair readCtorOrSelfType() throws IOException { StringPair _type = new StringPair("V", "<init>"); //assume it's a constructor String t = m_tok.nextToken(); if (t.equals("<") || t.equals("[")) // definitely not a ctor _type = readType(m_ctor, t); else if (t.equals("(")) // ctor would now have a open parenthesis m_tok.pushBack(); else _type = new StringPair("L" + m_type + ";", t); return _type; } public boolean readMethod(String retType, String name) throws IOException { MethodHint _meth = new MethodHint(retType, name); String t = m_tok.nextToken(); while (t != null) { if (t.equals(")")) { t = m_tok.nextToken(); while (t != null && !t.equals(";") && !t.equals("{")) t = m_tok.nextToken(); if (t == null) return false; if (t.equals("{") && !skipBlock(m_tok)) return false; m_parent.add(_meth); System.out.println(m_indent + _meth.toString()); return true; } StringPair param = readType(t); if (param.nextToken == null) break; if (param.nextToken.equals(",") || param.nextToken.equals(")")) { t = param.nextToken; param.nextToken = null; } else { t = m_tok.nextToken(); if (t.equals(",")) t = m_tok.nextToken(); } _meth.addParam(param.value, param.nextToken); } return false; } public String read() throws IOException { String currentToken = m_tok.nextToken(); StringPair _type; if (currentToken.equals("<")) // it's the <? extends Xyz> ? function(? _x); { if (!readGenerics()) return null; currentToken = m_tok.nextToken(); } if (currentToken.equals(m_ctor)) //might be Type(...) or Type prop; or Type meth(...); { _type = readCtorOrSelfType(); } else _type = readType(currentToken); if (_type.nextToken == null) return null; currentToken = m_tok.nextToken(); if (currentToken == null) return null; if (currentToken.equals("(")) { if (!readMethod(_type.value, _type.nextToken)) return null; return m_tok.nextToken(); } if (!currentToken.equals(";")) skipBlocksTo(m_tok, ";"); return m_tok.nextToken(); } } private boolean readClass(Tokenizer tok, String ctor, String typeName, String indent) throws IOException { final String type; if (m_package != null) type = m_package + "." + typeName; else type = typeName; GenericsReader class_generics = new GenericsReader(tok, ctor, type); String t = tok.nextToken(); if (t.equals("<")) class_generics.readGenerics(); if (!t.equals("{")) skipTo(tok, "{"); t = tok.nextToken(); ClassHint _class = new ClassHint(type); while (t != null) { if (t.equals("}")) { m_hints.add(_class); return true; } if (t.equals("@")) { t = ignoreAnnotation(tok); if (t == null) return false; } if (t.equals("class") || t.equals("interface") || t.equals("enum")) { t = tok.nextToken(); if (t == null) return false; System.out.println(indent + "Class: " + typeName + "$" + t + " {"); try { if (!readClass(tok, t, typeName + "$" + t, indent + " ")) return false; } finally { System.out.println(indent + "}"); } t = tok.nextToken(); if (t != null && t.equals(";")) t = tok.nextToken(); continue; } if (t.equals("{")) // static { ... } { if (!skipBlock(tok)) return false; t = tok.nextToken(); continue; } // a method or a property // method: <type> <name> "(" [<type> <name> ["," <type> <name>]*] ")" <block> // property: <type> <name> [";" | "="] tok.pushBack(); t = new MethodReader(tok, _class, ctor, type, indent, class_generics).read(); } return false; } public boolean read(File java) throws IOException { FileReader rd = new FileReader(java); Tokenizer tok = new Tokenizer(rd); int currentBracket = 0; int ignoreBracket = 2; //Integer.MAX_VALUE; try { String t = tok.nextToken(); while (t != null) { if (t.equals("@")) { t = ignoreAnnotation(tok); if (t == null) return false; } if (t.equals("package")) { if (!readPackage(tok)) return false; t = tok.nextToken(); continue; } if (t.equals("import")) { if (!readImport(tok)) return false; t = tok.nextToken(); continue; } if (t.equals("class") || t.equals("interface") || t.equals("enum")) { t = tok.nextToken(); if (t == null) return false; System.out.println("Class: " + t + " {"); try { if (!readClass(tok, t, t, " ")) return false; } finally { System.out.println("}"); } ++currentBracket; t = tok.nextToken(); if (t != null && t.equals(";")) t = tok.nextToken(); continue; } if (t.equals("{")) ++currentBracket; else if (t.equals("}")) --currentBracket; //if (currentBracket == ignoreBracket && t.equals("{")) System.out.println(";"); //if (currentBracket == ignoreBracket-1 && t.equals("}")) continue; if (currentBracket < ignoreBracket) { if (t.equals(";") || t.equals("{") || t.equals("}")) System.out.println(t); else System.out.print(t + " "); } t = tok.nextToken(); } } finally { rd.close(); } return true; } @Override public ClassHint[] getHints(String className) { m_hints = new Vector<ClassHint>(); File java = null; final File root = getSourceRoot(className); if (root != null) { String name = className.split("\\$")[0].replace('.', File.separatorChar) + ".java"; java = new File(root, name); } if (java == null || !java.isFile()) return null; try { if (!read(java)) return null; } catch (IOException ex) { return null; } if (m_hints.size() == 0) return null; ClassHint[] ret = new ClassHint[m_hints.size()]; return m_hints.toArray(ret); } }
package com.novoda.downloadmanager; import android.support.annotation.Nullable; import java.util.List; import java.util.Map; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.*; // This model knows how to interact with low level components. @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.StdCyclomaticComplexity", "PMD.ModifiedCyclomaticComplexity"}) class DownloadBatch { private static final int ZERO_BYTES = 0; private final Map<DownloadFileId, Long> fileBytesDownloadedMap; private final InternalDownloadBatchStatus downloadBatchStatus; private final List<DownloadFile> downloadFiles; private final DownloadsBatchPersistence downloadsBatchPersistence; private final CallbackThrottle callbackThrottle; private final ConnectionChecker connectionChecker; private long totalBatchSizeBytes; private DownloadBatchStatusCallback callback; DownloadBatch(InternalDownloadBatchStatus internalDownloadBatchStatus, List<DownloadFile> downloadFiles, Map<DownloadFileId, Long> fileBytesDownloadedMap, DownloadsBatchPersistence downloadsBatchPersistence, CallbackThrottle callbackThrottle, ConnectionChecker connectionChecker) { this.downloadFiles = downloadFiles; this.fileBytesDownloadedMap = fileBytesDownloadedMap; this.downloadBatchStatus = internalDownloadBatchStatus; this.downloadsBatchPersistence = downloadsBatchPersistence; this.callbackThrottle = callbackThrottle; this.connectionChecker = connectionChecker; } void setCallback(DownloadBatchStatusCallback callback) { this.callback = callback; callbackThrottle.setCallback(callback); } void download() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == PAUSED || status == DELETION) { return; } if (connectionNotAllowedForDownload(status)) { downloadBatchStatus.markAsWaitingForNetwork(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); DownloadsNetworkRecoveryCreator.getInstance().scheduleRecovery(); return; } if (status != DOWNLOADED) { downloadBatchStatus.markAsDownloading(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); } totalBatchSizeBytes = getTotalSize(downloadFiles); if (totalBatchSizeBytes <= ZERO_BYTES) { Optional<DownloadError> downloadError = Optional.of(new DownloadError(DownloadError.Error.NETWORK_ERROR_CANNOT_DOWNLOAD_FILE)); downloadBatchStatus.markAsError(downloadError, downloadsBatchPersistence); notifyCallback(downloadBatchStatus); return; } for (DownloadFile downloadFile : downloadFiles) { if (connectionNotAllowedForDownload(status)) { downloadBatchStatus.markAsWaitingForNetwork(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); break; } downloadFile.download(fileDownloadCallback); if (batchCannotContinue()) { break; } } if (networkError()) { DownloadsNetworkRecoveryCreator.getInstance().scheduleRecovery(); } callbackThrottle.stopUpdates(); } private boolean connectionNotAllowedForDownload(DownloadBatchStatus.Status status) { return !connectionChecker.isAllowedToDownload() && status != DOWNLOADED; } private final DownloadFile.Callback fileDownloadCallback = new DownloadFile.Callback() { @Override public void onUpdate(InternalDownloadFileStatus downloadFileStatus) { fileBytesDownloadedMap.put(downloadFileStatus.downloadFileId(), downloadFileStatus.bytesDownloaded()); long currentBytesDownloaded = getBytesDownloadedFrom(fileBytesDownloadedMap); downloadBatchStatus.update(currentBytesDownloaded, totalBatchSizeBytes); if (currentBytesDownloaded == totalBatchSizeBytes && totalBatchSizeBytes != ZERO_BYTES) { downloadBatchStatus.markAsDownloaded(downloadsBatchPersistence); } if (downloadFileStatus.isMarkedAsError()) { downloadBatchStatus.markAsError(downloadFileStatus.error(), downloadsBatchPersistence); } if (downloadFileStatus.isMarkedAsWaitingForNetwork()) { downloadBatchStatus.markAsWaitingForNetwork(downloadsBatchPersistence); } callbackThrottle.update(downloadBatchStatus); } }; private boolean networkError() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == WAITING_FOR_NETWORK) { return true; } else if (status == ERROR) { DownloadError.Error downloadErrorType = downloadBatchStatus.getDownloadErrorType(); if (downloadErrorType == DownloadError.Error.NETWORK_ERROR_CANNOT_DOWNLOAD_FILE) { return true; } } return false; } private boolean batchCannotContinue() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); return status == ERROR || status == DELETION || status == PAUSED || status == WAITING_FOR_NETWORK; } private long getBytesDownloadedFrom(Map<DownloadFileId, Long> fileBytesDownloadedMap) { long bytesDownloaded = 0; for (Map.Entry<DownloadFileId, Long> entry : fileBytesDownloadedMap.entrySet()) { bytesDownloaded += entry.getValue(); } return bytesDownloaded; } private void notifyCallback(InternalDownloadBatchStatus downloadBatchStatus) { if (callback != null) { callback.onUpdate(downloadBatchStatus); } } private long getTotalSize(List<DownloadFile> downloadFiles) { if (totalBatchSizeBytes == 0) { for (DownloadFile downloadFile : downloadFiles) { totalBatchSizeBytes += downloadFile.getTotalSize(); } } return totalBatchSizeBytes; } void pause() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == PAUSED || status == DOWNLOADED) { return; } downloadBatchStatus.markAsPaused(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.pause(); } } void waitForNetwork() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status != DOWNLOADING) { return; } for (DownloadFile downloadFile : downloadFiles) { downloadFile.waitForNetwork(); } } void resume() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == QUEUED || status == DOWNLOADING || status == DOWNLOADED) { return; } downloadBatchStatus.markAsQueued(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.resume(); } } void delete() { downloadsBatchPersistence.deleteAsync(downloadBatchStatus.getDownloadBatchId()); downloadBatchStatus.markForDeletion(); notifyCallback(downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.delete(); } } DownloadBatchId getId() { return downloadBatchStatus.getDownloadBatchId(); } InternalDownloadBatchStatus status() { return downloadBatchStatus; } @Nullable DownloadFileStatus downloadFileStatusWith(DownloadFileId downloadFileId) { for (DownloadFile downloadFile : downloadFiles) { if (downloadFile.matches(downloadFileId)) { return downloadFile.fileStatus(); } } return null; } void persist() { downloadsBatchPersistence.persistAsync( downloadBatchStatus.getDownloadBatchTitle(), downloadBatchStatus.getDownloadBatchId(), downloadBatchStatus.status(), downloadFiles, downloadBatchStatus.downloadedDateTimeInMillis(), downloadBatchStatus.notificationSeen() ); } }
package org.jboss.test.selenium; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.EnumSet; import java.util.List; import org.apache.commons.io.IOUtils; import org.jboss.test.selenium.browser.Browser; import org.jboss.test.selenium.browser.BrowserMode; import org.jboss.test.selenium.browser.BrowserType; import org.jboss.test.selenium.encapsulated.JavaScript; import org.jboss.test.selenium.framework.AjaxSelenium; import org.jboss.test.selenium.framework.AjaxSeleniumImpl; import org.jboss.test.selenium.framework.AjaxSeleniumProxy; import org.jboss.test.selenium.locator.ElementLocationStrategy; import org.jboss.test.selenium.waiting.ajax.AjaxWaiting; import org.jboss.test.selenium.waiting.conditions.AlertEquals; import org.jboss.test.selenium.waiting.conditions.AlertPresent; import org.jboss.test.selenium.waiting.conditions.AttributeEquals; import org.jboss.test.selenium.waiting.conditions.AttributePresent; import org.jboss.test.selenium.waiting.conditions.CountEquals; import org.jboss.test.selenium.waiting.conditions.ElementPresent; import org.jboss.test.selenium.waiting.conditions.StyleEquals; import org.jboss.test.selenium.waiting.conditions.TextEquals; import org.jboss.test.selenium.waiting.retrievers.AttributeRetriever; import org.jboss.test.selenium.waiting.retrievers.TextRetriever; import org.jboss.test.selenium.waiting.selenium.SeleniumWaiting; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format; import static org.jboss.test.selenium.waiting.Wait.waitAjax; import static org.jboss.test.selenium.waiting.Wait.waitSelenium; import static org.jboss.test.selenium.encapsulated.JavaScript.fromResource; import static org.jboss.test.selenium.SystemProperties.getBrowser; import static org.jboss.test.selenium.SystemProperties.getContextPath; import static org.jboss.test.selenium.SystemProperties.getContextRoot; import static org.jboss.test.selenium.SystemProperties.getMavenProjectBuildDirectory; import static org.jboss.test.selenium.SystemProperties.getMavenResourcesDir; import static org.jboss.test.selenium.SystemProperties.getSeleniumHost; import static org.jboss.test.selenium.SystemProperties.getSeleniumPort; import static org.jboss.test.selenium.SystemProperties.getSeleniumSpeed; import static org.jboss.test.selenium.SystemProperties.getSeleniumTimeout; import static org.jboss.test.selenium.SystemProperties.isSeleniumDebug; import static org.jboss.test.selenium.SystemProperties.isSeleniumMaximize; import static org.jboss.test.selenium.SystemProperties.isSeleniumNetworkTrafficEnabled; import static org.jboss.test.selenium.SystemProperties.SeleniumTimeoutType; /** * <p> * Abstract implementation of TestNG test using RichFaces Selenium * </p> * * @author <a href="mailto:lfryc@redhat.com">Lukas Fryc</a> * @version $Revision$ */ public abstract class AbstractTestCase { public static final int WAIT_GUI_INTERVAL = 100; public static final int WAIT_AJAX_INTERVAL = 500; public static final int WAIT_MODEL_INTERVAL = 1500; protected AjaxSelenium selenium; /** * Waits for GUI interaction, such as rendering */ protected AjaxWaiting waitGui; /** * Waits for AJAX interaction with server - not computationally difficult */ protected AjaxWaiting waitAjax; /** * Waits for computationally difficult requests */ protected SeleniumWaiting waitModel; protected ElementPresent elementPresent = ElementPresent.getInstance(); protected TextEquals textEquals = TextEquals.getInstance(); protected StyleEquals styleEquals = StyleEquals.getInstance(); protected AttributePresent attributePresent = AttributePresent.getInstance(); protected AttributeEquals attributeEquals = AttributeEquals.getInstance(); protected AlertPresent alertPresent = AlertPresent.getInstance(); protected AlertEquals alertEquals = AlertEquals.getInstance(); protected CountEquals countEquals = CountEquals.getInstance(); protected TextRetriever retrieveText = TextRetriever.getInstance(); protected AttributeRetriever retrieveAttribute = AttributeRetriever.getInstance(); /** * context root can be used to obtaining full URL paths, is set to actual tested application's context root */ protected URL contextRoot; /** * ContextPath will be used to retrieve pages from right URL. Don't hesitate to use it in cases of building absolute * URLs. */ protected URL contextPath; /** * Introduce some maven build properties */ protected File mavenProjectBuildDirectory; // usually ${project}/target protected File mavenResourcesDir; // usually ${project}/target/test-classes protected boolean seleniumDebug; // if used specified debug mode of selenium testing protected Browser browser; @BeforeClass(alwaysRun = true) public void initializeParameters() throws MalformedURLException { this.seleniumDebug = isSeleniumDebug(); this.contextRoot = getContextRoot(); this.contextPath = getContextPath(); this.mavenResourcesDir = getMavenResourcesDir(); this.mavenProjectBuildDirectory = getMavenProjectBuildDirectory(); this.browser = getBrowser(); } @BeforeClass(dependsOnMethods = { "initializeParameters", "isTestBrowserEnabled" }, alwaysRun = true) public void initializeBrowser() { selenium = new AjaxSeleniumImpl(getSeleniumHost(), getSeleniumPort(), browser, contextPath); AjaxSeleniumProxy.setCurrentContext(selenium); selenium.enableNetworkTrafficCapturing(isSeleniumNetworkTrafficEnabled()); selenium.start(); loadCustomLocationStrategies(); selenium.setSpeed(getSeleniumSpeed()); if (isSeleniumMaximize()) { // focus and maximaze tested window selenium.windowFocus(); selenium.windowMaximize(); } } /** * Restarts the browser by finalizing current session and initializing new one. */ public void restartBrowser() { finalizeBrowser(); initializeBrowser(); initializeExtensions(); } /** * Initializes the timeouts for waiting on interaction * * @param seleniumTimeoutDefault * the timeout set in Selenium API * @param seleniumTimeoutGui * initial timeout set for waiting GUI interaction * @param seleniumTimeoutAjax * initial timeout set for waiting server AJAX interaction * @param seleniumTimeoutModel * initial timeout set for waiting server computationally difficult interaction */ @BeforeClass(alwaysRun = true, dependsOnMethods = "initializeBrowser") public void initializeWaitTimeouts() { selenium.setTimeout(getSeleniumTimeout(SeleniumTimeoutType.DEFAULT)); waitGui = waitAjax().interval(WAIT_GUI_INTERVAL).timeout(getSeleniumTimeout(SeleniumTimeoutType.GUI)); waitAjax = waitAjax().interval(WAIT_AJAX_INTERVAL).timeout(getSeleniumTimeout(SeleniumTimeoutType.AJAX)); waitModel = waitSelenium().interval(WAIT_MODEL_INTERVAL).timeout(getSeleniumTimeout(SeleniumTimeoutType.MODEL)); } /** * Initializes page and Selenium's extensions to correctly install before test run. */ @BeforeClass(dependsOnMethods = { "initializeBrowser" }, alwaysRun = true) public void initializeExtensions() { List<String> seleniumExtensions = getExtensionsListFromResource("javascript/selenium-extensions-order.txt"); List<String> pageExtensions = getExtensionsListFromResource("javascript/page-extensions-order.txt"); // loads the extensions to the selenium selenium.getSeleniumExtensions().requireResources(seleniumExtensions); // register the handlers for newly loaded extensions selenium.getSeleniumExtensions().registerCustomHandlers(); // prepares the resources to load into page selenium.getPageExtensions().loadFromResources(pageExtensions); } /** * Loads the list of resource names from the given resource. * * @param resourceName * the path to resource on classpath * @return the list of resource names from the given resource. */ @SuppressWarnings("unchecked") private List<String> getExtensionsListFromResource(String resourceName) { try { return IOUtils.readLines(ClassLoader.getSystemResourceAsStream(resourceName)); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Uses selenium.addLocationStrategy to implement own strategies to locate items in the tested page */ private void loadCustomLocationStrategies() { // jQuery location strategy JavaScript strategySource = fromResource("javascript/selenium-location-strategies/jquery-location-strategy.js"); selenium.addLocationStrategy(ElementLocationStrategy.JQUERY, strategySource); } /** * Finalize context after each class run. */ @AfterClass(alwaysRun = true) public void finalizeBrowser() { if (selenium != null && selenium.isStarted()) { selenium.deleteAllVisibleCookies(); AjaxSeleniumProxy.setCurrentContext(null); selenium.stop(); selenium = null; } } /** * Check whenever the current test is enabled for selected browser (evaluated from testng.xml). * * If it is not enabled, skip the particular test. */ @Parameters({ "enabled-browsers", "disabled-browsers", "enabled-modes", "disabled-modes" }) @BeforeClass(dependsOnMethods = "initializeParameters", alwaysRun = true) public void isTestBrowserEnabled(@Optional("*") String enabledBrowsersParam, @Optional("") String disabledBrowsersParam, @Optional("*") String enabledModesParam, @Optional("") String disabledModesParam) { EnumSet<BrowserType> enabledBrowserTypes = BrowserType.parseTypes(enabledBrowsersParam); EnumSet<BrowserType> disabledBrowserTypes = BrowserType.parseTypes(disabledBrowsersParam); EnumSet<BrowserMode> enabledBrowserModes = BrowserMode.parseModes(enabledModesParam); EnumSet<BrowserMode> disabledBrowserModes = BrowserMode.parseModes(disabledModesParam); enabledBrowserTypes.removeAll(disabledBrowserTypes); enabledBrowserModes.addAll(BrowserMode.getModesFromTypes(enabledBrowserTypes)); enabledBrowserModes.removeAll(disabledBrowserModes); if (!enabledBrowserModes.contains(browser.getMode())) { throw new SkipException(format("This test isn't supported in {0}", browser)); } } }
package stategraph; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Stack; import lhpn2sbml.parser.ExprTree; import lhpn2sbml.parser.LHPNFile; public class StateGraph { private HashMap<boolean[], LinkedList<Marking>> stateGraph; private LHPNFile lhpn; public StateGraph(LHPNFile lhpn) { this.lhpn = lhpn; stateGraph = new HashMap<boolean[], LinkedList<Marking>>(); buildStateGraph(); } private void buildStateGraph() { ArrayList<String> variables = new ArrayList<String>(); for (String var : lhpn.getBooleanVars()) { variables.add(var); } boolean[] variableVector = new boolean[variables.size()]; for (int i = 0; i < variableVector.length; i++) { if (lhpn.getInitialVal(variables.get(i)).equals("true")) { variableVector[i] = true; } else { variableVector[i] = false; } } ArrayList<String> markedPlaces = new ArrayList<String>(); HashMap<String, Boolean> places = lhpn.getPlaces(); for (String place : places.keySet()) { if (places.get(place)) { markedPlaces.add(place); } } LinkedList<Marking> markings = new LinkedList<Marking>(); markings.add(new Marking(markedPlaces.toArray(new String[0]), new Marking[0] ,variableVector)); stateGraph.put(variableVector, markings); Stack<Transition> transitionsToFire = new Stack<Transition>(); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), copyStateVector(variableVector))); } } while (transitionsToFire.size() != 0) { Transition fire = transitionsToFire.pop(); markedPlaces = fire.getMarkedPlaces(); variableVector = fire.getVariableVector(); for (String place : lhpn.getPreset(fire.getTransition())) { markedPlaces.remove(place); } for (String place : lhpn.getPostset(fire.getTransition())) { markedPlaces.add(place); } for (int i = 0; i < variables.size(); i++) { if (lhpn.getBoolAssignTree(fire.getTransition(), variables.get(i)) != null) { if (evaluateExp(lhpn.getBoolAssignTree(fire.getTransition(), variables.get(i))) .equals("true")) { variableVector[i] = true; } else { variableVector[i] = false; } } } if (!stateGraph.containsKey(variableVector)) { markings = new LinkedList<Marking>(); markings.add(new Marking(markedPlaces.toArray(new String[0]), new Marking[0] ,variableVector)); stateGraph.put(variableVector, markings); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), copyStateVector(variableVector))); } } } else { markings = stateGraph.get(variableVector); boolean add = false; for (Marking mark : markings) { for (String place : mark.getMarkings()) { if (!markedPlaces.contains(place)) { add = true; } } for (String place : markedPlaces) { boolean contains = false; for (String place2 : mark.getMarkings()) { if (place2.equals(place)) { contains = true; } } if (!contains) { add = true; } } } if (add) { markings.add(new Marking(markedPlaces.toArray(new String[0]), new Marking[0] ,variableVector)); stateGraph.put(variableVector, markings); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), copyStateVector(variableVector))); } } } } } } private String evaluateExp(ExprTree[] exprTrees) { return "false"; } private ArrayList<String> copyArrayList(ArrayList<String> original) { ArrayList<String> copy = new ArrayList<String>(); for (String element : original) { copy.add(element); } return copy; } private boolean[] copyStateVector(boolean[] original) { boolean[] copy = new boolean[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = original[i]; } return copy; } private class Transition { private String transition; private boolean[] variableVector; private ArrayList<String> markedPlaces; private Transition(String transition, ArrayList<String> markedPlaces, boolean[] variableVector) { this.transition = transition; this.markedPlaces = markedPlaces; this.variableVector = variableVector; } private String getTransition() { return transition; } private ArrayList<String> getMarkedPlaces() { return markedPlaces; } private boolean[] getVariableVector() { return variableVector; } } private class Marking { private String[] markings; private boolean[] stateVector; private Marking[] nextStates; private Marking(String[] markings, Marking[] nextStates, boolean[] stateVector) { this.markings = markings; this.nextStates = nextStates; this.stateVector = stateVector; } private String[] getMarkings() { return markings; } private Marking[] getNextStates() { return nextStates; } private boolean[] getStateVector() { return stateVector; } private void addNextState(Marking nextState) { Marking[] newNextStates = new Marking[nextStates.length + 1]; for (int i = 0; i < nextStates.length; i++) { newNextStates[i] = nextStates[i]; } newNextStates[newNextStates.length - 1] = nextState; nextStates = newNextStates; } } }
package stategraph; import java.io.BufferedWriter; import java.io.FileWriter; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import javax.swing.JOptionPane; import parser.Parser; import biomodelsim.BioSim; import lhpn2sbml.parser.ExprTree; import lhpn2sbml.parser.LhpnFile; public class StateGraph implements Runnable { private HashMap<String, LinkedList<State>> stateGraph; private ArrayList<String> variables; private LhpnFile lhpn; private boolean stop; private String markovResults; private Parser probData; public StateGraph(LhpnFile lhpn) { this.lhpn = lhpn; stop = false; markovResults = null; } public void buildStateGraph() { stateGraph = new HashMap<String, LinkedList<State>>(); variables = new ArrayList<String>(); for (String var : lhpn.getBooleanVars()) { variables.add(var); } for (String var : lhpn.getIntVars()) { variables.add(var); } HashMap<String, String> allVariables = new HashMap<String, String>(); for (String var : lhpn.getBooleanVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getContVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getIntVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } ArrayList<String> markedPlaces = new ArrayList<String>(); for (String place : lhpn.getPlaceList()) { if (lhpn.getPlace(place).isMarked()) { markedPlaces.add(place); } } LinkedList<State> markings = new LinkedList<State>(); int counter = 0; State state = new State(markedPlaces.toArray(new String[0]), new StateTransitionPair[0], "S" + counter, createStateVector(variables, allVariables), copyAllVariables(allVariables)); markings.add(state); counter++; stateGraph.put(createStateVector(variables, allVariables), markings); Stack<Transition> transitionsToFire = new Stack<Transition>(); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; if (lhpn.getEnablingTree(transition) != null && lhpn.getEnablingTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getTransitionRateTree(transition) != null && lhpn.getTransitionRateTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getPreset(transition).length != 0) { for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } } else { addToStack = false; } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), state)); } } while (transitionsToFire.size() != 0 && !stop) { Transition fire = transitionsToFire.pop(); markedPlaces = fire.getMarkedPlaces(); allVariables = copyAllVariables(fire.getParent().getVariables()); for (String place : lhpn.getPreset(fire.getTransition())) { markedPlaces.remove(place); } for (String place : lhpn.getPostset(fire.getTransition())) { markedPlaces.add(place); } for (String key : allVariables.keySet()) { if (lhpn.getBoolAssignTree(fire.getTransition(), key) != null) { double eval = lhpn.getBoolAssignTree(fire.getTransition(), key).evaluateExpr(allVariables); if (eval == 0.0) { allVariables.put(key, "false"); } else { allVariables.put(key, "true"); } } if (lhpn.getContAssignTree(fire.getTransition(), key) != null) { allVariables.put(key, "" + lhpn.getContAssignTree(fire.getTransition(), key).evaluateExpr(allVariables)); } if (lhpn.getIntAssignTree(fire.getTransition(), key) != null) { allVariables.put(key, "" + ((int) lhpn.getIntAssignTree(fire.getTransition(), key).evaluateExpr(allVariables))); } } if (!stateGraph.containsKey(createStateVector(variables, allVariables))) { markings = new LinkedList<State>(); state = new State(markedPlaces.toArray(new String[0]), new StateTransitionPair[0], "S" + counter, createStateVector(variables, allVariables), copyAllVariables(allVariables)); markings.add(state); fire.getParent().addNextState(state, lhpn.getTransitionRateTree(fire.getTransition()).evaluateExpr(fire.getParent().getVariables()));// fire.getTransition()); counter++; stateGraph.put(createStateVector(variables, allVariables), markings); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; if (lhpn.getEnablingTree(transition) != null && lhpn.getEnablingTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getTransitionRateTree(transition) != null && lhpn.getTransitionRateTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getPreset(transition).length != 0) { for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } } else { addToStack = false; } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), state)); } } } else { markings = stateGraph.get(createStateVector(variables, allVariables)); boolean add = true; boolean same = true; for (State mark : markings) { for (String place : mark.getMarkings()) { if (!markedPlaces.contains(place)) { same = false; } } for (String place : markedPlaces) { boolean contains = false; for (String place2 : mark.getMarkings()) { if (place2.equals(place)) { contains = true; } } if (!contains) { same = false; } } if (same) { add = false; fire.getParent().addNextState(mark, lhpn.getTransitionRateTree(fire.getTransition()).evaluateExpr(fire.getParent().getVariables()));// fire.getTransition()); } same = true; } if (add) { state = new State(markedPlaces.toArray(new String[0]), new StateTransitionPair[0], "S" + counter, createStateVector(variables, allVariables), copyAllVariables(allVariables)); markings.add(state); fire.getParent().addNextState(state, lhpn.getTransitionRateTree(fire.getTransition()).evaluateExpr(fire.getParent().getVariables()));// fire.getTransition()); counter++; stateGraph.put(createStateVector(variables, allVariables), markings); for (String transition : lhpn.getTransitionList()) { boolean addToStack = true; if (lhpn.getEnablingTree(transition) != null && lhpn.getEnablingTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getTransitionRateTree(transition) != null && lhpn.getTransitionRateTree(transition).evaluateExpr(allVariables) == 0.0) { addToStack = false; } if (lhpn.getPreset(transition).length != 0) { for (String place : lhpn.getPreset(transition)) { if (!markedPlaces.contains(place)) { addToStack = false; } } } else { addToStack = false; } if (addToStack) { transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces), state)); } } } } } } public boolean canPerformMarkovianAnalysis() { for (String trans : lhpn.getTransitionList()) { if (!lhpn.isExpTransitionRateTree(trans)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has transitions without exponential delay.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } for (String var : lhpn.getVariables()) { if (lhpn.isRandomBoolAssignTree(trans, var)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has assignments containing random functions.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } if (lhpn.isRandomContAssignTree(trans, var)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has assignments containing random functions.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } if (lhpn.isRandomIntAssignTree(trans, var)) { JOptionPane.showMessageDialog(BioSim.frame, "LPN has assignments containing random functions.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } } } if (lhpn.getContVars().length > 0) { JOptionPane.showMessageDialog(BioSim.frame, "LPN contains continuous variables.", "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } return true; } public boolean performTransientMarkovianAnalysis(double timeLimit, double timeStep, double error, String[] condition) { if (!canPerformMarkovianAnalysis()) { stop = true; return false; } else if (condition != null) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); dataLabels.add("~(" + condition[0] + ")&~(" + condition[1] + ")"); dataLabels.add(condition[1]); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); probData = new Parser(dataLabels, data); State initial = getInitialState(); if (initial != null) { initial.setCurrentProb(1.0); initial.setPiProb(1.0); double lowerbound = 0; if (!condition[2].equals("")) { ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(condition[2]); expr.intexpr_L(condition[2]); lowerbound = Math.min(expr.evaluateExpr(null), timeLimit); pruneStateGraph("~(" + condition[0] + ")"); for (double i = 0; i < lowerbound; i += timeStep) { double step = Math.min(timeStep, lowerbound - i); if (!performTransientMarkovianAnalysis(step, error)) { return false; } probData.getData().get(0).add(i + timeStep); double prob = 0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok("~(" + condition[0] + ")"); expr.intexpr_L("~(" + condition[0] + ")"); if (expr.evaluateExpr(m.getVariables()) == 1.0) { prob += m.getCurrentProb(); } } } probData.getData().get(1).add(prob * 100); probData.getData().get(2).add(0.0); } } else { pruneStateGraph("~(" + condition[0] + ")"); } ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(condition[3]); expr.intexpr_L(condition[3]); double upperbound = Math.min(expr.evaluateExpr(null) - lowerbound, timeLimit - lowerbound); pruneStateGraph(condition[1]); for (double i = 0; i < upperbound; i += timeStep) { double step = Math.min(timeStep, upperbound - i); if (!performTransientMarkovianAnalysis(step, error)) { return false; } probData.getData().get(0).add(lowerbound + i + timeStep); double failureProb = 0; double successProb = 0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree failureExpr = new ExprTree(lhpn); failureExpr.token = failureExpr.intexpr_gettok("~(" + condition[0] + ")&~(" + condition[1] + ")"); failureExpr.intexpr_L("~(" + condition[0] + ")&~(" + condition[1] + ")"); ExprTree successExpr = new ExprTree(lhpn); successExpr.token = successExpr.intexpr_gettok(condition[1]); successExpr.intexpr_L(condition[1]); if (failureExpr.evaluateExpr(m.getVariables()) == 1.0) { failureProb += m.getCurrentProb(); } else if (successExpr.evaluateExpr(m.getVariables()) == 1.0) { successProb += m.getCurrentProb(); } } } probData.getData().get(1).add(failureProb * 100); probData.getData().get(2).add(successProb * 100); } HashMap<String, Double> output = new HashMap<String, Double>(); double failureProb = 0; double successProb = 0; double timelimitProb = 0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree failureExpr = new ExprTree(lhpn); failureExpr.token = failureExpr.intexpr_gettok("~(" + condition[0] + ")&~(" + condition[1] + ")"); failureExpr.intexpr_L("~(" + condition[0] + ")&~(" + condition[1] + ")"); ExprTree successExpr = new ExprTree(lhpn); successExpr.token = successExpr.intexpr_gettok(condition[1]); successExpr.intexpr_L(condition[1]); if (failureExpr.evaluateExpr(m.getVariables()) == 1.0) { failureProb += m.getCurrentProb(); } else if (successExpr.evaluateExpr(m.getVariables()) == 1.0) { successProb += m.getCurrentProb(); } else { timelimitProb += m.getCurrentProb(); } } } output.put("~(" + condition[0].trim() + ")&~(" + condition[1].trim() + ")", failureProb); output.put(condition[1].trim(), successProb); output.put("timelimit", timelimitProb); String result1 = "#total"; String result2 = "1.0"; for (String s : output.keySet()) { result1 += " " + s; result2 += " " + output.get(s); } markovResults = result1 + "\n" + result2 + "\n"; return true; } else { return false; } } else { boolean stop = false; for (double i = 0; i < timeLimit; i += timeStep) { double step = Math.min(timeStep, timeLimit - i); stop = !performTransientMarkovianAnalysis(step, error); if (stop) { return false; } } return !stop; } } private boolean performTransientMarkovianAnalysis(double timeLimit, double error) { if (timeLimit == 0.0) { return true; } // Compute Gamma double Gamma = 0; if (!stop) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { Gamma = Math.max(m.getTransitionSum(0.0, null), Gamma); } } } else { return false; } // Compute K int K = 0; double xi = 1; double delta = 1; double eta = (1 - error) / (Math.pow((Math.E), -Gamma * timeLimit)); while (delta < eta && !stop) { K = K + 1; xi = xi * ((Gamma * timeLimit) / K); delta = delta + xi; } if (stop) { return false; } // Approximate pi(t) for (int k = 1; k <= K && !stop; k++) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { double nextProb = m.getCurrentProb() * (1 - (m.getTransitionSum(0.0, null) / Gamma)); for (StateTransitionPair prev : m.getPrevStatesWithTrans()) { double prob = prev.getTransition(); // if (lhpn.getTransitionRateTree(prev.getTransition()) != null) { // prob = // lhpn.getTransitionRateTree(prev.getTransition()).evaluateExpr(prev.getState().getVariables()); nextProb += (prev.getState().getCurrentProb() * prob) / Gamma; } m.setNextProb(nextProb * ((Gamma * timeLimit) / k)); m.setPiProb(m.getPiProb() + m.getNextProb()); } } if (stop) { return false; } for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setCurrentProbToNext(); } } } if (!stop) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setPiProb(m.getPiProb() * (Math.pow((Math.E), -Gamma * timeLimit))); m.setCurrentProbToPi(); } } } if (stop) { return false; } return true; } public void pruneStateGraph(String condition) { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(condition); expr.intexpr_L(condition); if (expr.evaluateExpr(m.getVariables()) == 1.0) { for (State s : m.getNextStates()) { ArrayList<StateTransitionPair> newTrans = new ArrayList<StateTransitionPair>(); for (StateTransitionPair trans : s.getPrevStatesWithTrans()) { if (trans.getState() != m) { newTrans.add(trans); } } s.setPrevStatesWithTrans(newTrans.toArray(new StateTransitionPair[0])); } m.setNextStatesWithTrans(new StateTransitionPair[0]); } m.setTransitionSum(-1); } } } public boolean performSteadyStateMarkovianAnalysis(double tolerance, ArrayList<String> conditions) { if (!canPerformMarkovianAnalysis()) { stop = true; return false; } else { State initial = getInitialState(); if (initial != null && !stop) { resetColorsForMarkovianAnalysis(); int period = findPeriod(initial); if (period == 0) { period = 1; } int step = 0; initial.setCurrentProb(1.0); boolean done = false; if (!stop) { do { step++; step = step % period; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (m.getColor() % period == step) { double nextProb = 0.0; for (StateTransitionPair prev : m.getPrevStatesWithTrans()) { double transProb = 0.0; transProb += prev.getTransition(); // if (lhpn.getTransitionRateTree(prev.getTransition()) != // null) { // if (lhpn.getTransitionRateTree(prev.getTransition()) != // null) { // (!lhpn.isExpTransitionRateTree(prev // .getTransition()) // lhpn.getDelayTree(prev.getTransition()) // .evaluateExpr(null) == 0) { // transProb = 1.0; // else { // transProb = // lhpn.getTransitionRateTree(prev.getTransition()).evaluateExpr( // prev.getState().getVariables()); // else { // transProb = 1.0; double transitionSum = prev.getState().getTransitionSum(1.0, m); if (transitionSum != 0) { transProb = (transProb / transitionSum); } else { transProb = 0.0; } nextProb += (prev.getState().getCurrentProb() * transProb); if (stop) { return false; } } if (nextProb != 0.0) { m.setNextProb(nextProb); } } if (stop) { return false; } } if (stop) { return false; } } boolean change = false; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (m.getColor() % period == step) { if ((m.getCurrentProb() != 0) && (Math.abs(((m.getCurrentProb() - m.getNextProb())) / m.getCurrentProb()) > tolerance)) { change = true; } else if (m.getCurrentProb() == 0 && m.getNextProb() > tolerance) { change = true; } m.setCurrentProbToNext(); } if (stop) { return false; } } if (stop) { return false; } } if (!change) { done = true; } } while (!done && !stop); } if (!stop) { double totalProb = 0.0; for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { double transitionSum = m.getTransitionSum(1.0, null); if (transitionSum != 0.0) { m.setCurrentProb((m.getCurrentProb() / period) / transitionSum); } totalProb += m.getCurrentProb(); if (stop) { return false; } } if (stop) { return false; } } for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (totalProb != 0.0) { m.setCurrentProb(m.getCurrentProb() / totalProb); } if (stop) { return false; } } if (stop) { return false; } } resetColors(); HashMap<String, Double> output = new HashMap<String, Double>(); if (conditions != null && !stop) { for (String cond : conditions) { double prob = 0; // for (String ss : s.split("&&")) { // if (ss.split("->").length == 2) { // String[] states = ss.split("->"); // for (String state : stateGraph.keySet()) { // for (State m : stateGraph.get(state)) { // ExprTree expr = new ExprTree(lhpn); // expr.token = expr.intexpr_gettok(states[0]); // expr.intexpr_L(states[0]); // if (expr.evaluateExpr(m.getVariables()) == 1.0) { // for (StateTransitionPair nextState : m // .getNextStatesWithTrans()) { // ExprTree nextExpr = new ExprTree(lhpn); // nextExpr.token = nextExpr // .intexpr_gettok(states[1]); // nextExpr.intexpr_L(states[1]); // if (nextExpr.evaluateExpr(nextState.getState() // .getVariables()) == 1.0) { // prob += (m.getCurrentProb() * (lhpn // .getTransitionRateTree( // nextState.getTransition()) // .evaluateExpr(m.getVariables()) / m // .getTransitionSum(1.0, null))); // if (stop) { // return false; // if (stop) { // return false; // if (stop) { // return false; // else { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { ExprTree expr = new ExprTree(lhpn); expr.token = expr.intexpr_gettok(cond); expr.intexpr_L(cond); if (expr.evaluateExpr(m.getVariables()) == 1.0) { prob += m.getCurrentProb(); } } } output.put(cond.trim(), prob); } String result1 = "#total"; String result2 = "1.0"; for (String s : output.keySet()) { result1 += " " + s; result2 += " " + output.get(s); } markovResults = result1 + "\n" + result2 + "\n"; } } } return true; } } public String getMarkovResults() { return markovResults; } public boolean outputTSD(String filename) { if (probData != null) { probData.outputTSD(filename); return true; } return false; } private int findPeriod(State state) { if (stop) { return 0; } int period = 0; int color = 0; state.setColor(color); color = state.getColor() + 1; Queue<State> unVisitedStates = new LinkedList<State>(); for (State s : state.getNextStates()) { if (s.getColor() == -1) { s.setColor(color); unVisitedStates.add(s); } else { if (period == 0) { period = (state.getColor() - s.getColor() + 1); } else { period = gcd(state.getColor() - s.getColor() + 1, period); } } if (stop) { return 0; } } while (!unVisitedStates.isEmpty() && !stop) { state = unVisitedStates.poll(); color = state.getColor() + 1; for (State s : state.getNextStates()) { if (s.getColor() == -1) { s.setColor(color); unVisitedStates.add(s); } else { if (period == 0) { period = (state.getColor() - s.getColor() + 1); } else { period = gcd(state.getColor() - s.getColor() + 1, period); } } if (stop) { return 0; } } } return period; } private int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private void resetColorsForMarkovianAnalysis() { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setColor(-1); if (stop) { return; } } if (stop) { return; } } } public void resetColors() { for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { m.setColor(0); if (stop) { return; } } if (stop) { return; } } } public State getInitialState() { HashMap<String, String> allVariables = new HashMap<String, String>(); for (String var : lhpn.getBooleanVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getContVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (String var : lhpn.getIntVars()) { allVariables.put(var, lhpn.getInitialVal(var)); } for (State s : stateGraph.get(createStateVector(variables, allVariables))) { if (s.getID().equals("S0")) { return s; } } return null; } public HashMap<String, LinkedList<State>> getStateGraph() { return stateGraph; } public int getNumberOfStates() { int count = 0; for (String s : stateGraph.keySet()) { for (int i = 0; i < stateGraph.get(s).size(); i++) { count++; } } return count; } private ArrayList<String> copyArrayList(ArrayList<String> original) { ArrayList<String> copy = new ArrayList<String>(); for (String element : original) { copy.add(element); } return copy; } private HashMap<String, String> copyAllVariables(HashMap<String, String> original) { HashMap<String, String> copy = new HashMap<String, String>(); for (String s : original.keySet()) { copy.put(s, original.get(s)); } return copy; } private String createStateVector(ArrayList<String> variables, HashMap<String, String> allVariables) { String vector = ""; for (String s : variables) { if (allVariables.get(s).toLowerCase().equals("true")) { vector += "1,"; } else if (allVariables.get(s).toLowerCase().equals("false")) { vector += "0,"; } else { vector += allVariables.get(s) + ","; } } if (vector.length() > 0) { vector = vector.substring(0, vector.length() - 1); } return vector; } public void outputStateGraph(String file, boolean withProbs) { try { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(6); num.setGroupingUsed(false); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write("digraph G {\n"); for (String state : stateGraph.keySet()) { for (State m : stateGraph.get(state)) { if (withProbs) { out.write(m.getID() + " [shape=\"ellipse\",label=\"" + m.getID() + "\\n<" + state + ">\\nProb = " + num.format(m.getCurrentProb()) + "\"]\n"); } else { out.write(m.getID() + " [shape=\"ellipse\",label=\"" + m.getID() + "\\n<" + state + ">\"]\n"); } for (StateTransitionPair next : m.getNextStatesWithTrans()) { /* * System.out.println(m.getID() + " -> " + next.getState().getID() + * " [label=\"" + next.getTransition() + "\\n"); * System.out.println(m.getTransitionSum()); * System.out.println(lhpn.getTransitionRateTree( next.getTransition * ()).evaluateExpr(m.getVariables())); */ out.write(m.getID() + " -> " + next.getState().getID() + " [label=\"" + next.getTransition() + "\\n" + num.format(next.getTransition()) + "\"]\n"); // if (lhpn.getTransitionRateTree(next.getTransition()) != null) { // out.write(m.getID() // + next.getState().getID() // + " [label=\"" // + next.getTransition() // num.format((lhpn.getTransitionRateTree(next.getTransition()).evaluateExpr(m // .getVariables()) /* // * / m . getTransitionSum ( ) // */)) + "\"]\n"); // else { // out.write(m.getID() + " -> " + next.getState().getID() + // " [label=\"" + next.getTransition() + "\"]\n"); } } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error outputting state graph as dot file."); } } public void stop() { stop = true; } public boolean getStop() { return stop; } private class Transition { private String transition; private ArrayList<String> markedPlaces; private State parent; private Transition(String transition, ArrayList<String> markedPlaces, State parent) { this.transition = transition; this.markedPlaces = markedPlaces; this.parent = parent; } private String getTransition() { return transition; } private ArrayList<String> getMarkedPlaces() { return markedPlaces; } private State getParent() { return parent; } } private class StateTransitionPair { private double transition; private State state; private StateTransitionPair(State state, double transition) { this.state = state; this.transition = transition; } private State getState() { return state; } private double getTransition() { return transition; } } public class State { private String[] markings; private StateTransitionPair[] nextStates; private StateTransitionPair[] prevStates; private String stateVector; private String id; private int color; private double currentProb; private double nextProb; private double piProb; private HashMap<String, String> variables; private double transitionSum; public State(String[] markings, StateTransitionPair[] nextStates, String id, String stateVector, HashMap<String, String> variables) { this.markings = markings; this.nextStates = nextStates; prevStates = new StateTransitionPair[0]; this.id = id; this.stateVector = stateVector; color = 0; currentProb = 0.0; nextProb = 0.0; this.variables = variables; transitionSum = -1; } private String getID() { return id; } private HashMap<String, String> getVariables() { return variables; } private String[] getMarkings() { return markings; } private void setCurrentProb(double probability) { currentProb = probability; } private double getCurrentProb() { return currentProb; } private void setNextProb(double probability) { nextProb = probability; } private double getNextProb() { return nextProb; } private void setPiProb(double probability) { piProb = probability; } private double getPiProb() { return piProb; } private void setCurrentProbToNext() { currentProb = nextProb; } private void setCurrentProbToPi() { currentProb = piProb; } private void setTransitionSum(double transitionSum) { this.transitionSum = transitionSum; } private double getTransitionSum(double noRate, State n) { if (transitionSum == -1) { transitionSum = 0; for (StateTransitionPair next : nextStates) { transitionSum += next.getTransition(); // if (lhpn.getTransitionRateTree(next.getTransition()) != null) { // (!lhpn.isExpTransitionRateTree(next.getTransition()) // lhpn.getDelayTree(next.getTransition()).evaluateExpr(null) // if (n == null || next.equals(n)) { // return 1.0; // else { // return 0.0; // else { // transitionSum += // lhpn.getTransitionRateTree(next.getTransition()).evaluateExpr(variables); // else { // transitionSum += noRate; } } return transitionSum; } private StateTransitionPair[] getNextStatesWithTrans() { return nextStates; } private StateTransitionPair[] getPrevStatesWithTrans() { return prevStates; } public State[] getNextStates() { ArrayList<State> next = new ArrayList<State>(); for (StateTransitionPair st : nextStates) { next.add(st.getState()); } return next.toArray(new State[0]); } public State[] getPrevStates() { ArrayList<State> next = new ArrayList<State>(); for (StateTransitionPair st : prevStates) { next.add(st.getState()); } return next.toArray(new State[0]); } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getStateVector() { return stateVector; } private void addNextState(State nextState, double transition) { StateTransitionPair[] newNextStates = new StateTransitionPair[nextStates.length + 1]; for (int i = 0; i < nextStates.length; i++) { newNextStates[i] = nextStates[i]; } newNextStates[newNextStates.length - 1] = new StateTransitionPair(nextState, transition); nextStates = newNextStates; nextState.addPreviousState(this, transition); } private void addPreviousState(State prevState, double transition) { StateTransitionPair[] newPrevStates = new StateTransitionPair[prevStates.length + 1]; for (int i = 0; i < prevStates.length; i++) { newPrevStates[i] = prevStates[i]; } newPrevStates[newPrevStates.length - 1] = new StateTransitionPair(prevState, transition); prevStates = newPrevStates; } private void setNextStatesWithTrans(StateTransitionPair[] trans) { nextStates = trans; } private void setPrevStatesWithTrans(StateTransitionPair[] trans) { prevStates = trans; } } public void run() { } }
package utility; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import oracle.jdbc.pool.OracleDataSource; import org.postgresql.jdbc3.Jdbc3PoolingDataSource; import javax.sql.DataSource; import java.security.InvalidParameterException; import java.sql.SQLException; import java.util.Properties; // Returns a datasource for the selected vendor. // We do it in a factory function because we exploit unique method calls of the dataSources. // The code could be distributed into files in src.vendor package. public class DataSourceFactory { public static DataSource getConfiguredDataSource(Properties properties, String password) throws SQLException { String vendor = properties.getProperty("vendor"); switch (vendor) { case "MySQL": { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setConnectionAttributes("program_name:Linkifier"); dataSource.setServerName(properties.getProperty("host")); dataSource.setDatabaseName(properties.getProperty("database")); dataSource.setPortNumber(Integer.valueOf(properties.getProperty("port"))); dataSource.setUser(properties.getProperty("username")); dataSource.setPassword(password); return dataSource; } case "Oracle": { // Oracle does not return number length and count of digits always in the expected format. // We use a following workaround (it is not perfect but good enough): System.getProperties().setProperty("oracle.jdbc.J2EE13Compliant", "true"); OracleDataSource dataSource = new OracleDataSource(); dataSource.setDescription("Linkifier"); dataSource.setServerName(properties.getProperty("host")); dataSource.setDatabaseName(properties.getProperty("database")); dataSource.setPortNumber(Integer.valueOf(properties.getProperty("port"))); dataSource.setServiceName(properties.getProperty("servicename")); dataSource.setUser(properties.getProperty("username")); dataSource.setPassword(password); dataSource.setDriverType("thin"); // Use "thin" (Java based driver) even when "oci" (C based driver) is available return dataSource; } case "PostgreSQL": { Jdbc3PoolingDataSource dataSource = new Jdbc3PoolingDataSource(); dataSource.setApplicationName("Linkifier"); dataSource.setServerName(properties.getProperty("host")); dataSource.setDatabaseName(properties.getProperty("database")); dataSource.setCurrentSchema(properties.getProperty("schema")); dataSource.setPortNumber(Integer.valueOf(properties.getProperty("port"))); dataSource.setUser(properties.getProperty("username")); dataSource.setPassword(password); return dataSource; } case "Microsoft SQL Server": { SQLServerDataSource dataSource = new SQLServerDataSource(); dataSource.setApplicationName("Linkifier"); dataSource.setServerName(properties.getProperty("host")); dataSource.setDatabaseName(properties.getProperty("database")); dataSource.setPortNumber(Integer.valueOf(properties.getProperty("port"))); dataSource.setUser(properties.getProperty("username")); dataSource.setPassword(password); return dataSource; } default: throw new InvalidParameterException("Invalid db type was defined"); } } }
package mockit.internal.expectations; import java.util.*; import javax.annotation.*; import mockit.internal.expectations.invocation.*; public final class OrderedVerificationPhase extends BaseVerificationPhase { private final int expectationCount; private ExpectedInvocation unverifiedInvocationLeftBehind; private ExpectedInvocation unverifiedInvocationPrecedingVerifiedOnesLeftBehind; private boolean unverifiedExpectationsFixed; private int indexIncrement; OrderedVerificationPhase( @Nonnull RecordAndReplayExecution recordAndReplay, @Nonnull List<Expectation> expectationsInReplayOrder, @Nonnull List<Object> invocationInstancesInReplayOrder, @Nonnull List<Object[]> invocationArgumentsInReplayOrder) { super( recordAndReplay, new ArrayList<Expectation>(expectationsInReplayOrder), invocationInstancesInReplayOrder, invocationArgumentsInReplayOrder); discardExpectationsAndArgumentsAlreadyVerified(); expectationCount = expectationsInReplayOrder.size(); indexIncrement = 1; } private void discardExpectationsAndArgumentsAlreadyVerified() { for (VerifiedExpectation verified : recordAndReplay.executionState.verifiedExpectations) { int i = expectationsInReplayOrder.indexOf(verified.expectation); if (i >= 0) { expectationsInReplayOrder.set(i, null); } } } @Override protected void findNonStrictExpectation( @Nullable Object mock, @Nonnull String mockClassDesc, @Nonnull String mockNameAndDesc, @Nonnull Object[] args) { int i = replayIndex; while (i >= 0 && i < expectationCount) { Expectation replayExpectation = expectationsInReplayOrder.get(i); Object replayInstance = invocationInstancesInReplayOrder.get(i); Object[] replayArgs = invocationArgumentsInReplayOrder.get(i); i += indexIncrement; if (replayExpectation == null) { continue; } if (!matchInstance && recordAndReplay.executionState.isToBeMatchedOnInstance(mock, mockNameAndDesc)) { matchInstance = true; } if (matches(mock, mockClassDesc, mockNameAndDesc, args, replayExpectation, replayInstance, replayArgs)) { currentExpectation = replayExpectation; i += 1 - indexIncrement; indexIncrement = 1; replayIndex = i; expectationBeingVerified().constraints.invocationCount++; mapNewInstanceToReplacementIfApplicable(mock); break; } if (!unverifiedExpectationsFixed) { unverifiedInvocationLeftBehind = replayExpectation.invocation; } else if (indexIncrement > 0) { recordAndReplay.setErrorThrown(replayExpectation.invocation.errorForUnexpectedInvocation()); replayIndex = i; break; } } } public void fixPositionOfUnverifiedExpectations() { if (unverifiedInvocationLeftBehind != null) { throw currentExpectation == null ? unverifiedInvocationLeftBehind.errorForUnexpectedInvocation() : unverifiedInvocationLeftBehind.errorForUnexpectedInvocationBeforeAnother(currentExpectation.invocation); } int indexOfLastUnverified = indexOfLastUnverifiedExpectation(); if (indexOfLastUnverified >= 0) { replayIndex = indexOfLastUnverified; indexIncrement = -1; unverifiedExpectationsFixed = true; } } private int indexOfLastUnverifiedExpectation() { for (int i = expectationCount - 1; i >= 0; i if (expectationsInReplayOrder.get(i) != null) { return i; } } return -1; } @SuppressWarnings("OverlyComplexMethod") @Override public void handleInvocationCountConstraint(int minInvocations, int maxInvocations) { Error errorThrown = pendingError; pendingError = null; if (errorThrown != null && minInvocations > 0) { throw errorThrown; } Expectation verifying = expectationBeingVerified(); ExpectedInvocation invocation = verifying.invocation; argMatchers = invocation.arguments.getMatchers(); int invocationCount = 1; while (replayIndex < expectationCount) { Expectation replayExpectation = expectationsInReplayOrder.get(replayIndex); if (replayExpectation != null && matchesCurrentVerification(replayExpectation)) { invocationCount++; verifying.constraints.invocationCount++; if (invocationCount > maxInvocations) { if (maxInvocations >= 0 && numberOfIterations <= 1) { throw replayExpectation.invocation.errorForUnexpectedInvocation(); } break; } } else if (invocationCount >= minInvocations) { break; } replayIndex++; } argMatchers = null; int n = minInvocations - invocationCount; if (n > 0) { throw invocation.errorForMissingInvocations(n); } verifyMaxInvocations(maxInvocations); } private boolean matchesCurrentVerification(@Nonnull Expectation replayExpectation) { ExpectedInvocation invocation = expectationBeingVerified().invocation; Object mock = invocation.instance; String mockClassDesc = invocation.getClassDesc(); String mockNameAndDesc = invocation.getMethodNameAndDescription(); Object[] args = invocation.arguments.getValues(); matchInstance = invocation.matchInstance; if (recordAndReplay.executionState.isToBeMatchedOnInstance(mock, mockNameAndDesc)) { matchInstance = true; } Object replayInstance = invocationInstancesInReplayOrder.get(replayIndex); Object[] replayArgs = invocationArgumentsInReplayOrder.get(replayIndex); return matches(mock, mockClassDesc, mockNameAndDesc, args, replayExpectation, replayInstance, replayArgs); } private void verifyMaxInvocations(int maxInvocations) { if (maxInvocations >= 0) { int multiplier = numberOfIterations <= 1 ? 1 : numberOfIterations; Expectation verifying = expectationBeingVerified(); int n = verifying.constraints.invocationCount - maxInvocations * multiplier; if (n > 0) { Object[] replayArgs = invocationArgumentsInReplayOrder.get(replayIndex - 1); throw verifying.invocation.errorForUnexpectedInvocations(replayArgs, n); } } } @Nullable @Override protected Error endVerification() { if (pendingError != null) { return pendingError; } if ( unverifiedExpectationsFixed && indexIncrement > 0 && currentExpectation != null && replayIndex <= indexOfLastUnverifiedExpectation() ) { ExpectedInvocation unexpectedInvocation = expectationsInReplayOrder.get(replayIndex).invocation; return unexpectedInvocation.errorForUnexpectedInvocationAfterAnother(currentExpectation.invocation); } if (unverifiedInvocationPrecedingVerifiedOnesLeftBehind != null) { return unverifiedInvocationPrecedingVerifiedOnesLeftBehind.errorForUnexpectedInvocation(); } Error error = verifyRemainingIterations(); if (error != null) { return error; } return super.endVerification(); } @Nullable private Error verifyRemainingIterations() { int expectationsVerifiedInFirstIteration = recordAndReplay.executionState.verifiedExpectations.size(); for (int i = 1; i < numberOfIterations; i++) { Error error = verifyNextIterationOfWholeBlockOfInvocations(expectationsVerifiedInFirstIteration); if (error != null) { return error; } } return null; } @Nullable private Error verifyNextIterationOfWholeBlockOfInvocations(int expectationsVerifiedInFirstIteration) { List<VerifiedExpectation> expectationsVerified = recordAndReplay.executionState.verifiedExpectations; for (int i = 0; i < expectationsVerifiedInFirstIteration; i++) { VerifiedExpectation verifiedExpectation = expectationsVerified.get(i); ExpectedInvocation invocation = verifiedExpectation.expectation.invocation; argMatchers = verifiedExpectation.argMatchers; handleInvocation( invocation.instance, 0, invocation.getClassDesc(), invocation.getMethodNameAndDescription(), null, false, verifiedExpectation.arguments); Error testFailure = recordAndReplay.getErrorThrown(); if (testFailure != null) { return testFailure; } } return null; } @Override boolean shouldDiscardInformationAboutVerifiedInvocationOnceUsed() { return true; } public void checkOrderOfVerifiedInvocations(@Nonnull BaseVerificationPhase verificationPhase) { if (verificationPhase instanceof OrderedVerificationPhase) { throw new IllegalArgumentException("Invalid use of ordered verification block"); } UnorderedVerificationPhase previousVerification = (UnorderedVerificationPhase) verificationPhase; if (previousVerification.verifiedExpectations.isEmpty()) { return; } if (indexIncrement > 0) { checkForwardOrderOfVerifiedInvocations(previousVerification); } else { checkBackwardOrderOfVerifiedInvocations(previousVerification); } } private void checkForwardOrderOfVerifiedInvocations(@Nonnull UnorderedVerificationPhase previousVerification) { int maxReplayIndex = replayIndex - 1; for (VerifiedExpectation verified : previousVerification.verifiedExpectations) { if (verified.replayIndex < replayIndex) { ExpectedInvocation unexpectedInvocation = verified.expectation.invocation; throw currentExpectation == null ? unexpectedInvocation.errorForUnexpectedInvocationFoundBeforeAnother() : unexpectedInvocation.errorForUnexpectedInvocationFoundBeforeAnother(currentExpectation.invocation); } if (verified.replayIndex > maxReplayIndex) { maxReplayIndex = verified.replayIndex; } } for (int i = replayIndex; i < maxReplayIndex; i++) { Expectation expectation = expectationsInReplayOrder.get(i); if (expectation != null) { unverifiedInvocationPrecedingVerifiedOnesLeftBehind = expectation.invocation; break; } } replayIndex = maxReplayIndex + 1; currentExpectation = replayIndex < expectationCount ? expectationsInReplayOrder.get(replayIndex) : null; } private void checkBackwardOrderOfVerifiedInvocations(@Nonnull UnorderedVerificationPhase previousVerification) { int indexOfLastUnverified = indexOfLastUnverifiedExpectation(); if (indexOfLastUnverified >= 0) { VerifiedExpectation firstVerified = previousVerification.firstExpectationVerified(); assert firstVerified != null; if (firstVerified.replayIndex != indexOfLastUnverified + 1) { Expectation lastUnverified = expectationsInReplayOrder.get(indexOfLastUnverified); Expectation after = firstVerified.expectation; throw lastUnverified.invocation.errorForUnexpectedInvocationAfterAnother(after.invocation); } } } }
package io.mangoo.routing.bindings; import java.util.HashMap; import java.util.Map; import org.boon.json.JsonFactory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.ReadContext; import io.mangoo.authentication.Authentication; import io.mangoo.core.Application; import io.mangoo.interfaces.MangooValidator; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.util.HeaderMap; import io.undertow.util.HttpString; /** * * @author svenkubiak * */ public class Request implements MangooValidator { private HttpServerExchange httpServerExchange; private String body; private Session session; private String authenticityToken; private Authentication authentication; private Validator validator; private Map<String, String> parameter; private Map<String, Cookie> cookies; public Request(){ } public Request(HttpServerExchange httpServerExchange, Session session, String authenticityToken, Authentication authentication, Map<String, String> parameter, String body) { Preconditions.checkNotNull(httpServerExchange, "httpServerExchange can not be null"); this.httpServerExchange = httpServerExchange; this.session = session; this.authenticityToken = authenticityToken; this.authentication = authentication; this.body = body; this.parameter = parameter; this.validator = Application.getInstance(Validator.class); this.validator.setValues(this.parameter); this.cookies = (httpServerExchange.getRequestCookies() == null) ? new HashMap<String, Cookie>() : ImmutableMap.copyOf(httpServerExchange.getRequestCookies()); } /** * @return The current session */ public Session getSession() { return this.session; } /** * * @return The request body */ public String getBody() { return this.body; } /** * * @return The request body as Map object */ @SuppressWarnings("unchecked") public Map<String, Object> getBodyAsJsonMap() { return JsonFactory.create().readValue(this.body, Map.class); } /** * * @return The request body as JsonPath object */ public ReadContext getBodyAsJsonPath() { return JsonPath.parse(this.body); } /** * Checks if the session bound authenticity token matches the client sent * authenticity token * * @return True if the token matches, false otherwise */ public boolean authenticityMatches() { return this.session.getAuthenticityToken().equals(this.authenticityToken); } /** * @return The current authentication */ public Authentication getAuthentication() { return authentication; } /** * Retrieves a request parameter (request or query parameter) by its name * * @param key The key to lookup the parameter * @return The value for the given or null if none found */ public String getParameter(String key) { return this.parameter.get(key); } /** * Retrieves a map of request parameter (request or query parameter) * * @return Map of request and query parameter */ public Map<String, String> getParameter() { return this.parameter; } /** * Retrieves a list of all headers send by the client * * @return A HeaderMap of client sent headers */ public HeaderMap getHeaders() { return this.httpServerExchange.getRequestHeaders(); } /** * Retrieves a specific header value by its name * * @param headerName The name of the header to retrieve * @return The value of the header or null if none found */ public String getHeader(HttpString headerName) { return (this.httpServerExchange.getRequestHeaders().get(headerName) == null) ? null : this.httpServerExchange.getRequestHeaders().get(headerName).element(); } public String getURI() { return this.httpServerExchange.getRequestURI(); } /** * Reconstructs the complete URL as seen by the user. This includes scheme, host name etc, * but does not include query string. * * This is not decoded. * * @return The request URL */ public String getURL() { return this.httpServerExchange.getRequestURL(); } /** * @return An immutable map of request cookies */ public Map<String, Cookie> getCookies() { return this.cookies; } /** * Retrieves a single cookie from the request * * @param name The name of the cookie * @return The Cookie */ public Cookie getCookie(String name) { return this.cookies.get(name); } /** * Get the request URI scheme. Normally this is one of {@code http} or {@code https}. * * @return the request URI scheme */ public String getScheme() { return this.httpServerExchange.getRequestScheme(); } /** * Returns the request charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getCharset() { return this.httpServerExchange.getRequestCharset(); } /** * @return The content length of the request, or <code>-1</code> if it has not been set */ public long getContentLength() { return this.httpServerExchange.getRequestContentLength(); } /** * Get the HTTP request method. Normally this is one of the strings listed in {@link io.undertow.util.Methods}. * * @return the HTTP request method */ public HttpString getMethod() { return this.httpServerExchange.getRequestMethod(); } public String getPath() { return this.httpServerExchange.getRequestPath(); } @Override public Validator validation() { return this.validator; } @Override public String getError(String name) { return this.validator.hasError(name) ? this.validator.getError(name) : ""; } }
package com.ihtsdo.snomed.dto.refset; import java.util.ArrayList; import java.util.List; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import com.google.common.base.Objects; import com.google.common.primitives.Longs; import com.ihtsdo.snomed.exception.UnrecognisedRefsetException; import com.ihtsdo.snomed.model.Concept; import com.ihtsdo.snomed.model.refset.RefsetPlan; import com.ihtsdo.snomed.model.refset.RefsetRule; import com.ihtsdo.snomed.model.refset.Visitor; import com.ihtsdo.snomed.model.refset.rule.BaseSetOperationRefsetRule; import com.ihtsdo.snomed.model.refset.rule.ListConceptsRefsetRule; @XmlRootElement(name="plan") public class RefsetPlanDto { @Transient private long id; public RefsetPlanDto(){} @XmlElementWrapper(name = "rules") @XmlElement(name="rule") private List<RefsetRuleDto> refsetRules = new ArrayList<>(); @NotNull(message="validation.refsetplan.terminal.not.null") private Long terminal; @Override public String toString(){ return Objects.toStringHelper(this) .add("id", getId()) .add("refsetRules", getRefsetRules()) .add("terminal", getTerminal()) .toString(); } @Override public boolean equals(Object o){ if (o instanceof RefsetPlanDto){ RefsetPlanDto dto = (RefsetPlanDto) o; if (Objects.equal(dto.getId(), getId()) && (Objects.equal(dto.getRefsetRules(), getRefsetRules())) && (Objects.equal(dto.getTerminal(), getTerminal()))){ return true; } } return false; } @Override public int hashCode(){ return Longs.hashCode(getId()); } public long getId() { return id; } public void setId(long id) { this.id = id; } public List<RefsetRuleDto> getRefsetRules() { return refsetRules; } public void setRefsetRules(List<RefsetRuleDto> refsetRules) { this.refsetRules = refsetRules; } public void addRefsetRule(RefsetRuleDto refsetRule){ this.refsetRules.add(refsetRule); } public Long getTerminal() { return terminal; } public void setTerminal(Long terminal) { this.terminal = terminal; } public static RefsetPlanDto parse(RefsetPlan plan){ RefsetPlanParser parser = new RefsetPlanParser(); RefsetPlanDto planDto = null; if (plan.getTerminal() != null){ plan.getTerminal().accept(parser); planDto = parser.getPlanDto(); planDto.setTerminal(plan.getTerminal().getId()); }else{ planDto = new RefsetPlanDto(); } planDto.setId(plan.getId()); return planDto; } private static class RefsetPlanParser implements Visitor{ private RefsetPlanDto built = new RefsetPlanDto(); public RefsetPlanDto getPlanDto(){ return built; } @Override public void visit(RefsetRule rule) { RefsetRuleDto refsetRuleDto = new RefsetRuleDto(); refsetRuleDto.setType(RefsetRuleDto.CLASS_TYPE_MAP.get(rule.getClass())); refsetRuleDto.setId(rule.getId()); if (rule instanceof ListConceptsRefsetRule){ ListConceptsRefsetRule lcRule = (ListConceptsRefsetRule)rule; for (Concept c : lcRule.getConcepts()){ ConceptDto conceptDto = new ConceptDto(c.getSerialisedId()); conceptDto.setTitle(c.getDisplayName()); refsetRuleDto.addConcept(conceptDto); } } else if (rule instanceof BaseSetOperationRefsetRule){ BaseSetOperationRefsetRule setOperationRule = (BaseSetOperationRefsetRule) rule; refsetRuleDto.setLeft(setOperationRule.getLeft() == null ? null : setOperationRule.getLeft().getId()); refsetRuleDto.setRight(setOperationRule.getRight() == null ? null : setOperationRule.getRight().getId()); }else{ throw new UnrecognisedRefsetException("I've not been able to handle RefsetRule of class " + rule.getClass()); } built.refsetRules.add(refsetRuleDto); } } public static Builder getBuilder() { return new Builder(); } public static class Builder{ private RefsetPlanDto built; Builder() { built = new RefsetPlanDto(); } public Builder id(long id){ built.setId(id); return this; } public Builder add(RefsetRuleDto ruleDto){ built.addRefsetRule(ruleDto); return this; } public Builder terminal(Long terminalId){ built.setTerminal(terminalId); return this; } public RefsetPlanDto build() { return built; } } }
/* @java.file.header */ package org.gridgain.grid; import org.gridgain.client.ssl.*; import org.gridgain.grid.cache.*; import org.gridgain.grid.compute.*; import org.gridgain.grid.dotnet.*; import org.gridgain.grid.dr.hub.receiver.*; import org.gridgain.grid.dr.hub.sender.*; import org.gridgain.grid.events.*; import org.gridgain.grid.ggfs.*; import org.gridgain.grid.hadoop.*; import org.gridgain.grid.kernal.managers.eventstorage.*; import org.gridgain.grid.lang.*; import org.gridgain.grid.logger.*; import org.gridgain.grid.marshaller.*; import org.gridgain.grid.marshaller.jdk.*; import org.gridgain.grid.marshaller.optimized.*; import org.gridgain.grid.portables.*; import org.gridgain.grid.security.*; import org.gridgain.grid.segmentation.*; import org.gridgain.grid.service.*; import org.gridgain.grid.spi.authentication.*; import org.gridgain.grid.spi.authentication.noop.*; import org.gridgain.grid.spi.checkpoint.*; import org.gridgain.grid.spi.checkpoint.noop.*; import org.gridgain.grid.spi.collision.*; import org.gridgain.grid.spi.collision.noop.*; import org.gridgain.grid.spi.communication.*; import org.gridgain.grid.spi.communication.tcp.*; import org.gridgain.grid.spi.deployment.*; import org.gridgain.grid.spi.deployment.local.*; import org.gridgain.grid.spi.discovery.*; import org.gridgain.grid.spi.discovery.tcp.*; import org.gridgain.grid.spi.eventstorage.*; import org.gridgain.grid.spi.eventstorage.memory.*; import org.gridgain.grid.spi.failover.*; import org.gridgain.grid.spi.failover.always.*; import org.gridgain.grid.spi.indexing.*; import org.gridgain.grid.spi.loadbalancing.*; import org.gridgain.grid.spi.loadbalancing.roundrobin.*; import org.gridgain.grid.spi.securesession.*; import org.gridgain.grid.spi.securesession.noop.*; import org.gridgain.grid.spi.swapspace.*; import org.gridgain.grid.spi.swapspace.file.*; import org.gridgain.grid.streamer.*; import org.gridgain.grid.util.typedef.internal.*; import org.jetbrains.annotations.*; import javax.management.*; import java.lang.management.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import static org.gridgain.grid.segmentation.GridSegmentationPolicy.*; /** * This class defines grid runtime configuration. This configuration is passed to * {@link GridGain#start(GridConfiguration)} method. It defines all configuration * parameters required to start a grid instance. Usually, a special * class called "loader" will create an instance of this interface and apply * {@link GridGain#start(GridConfiguration)} method to initialize GridGain instance. * <p> * Note that you should only set values that differ from defaults, as grid * will automatically pick default values for all values that are not set. * <p> * For more information about grid configuration and startup refer to {@link GridGain} * documentation. */ public class GridConfiguration { /** Courtesy notice log category. */ public static final String COURTESY_LOGGER_NAME = "org.gridgain.grid.CourtesyConfigNotice"; /** * Default flag for peer class loading. By default the value is {@code false} * which means that peer class loading is disabled. */ public static final boolean DFLT_P2P_ENABLED = false; /** Default metrics history size (value is {@code 10000}). */ public static final int DFLT_METRICS_HISTORY_SIZE = 10000; /** Default metrics update frequency. */ public static final long DFLT_METRICS_UPDATE_FREQ = 2000; /** * Default metrics expire time. The value is {@link Long#MAX_VALUE} which * means that metrics never expire. */ public static final long DFLT_METRICS_EXPIRE_TIME = Long.MAX_VALUE; /** Default maximum timeout to wait for network responses in milliseconds (value is {@code 5,000ms}). */ public static final long DFLT_NETWORK_TIMEOUT = 5000; /** Default interval between message send retries. */ public static final long DFLT_SEND_RETRY_DELAY = 1000; /** Default message send retries count. */ public static final int DFLT_SEND_RETRY_CNT = 3; /** Default number of clock sync samples. */ public static final int DFLT_CLOCK_SYNC_SAMPLES = 8; /** Default clock synchronization frequency. */ public static final int DFLT_CLOCK_SYNC_FREQUENCY = 120000; /** Default discovery startup delay in milliseconds (value is {@code 60,000ms}). */ public static final long DFLT_DISCOVERY_STARTUP_DELAY = 60000; /** Default deployment mode (value is {@link GridDeploymentMode#SHARED}). */ public static final GridDeploymentMode DFLT_DEPLOYMENT_MODE = GridDeploymentMode.SHARED; /** Default cache size for missed resources. */ public static final int DFLT_P2P_MISSED_RESOURCES_CACHE_SIZE = 100; /** Default SMTP port. */ public static final int DFLT_SMTP_PORT = 25; /** Default SSL enabled flag. */ public static final boolean DFLT_SMTP_SSL = false; /** Default STARTTLS enabled flag. */ public static final boolean DFLT_SMTP_STARTTLS = false; /** Default FROM email address. */ public static final String DFLT_SMTP_FROM_EMAIL = "info@gridgain.com"; /** Default time server port base. */ public static final int DFLT_TIME_SERVER_PORT_BASE = 31100; /** Default time server port range. */ public static final int DFLT_TIME_SERVER_PORT_RANGE = 100; /** Default core size of public thread pool. */ public static final int DFLT_PUBLIC_CORE_THREAD_CNT = Math.max(8, Runtime.getRuntime().availableProcessors()) * 2; /** Default max size of public thread pool. */ public static final int DFLT_PUBLIC_MAX_THREAD_CNT = DFLT_PUBLIC_CORE_THREAD_CNT; /** Default keep alive time for public thread pool. */ public static final long DFLT_PUBLIC_KEEP_ALIVE_TIME = 0; /** Default max queue capacity of public thread pool. */ public static final int DFLT_PUBLIC_THREADPOOL_QUEUE_CAP = Integer.MAX_VALUE; /** Default size of system thread pool. */ public static final int DFLT_SYSTEM_CORE_THREAD_CNT = DFLT_PUBLIC_CORE_THREAD_CNT; /** Default max size of system thread pool. */ public static final int DFLT_SYSTEM_MAX_THREAD_CNT = DFLT_PUBLIC_CORE_THREAD_CNT; /** Default keep alive time for system thread pool. */ public static final long DFLT_SYSTEM_KEEP_ALIVE_TIME = 0; /** Default max queue capacity of system thread pool. */ public static final int DFLT_SYSTEM_THREADPOOL_QUEUE_CAP = Integer.MAX_VALUE; /** Default size of peer class loading thread pool. */ public static final int DFLT_P2P_THREAD_CNT = 2; /** Default size of management thread pool. */ public static final int DFLT_MGMT_THREAD_CNT = 4; /** Default max queue capacity of GGFS thread pool. */ public static final int DFLT_GGFS_THREADPOOL_QUEUE_CAP = 16; /** Default size of REST thread pool. */ public static final int DFLT_REST_CORE_THREAD_CNT = DFLT_PUBLIC_CORE_THREAD_CNT; /** Default max size of REST thread pool. */ public static final int DFLT_REST_MAX_THREAD_CNT = DFLT_PUBLIC_CORE_THREAD_CNT; /** Default keep alive time for REST thread pool. */ public static final long DFLT_REST_KEEP_ALIVE_TIME = 0; /** Default max queue capacity of REST thread pool. */ public static final int DFLT_REST_THREADPOOL_QUEUE_CAP = Integer.MAX_VALUE; /** Default segmentation policy. */ public static final GridSegmentationPolicy DFLT_SEG_PLC = STOP; /** Default value for wait for segment on startup flag. */ public static final boolean DFLT_WAIT_FOR_SEG_ON_START = true; /** Default value for all segmentation resolvers pass required. */ public static final boolean DFLT_ALL_SEG_RESOLVERS_PASS_REQ = true; /** Default value segmentation resolve attempts count. */ public static final int DFLT_SEG_RESOLVE_ATTEMPTS = 2; /** Default segment check frequency in discovery manager. */ public static final long DFLT_SEG_CHK_FREQ = 10000; /** Default frequency of metrics log print out. */ public static final long DFLT_METRICS_LOG_FREQ = 60000; /** Default TCP server port. */ public static final int DFLT_TCP_PORT = 11211; /** Default TCP_NODELAY flag. */ public static final boolean DFLT_TCP_NODELAY = true; /** Default TCP direct buffer flag. */ public static final boolean DFLT_REST_TCP_DIRECT_BUF = false; /** Default REST idle timeout. */ public static final int DFLT_REST_IDLE_TIMEOUT = 7000; /** Default rest port range. */ public static final int DFLT_REST_PORT_RANGE = 100; /** Default marshal local jobs flag. */ public static final boolean DFLT_MARSHAL_LOCAL_JOBS = false; /** Default value for cache sanity check enabled flag. */ public static final boolean DFLT_CACHE_SANITY_CHECK_ENABLED = true; /** Optional grid name. */ private String gridName; /** User attributes. */ private Map<String, ?> userAttrs; /** Logger. */ private GridLogger log; /** Executor service. */ private ExecutorService execSvc; /** Executor service. */ private ExecutorService sysSvc; /** Management executor service. */ private ExecutorService mgmtSvc; /** GGFS executor service. */ private ExecutorService ggfsSvc; /** REST requests executor service. */ private ExecutorService restExecSvc; /** Peer class loading executor service shutdown flag. */ private boolean p2pSvcShutdown = true; /** Executor service shutdown flag. */ private boolean execSvcShutdown = true; /** System executor service shutdown flag. */ private boolean sysSvcShutdown = true; /** Management executor service shutdown flag. */ private boolean mgmtSvcShutdown = true; /** GGFS executor service shutdown flag. */ private boolean ggfsSvcShutdown = true; /** REST executor service shutdown flag. */ private boolean restSvcShutdown = true; /** Lifecycle email notification. */ private boolean lifeCycleEmailNtf = true; /** Executor service. */ private ExecutorService p2pSvc; /** Gridgain installation folder. */ private String ggHome; /** Gridgain work folder. */ private String ggWork; /** MBean server. */ private MBeanServer mbeanSrv; /** Local node ID. */ private UUID nodeId; /** Marshaller. */ private GridMarshaller marsh; /** Marshal local jobs. */ private boolean marshLocJobs = DFLT_MARSHAL_LOCAL_JOBS; /** Daemon flag. */ private boolean daemon; /** Jetty XML configuration path. */ private String jettyPath; /** {@code REST} flag. */ private boolean restEnabled; /** Whether or not peer class loading is enabled. */ private boolean p2pEnabled = DFLT_P2P_ENABLED; /** List of package prefixes from the system class path that should be P2P loaded. */ private String[] p2pLocClsPathExcl; /** Events of these types should be recorded. */ private int[] inclEvtTypes; /** Maximum network requests timeout. */ private long netTimeout = DFLT_NETWORK_TIMEOUT; /** Interval between message send retries. */ private long sndRetryDelay = DFLT_SEND_RETRY_DELAY; /** Message send retries delay. */ private int sndRetryCnt = DFLT_SEND_RETRY_CNT; /** Number of samples for clock synchronization. */ private int clockSyncSamples = DFLT_CLOCK_SYNC_SAMPLES; /** Clock synchronization frequency. */ private long clockSyncFreq = DFLT_CLOCK_SYNC_FREQUENCY; /** Metrics history time. */ private int metricsHistSize = DFLT_METRICS_HISTORY_SIZE; /** Full metrics enabled flag. */ private long metricsUpdateFreq = DFLT_METRICS_UPDATE_FREQ; /** Metrics expire time. */ private long metricsExpTime = DFLT_METRICS_EXPIRE_TIME; /** Collection of life-cycle beans. */ private GridLifecycleBean[] lifecycleBeans; /** Discovery SPI. */ private GridDiscoverySpi discoSpi; /** Segmentation policy. */ private GridSegmentationPolicy segPlc = DFLT_SEG_PLC; /** Segmentation resolvers. */ private GridSegmentationResolver[] segResolvers; /** Segmentation resolve attempts count. */ private int segResolveAttempts = DFLT_SEG_RESOLVE_ATTEMPTS; /** Wait for segment on startup flag. */ private boolean waitForSegOnStart = DFLT_WAIT_FOR_SEG_ON_START; /** All segmentation resolvers pass required flag. */ private boolean allResolversPassReq = DFLT_ALL_SEG_RESOLVERS_PASS_REQ; /** Segment check frequency. */ private long segChkFreq = DFLT_SEG_CHK_FREQ; /** Communication SPI. */ private GridCommunicationSpi commSpi; /** Event storage SPI. */ private GridEventStorageSpi evtSpi; /** Collision SPI. */ private GridCollisionSpi colSpi; /** Authentication SPI. */ private GridAuthenticationSpi authSpi; /** Secure session SPI. */ private GridSecureSessionSpi sesSpi; /** Deployment SPI. */ private GridDeploymentSpi deploySpi; /** Checkpoint SPI. */ private GridCheckpointSpi[] cpSpi; /** Failover SPI. */ private GridFailoverSpi[] failSpi; /** Load balancing SPI. */ private GridLoadBalancingSpi[] loadBalancingSpi; /** Checkpoint SPI. */ private GridSwapSpaceSpi swapSpaceSpi; /** Indexing SPI. */ private GridIndexingSpi[] indexingSpi; /** Address resolver. */ private GridAddressResolver addrRslvr; /** Cache configurations. */ private GridCacheConfiguration[] cacheCfg; /** Configuration for .Net nodes. */ private GridDotNetConfiguration dotNetCfg; /** Flag indicating whether cache sanity check is enabled. */ private boolean cacheSanityCheckEnabled = DFLT_CACHE_SANITY_CHECK_ENABLED; /** Discovery startup delay. */ private long discoStartupDelay = DFLT_DISCOVERY_STARTUP_DELAY; /** Tasks classes sharing mode. */ private GridDeploymentMode deployMode = DFLT_DEPLOYMENT_MODE; /** Cache size of missed resources. */ private int p2pMissedCacheSize = DFLT_P2P_MISSED_RESOURCES_CACHE_SIZE; private String smtpHost; private int smtpPort = DFLT_SMTP_PORT; private String smtpUsername; private String smtpPwd; private String[] adminEmails; private String smtpFromEmail = DFLT_SMTP_FROM_EMAIL; private boolean smtpSsl = DFLT_SMTP_SSL; private boolean smtpStartTls = DFLT_SMTP_STARTTLS; /** Local host. */ private String locHost; /** Base port number for time server. */ private int timeSrvPortBase = DFLT_TIME_SERVER_PORT_BASE; /** Port number range for time server. */ private int timeSrvPortRange = DFLT_TIME_SERVER_PORT_RANGE; /** REST secret key. */ private String restSecretKey; /** Property names to include into node attributes. */ private String[] includeProps; private String licUrl; /** Frequency of metrics log print out. */ @SuppressWarnings("RedundantFieldInitialization") private long metricsLogFreq = DFLT_METRICS_LOG_FREQ; /** Local event listeners. */ private Map<GridPredicate<? extends GridEvent>, int[]> lsnrs; /** TCP host. */ private String restTcpHost; /** TCP port. */ private int restTcpPort = DFLT_TCP_PORT; /** TCP no delay flag. */ private boolean restTcpNoDelay = DFLT_TCP_NODELAY; /** REST TCP direct buffer flag. */ private boolean restTcpDirectBuf = DFLT_REST_TCP_DIRECT_BUF; /** REST TCP send buffer size. */ private int restTcpSndBufSize; /** REST TCP receive buffer size. */ private int restTcpRcvBufSize; /** REST TCP send queue limit. */ private int restTcpSndQueueLimit; /** REST TCP selector count. */ private int restTcpSelectorCnt = Math.min(4, Runtime.getRuntime().availableProcessors()); /** Idle timeout. */ private long restIdleTimeout = DFLT_REST_IDLE_TIMEOUT; /** SSL enable flag, default is disabled. */ private boolean restTcpSslEnabled; /** SSL need client auth flag. */ private boolean restTcpSslClientAuth; /** SSL context factory for rest binary server. */ private GridSslContextFactory restTcpSslCtxFactory; /** Port range */ private int restPortRange = DFLT_REST_PORT_RANGE; /** Folders accessible by REST. */ private String[] restAccessibleFolders; /** GGFS configuration. */ private GridGgfsConfiguration[] ggfsCfg; /** Client message interceptor. */ private GridClientMessageInterceptor clientMsgInterceptor; /** Streamer configuration. */ private GridStreamerConfiguration[] streamerCfg; /** Data center receiver hub configuration. */ private GridDrReceiverHubConfiguration drRcvHubCfg; /** Data center sender hub configuration. */ private GridDrSenderHubConfiguration drSndHubCfg; /** Data center ID. */ private byte dataCenterId; /** Security credentials. */ private GridSecurityCredentialsProvider securityCred; /** Service configuration. */ private GridServiceConfiguration[] svcCfgs; /** Hadoop configuration. */ private GridHadoopConfiguration hadoopCfg; /** Client access configuration. */ private GridClientConnectionConfiguration clientCfg; /** Portable configuration. */ private GridPortableConfiguration portableCfg; /** Warmup closure. Will be invoked before actual grid start. */ private GridInClosure<GridConfiguration> warmupClos; /** * Creates valid grid configuration with all default values. */ public GridConfiguration() { // No-op. } /** * Creates grid configuration by coping all configuration properties from * given configuration. * * @param cfg Grid configuration to copy from. */ @SuppressWarnings("deprecation") public GridConfiguration(GridConfiguration cfg) { assert cfg != null; // SPIs. discoSpi = cfg.getDiscoverySpi(); commSpi = cfg.getCommunicationSpi(); deploySpi = cfg.getDeploymentSpi(); evtSpi = cfg.getEventStorageSpi(); cpSpi = cfg.getCheckpointSpi(); colSpi = cfg.getCollisionSpi(); failSpi = cfg.getFailoverSpi(); authSpi = cfg.getAuthenticationSpi(); sesSpi = cfg.getSecureSessionSpi(); loadBalancingSpi = cfg.getLoadBalancingSpi(); swapSpaceSpi = cfg.getSwapSpaceSpi(); indexingSpi = cfg.getIndexingSpi(); /* * Order alphabetically for maintenance purposes. */ addrRslvr = cfg.getAddressResolver(); adminEmails = cfg.getAdminEmails(); allResolversPassReq = cfg.isAllSegmentationResolversPassRequired(); daemon = cfg.isDaemon(); cacheCfg = cfg.getCacheConfiguration(); cacheSanityCheckEnabled = cfg.isCacheSanityCheckEnabled(); clientCfg = cfg.getClientConnectionConfiguration(); clientMsgInterceptor = cfg.getClientMessageInterceptor(); clockSyncFreq = cfg.getClockSyncFrequency(); clockSyncSamples = cfg.getClockSyncSamples(); dataCenterId = cfg.getDataCenterId(); deployMode = cfg.getDeploymentMode(); discoStartupDelay = cfg.getDiscoveryStartupDelay(); drRcvHubCfg = cfg.getDrReceiverHubConfiguration() != null ? new GridDrReceiverHubConfiguration(cfg.getDrReceiverHubConfiguration()) : null; drSndHubCfg = cfg.getDrSenderHubConfiguration() != null ? new GridDrSenderHubConfiguration(cfg.getDrSenderHubConfiguration()) : null; execSvc = cfg.getExecutorService(); execSvcShutdown = cfg.getExecutorServiceShutdown(); ggHome = cfg.getGridGainHome(); ggWork = cfg.getWorkDirectory(); gridName = cfg.getGridName(); ggfsCfg = cfg.getGgfsConfiguration(); ggfsSvc = cfg.getGgfsExecutorService(); ggfsSvcShutdown = cfg.getGgfsExecutorServiceShutdown(); hadoopCfg = cfg.getHadoopConfiguration(); inclEvtTypes = cfg.getIncludeEventTypes(); includeProps = cfg.getIncludeProperties(); jettyPath = cfg.getRestJettyPath(); licUrl = cfg.getLicenseUrl(); lifecycleBeans = cfg.getLifecycleBeans(); lifeCycleEmailNtf = cfg.isLifeCycleEmailNotification(); locHost = cfg.getLocalHost(); log = cfg.getGridLogger(); lsnrs = cfg.getLocalEventListeners(); marsh = cfg.getMarshaller(); marshLocJobs = cfg.isMarshalLocalJobs(); mbeanSrv = cfg.getMBeanServer(); metricsHistSize = cfg.getMetricsHistorySize(); metricsExpTime = cfg.getMetricsExpireTime(); metricsLogFreq = cfg.getMetricsLogFrequency(); metricsUpdateFreq = cfg.getMetricsUpdateFrequency(); mgmtSvc = cfg.getManagementExecutorService(); mgmtSvcShutdown = cfg.getManagementExecutorServiceShutdown(); netTimeout = cfg.getNetworkTimeout(); nodeId = cfg.getNodeId(); p2pEnabled = cfg.isPeerClassLoadingEnabled(); p2pLocClsPathExcl = cfg.getPeerClassLoadingLocalClassPathExclude(); p2pMissedCacheSize = cfg.getPeerClassLoadingMissedResourcesCacheSize(); p2pSvc = cfg.getPeerClassLoadingExecutorService(); p2pSvcShutdown = cfg.getPeerClassLoadingExecutorServiceShutdown(); portableCfg = cfg.getPortableConfiguration(); restAccessibleFolders = cfg.getRestAccessibleFolders(); restEnabled = cfg.isRestEnabled(); restIdleTimeout = cfg.getRestIdleTimeout(); restPortRange = cfg.getRestPortRange(); restSecretKey = cfg.getRestSecretKey(); restTcpHost = cfg.getRestTcpHost(); restTcpNoDelay = cfg.isRestTcpNoDelay(); restTcpDirectBuf = cfg.isRestTcpDirectBuffer(); restTcpSndBufSize = cfg.getRestTcpSendBufferSize(); restTcpRcvBufSize = cfg.getRestTcpReceiveBufferSize(); restTcpSndQueueLimit = cfg.getRestTcpSendQueueLimit(); restTcpSelectorCnt = cfg.getRestTcpSelectorCount(); restTcpPort = cfg.getRestTcpPort(); restTcpSslCtxFactory = cfg.getRestTcpSslContextFactory(); restTcpSslEnabled = cfg.isRestTcpSslEnabled(); restTcpSslClientAuth = cfg.isRestTcpSslClientAuth(); restExecSvc = cfg.getRestExecutorService(); restSvcShutdown = cfg.getRestExecutorServiceShutdown(); securityCred = cfg.getSecurityCredentialsProvider(); segChkFreq = cfg.getSegmentCheckFrequency(); segPlc = cfg.getSegmentationPolicy(); segResolveAttempts = cfg.getSegmentationResolveAttempts(); segResolvers = cfg.getSegmentationResolvers(); sndRetryCnt = cfg.getNetworkSendRetryCount(); sndRetryDelay = cfg.getNetworkSendRetryDelay(); smtpHost = cfg.getSmtpHost(); smtpPort = cfg.getSmtpPort(); smtpUsername = cfg.getSmtpUsername(); smtpPwd = cfg.getSmtpPassword(); smtpFromEmail = cfg.getSmtpFromEmail(); smtpSsl = cfg.isSmtpSsl(); smtpStartTls = cfg.isSmtpStartTls(); streamerCfg = cfg.getStreamerConfiguration(); sysSvc = cfg.getSystemExecutorService(); sysSvcShutdown = cfg.getSystemExecutorServiceShutdown(); timeSrvPortBase = cfg.getTimeServerPortBase(); timeSrvPortRange = cfg.getTimeServerPortRange(); userAttrs = cfg.getUserAttributes(); waitForSegOnStart = cfg.isWaitForSegmentOnStart(); warmupClos = cfg.getWarmupClosure(); dotNetCfg = cfg.getDotNetConfiguration() == null ? null : new GridDotNetConfiguration(cfg.getDotNetConfiguration()); } /** * Whether or not send email notifications on node start and stop. Note if enabled * email notifications will only be sent if SMTP is configured and at least one * admin email is provided. * <p> * By default - email notifications are enabled. * * @return {@code True} to enable lifecycle email notifications. * @see #getSmtpHost() * @see #getAdminEmails() */ public boolean isLifeCycleEmailNotification() { return lifeCycleEmailNtf; } public String getLicenseUrl() { return licUrl; } public boolean isSmtpSsl() { return smtpSsl; } public boolean isSmtpStartTls() { return smtpStartTls; } public String getSmtpHost() { return smtpHost; } public int getSmtpPort() { return smtpPort; } public String getSmtpUsername() { return smtpUsername; } public String getSmtpPassword() { return smtpPwd; } public String[] getAdminEmails() { return adminEmails; } /** * Gets optional FROM email address for email notifications. By default * {@link #DFLT_SMTP_FROM_EMAIL} will be used. * * @return Optional FROM email address for email notifications. If {@code null} * - {@link #DFLT_SMTP_FROM_EMAIL} will be used by default. * @see #DFLT_SMTP_FROM_EMAIL * @see GridSystemProperties#GG_SMTP_FROM */ public String getSmtpFromEmail() { return smtpFromEmail; } public void setLicenseUrl(String licUrl) { this.licUrl = licUrl; } /** * Sets whether or not to enable lifecycle email notifications. * * @param lifeCycleEmailNtf {@code True} to enable lifecycle email notifications. * @see GridSystemProperties#GG_LIFECYCLE_EMAIL_NOTIFY */ public void setLifeCycleEmailNotification(boolean lifeCycleEmailNtf) { this.lifeCycleEmailNtf = lifeCycleEmailNtf; } public void setSmtpSsl(boolean smtpSsl) { this.smtpSsl = smtpSsl; } public void setSmtpStartTls(boolean smtpStartTls) { this.smtpStartTls = smtpStartTls; } public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; } public void setSmtpPort(int smtpPort) { this.smtpPort = smtpPort; } public void setSmtpUsername(String smtpUsername) { this.smtpUsername = smtpUsername; } public void setSmtpPassword(String smtpPwd) { this.smtpPwd = smtpPwd; } public void setAdminEmails(String[] adminEmails) { this.adminEmails = adminEmails; } /** * Sets optional FROM email address for email notifications. By default * {@link #DFLT_SMTP_FROM_EMAIL} will be used. * * @param smtpFromEmail Optional FROM email address for email notifications. If {@code null} * - {@link #DFLT_SMTP_FROM_EMAIL} will be used by default. * @see #DFLT_SMTP_FROM_EMAIL * @see GridSystemProperties#GG_SMTP_FROM */ public void setSmtpFromEmail(String smtpFromEmail) { this.smtpFromEmail = smtpFromEmail; } /** * Gets optional grid name. Returns {@code null} if non-default grid name was not * provided. * * @return Optional grid name. Can be {@code null}, which is default grid name, if * non-default grid name was not provided. */ public String getGridName() { return gridName; } /** * Whether or not this node should be a daemon node. * <p> * Daemon nodes are the usual grid nodes that participate in topology but not * visible on the main APIs, i.e. they are not part of any projections. The only * way to see daemon nodes is to use {@link GridProjection#forDaemons()} method. * <p> * Daemon nodes are used primarily for management and monitoring functionality that * is build on GridGain and needs to participate in the topology but also needs to be * excluded from "normal" topology so that it won't participate in task execution * or in-memory data grid storage. * * @return {@code True} if this node should be a daemon node, {@code false} otherwise. * @see GridProjection#forDaemons() */ public boolean isDaemon() { return daemon; } /** * Sets daemon flag. * <p> * Daemon nodes are the usual grid nodes that participate in topology but not * visible on the main APIs, i.e. they are not part of any projections. The only * way to see daemon nodes is to use {@link GridProjection#forDaemons()} method. * <p> * Daemon nodes are used primarily for management and monitoring functionality that * is build on GridGain and needs to participate in the topology but also needs to be * excluded from "normal" topology so that it won't participate in task execution * or in-memory data grid storage. * * @param daemon Daemon flag. */ public void setDaemon(boolean daemon) { this.daemon = daemon; } /** * Sets grid name. Note that {@code null} is a default grid name. * * @param gridName Grid name to set. Can be {@code null}, which is default * grid name. */ public void setGridName(String gridName) { this.gridName = gridName; } /** * Should return any user-defined attributes to be added to this node. These attributes can * then be accessed on nodes by calling {@link GridNode#attribute(String)} or * {@link GridNode#attributes()} methods. * <p> * Note that system adds the following (among others) attributes automatically: * <ul> * <li>{@code {@link System#getProperties()}} - All system properties.</li> * <li>{@code {@link System#getenv(String)}} - All environment properties.</li> * </ul> * <p> * Note that grid will add all System properties and environment properties * to grid node attributes also. SPIs may also add node attributes that are * used for SPI implementation. * <p> * <b>NOTE:</b> attributes names starting with {@code org.gridgain} are reserved * for internal use. * * @return User defined attributes for this node. */ public Map<String, ?> getUserAttributes() { return userAttrs; } /** * Sets user attributes for this node. * * @param userAttrs User attributes for this node. * @see GridConfiguration#getUserAttributes() */ public void setUserAttributes(Map<String, ?> userAttrs) { this.userAttrs = userAttrs; } /** * Should return an instance of logger to use in grid. If not provided, * {@gglink org.gridgain.grid.logger.log4j.GridLog4jLogger} * will be used. * * @return Logger to use in grid. */ public GridLogger getGridLogger() { return log; } /** * Sets logger to use within grid. * * @param log Logger to use within grid. * @see GridConfiguration#getGridLogger() */ public void setGridLogger(GridLogger log) { this.log = log; } /** * Should return an instance of fully configured thread pool to be used in grid. * This executor service will be in charge of processing {@link GridComputeJob GridJobs} * and user messages sent to node. * <p> * If not provided, new executor service will be created using the following configuration: * <ul> * <li>Core pool size - {@link #DFLT_PUBLIC_CORE_THREAD_CNT}</li> * <li>Max pool size - {@link #DFLT_PUBLIC_MAX_THREAD_CNT}</li> * <li>Queue capacity - {@link #DFLT_PUBLIC_THREADPOOL_QUEUE_CAP}</li> * </ul> * * @return Thread pool implementation to be used in grid to process job execution * requests and user messages sent to the node. */ public ExecutorService getExecutorService() { return execSvc; } /** * Executor service that is in charge of processing internal system messages. * <p> * If not provided, new executor service will be created using the following configuration: * <ul> * <li>Core pool size - {@link #DFLT_SYSTEM_CORE_THREAD_CNT}</li> * <li>Max pool size - {@link #DFLT_SYSTEM_MAX_THREAD_CNT}</li> * <li>Queue capacity - {@link #DFLT_SYSTEM_THREADPOOL_QUEUE_CAP}</li> * </ul> * * @return Thread pool implementation to be used in grid for internal system messages. */ public ExecutorService getSystemExecutorService() { return sysSvc; } /** * Executor service that is in charge of processing internal and Visor * {@link GridComputeJob GridJobs}. * <p> * If not provided, new executor service will be created using the following configuration: * <ul> * <li>Core pool size - {@link #DFLT_MGMT_THREAD_CNT}</li> * <li>Max pool size - {@link #DFLT_MGMT_THREAD_CNT}</li> * <li>Queue capacity - unbounded</li> * </ul> * * @return Thread pool implementation to be used in grid for internal and Visor * jobs processing. */ public ExecutorService getManagementExecutorService() { return mgmtSvc; } /** * Should return an instance of fully configured executor service which * is in charge of peer class loading requests/responses. If you don't use * peer class loading and use GAR deployment only we would recommend to decrease * the value of total threads to {@code 1}. * <p> * If not provided, new executor service will be created using the following configuration: * <ul> * <li>Core pool size - {@link #DFLT_P2P_THREAD_CNT}</li> * <li>Max pool size - {@link #DFLT_P2P_THREAD_CNT}</li> * <li>Queue capacity - unbounded</li> * </ul> * * @return Thread pool implementation to be used for peer class loading * requests handling. */ public ExecutorService getPeerClassLoadingExecutorService() { return p2pSvc; } /** * Executor service that is in charge of processing outgoing GGFS messages. Note that this * executor must have limited task queue to avoid OutOfMemory errors when incoming data stream * is faster than network bandwidth. * <p> * If not provided, new executor service will be created using the following configuration: * <ul> * <li>Core pool size - number of processors available in system</li> * <li>Max pool size - number of processors available in system</li> * <li>Queue capacity - {@link #DFLT_GGFS_THREADPOOL_QUEUE_CAP}</li> * </ul> * * @return Thread pool implementation to be used for GGFS outgoing message sending. */ public ExecutorService getGgfsExecutorService() { return ggfsSvc; } /** * Shutdown flag for executor service. * <p> * If not provided, default value {@code true} will be used which will shutdown * executor service when GridGain stops regardless of whether it was started before * GridGain or by GridGain. * * @return Executor service shutdown flag. */ public boolean getExecutorServiceShutdown() { return execSvcShutdown; } /** * Shutdown flag for system executor service. * <p> * If not provided, default value {@code true} will be used which will shutdown * executor service when GridGain stops regardless of whether it was started before * GridGain or by GridGain. * * @return System executor service shutdown flag. */ public boolean getSystemExecutorServiceShutdown() { return sysSvcShutdown; } /** * Shutdown flag for management executor service. * <p> * If not provided, default value {@code true} will be used which will shutdown * executor service when GridGain stops regardless of whether it was started before * GridGain or by GridGain. * * @return Management executor service shutdown flag. */ public boolean getManagementExecutorServiceShutdown() { return mgmtSvcShutdown; } /** * Should return flag of peer class loading executor service shutdown when the grid stops. * <p> * If not provided, default value {@code true} will be used which means * that when grid will be stopped it will shut down peer class loading executor service. * * @return Peer class loading executor service shutdown flag. */ public boolean getPeerClassLoadingExecutorServiceShutdown() { return p2pSvcShutdown; } /** * Shutdown flag for GGFS executor service. * <p> * If not provided, default value {@code true} will be used which will shutdown * executor service when GridGain stops regardless whether it was started before GridGain * or by GridGain. * * @return GGFS executor service shutdown flag. */ public boolean getGgfsExecutorServiceShutdown() { return ggfsSvcShutdown; } /** * Sets thread pool to use within grid. * * @param execSvc Thread pool to use within grid. * @see GridConfiguration#getExecutorService() */ public void setExecutorService(ExecutorService execSvc) { this.execSvc = execSvc; } /** * Sets executor service shutdown flag. * * @param execSvcShutdown Executor service shutdown flag. * @see GridConfiguration#getExecutorServiceShutdown() */ public void setExecutorServiceShutdown(boolean execSvcShutdown) { this.execSvcShutdown = execSvcShutdown; } /** * Sets system thread pool to use within grid. * * @param sysSvc Thread pool to use within grid. * @see GridConfiguration#getSystemExecutorService() */ public void setSystemExecutorService(ExecutorService sysSvc) { this.sysSvc = sysSvc; } /** * Sets system executor service shutdown flag. * * @param sysSvcShutdown System executor service shutdown flag. * @see GridConfiguration#getSystemExecutorServiceShutdown() */ public void setSystemExecutorServiceShutdown(boolean sysSvcShutdown) { this.sysSvcShutdown = sysSvcShutdown; } /** * Sets management thread pool to use within grid. * * @param mgmtSvc Thread pool to use within grid. * @see GridConfiguration#getManagementExecutorService() */ public void setManagementExecutorService(ExecutorService mgmtSvc) { this.mgmtSvc = mgmtSvc; } /** * Sets management executor service shutdown flag. * * @param mgmtSvcShutdown Management executor service shutdown flag. * @see GridConfiguration#getManagementExecutorServiceShutdown() */ public void setManagementExecutorServiceShutdown(boolean mgmtSvcShutdown) { this.mgmtSvcShutdown = mgmtSvcShutdown; } /** * Sets thread pool to use for peer class loading. * * @param p2pSvc Thread pool to use within grid. * @see GridConfiguration#getPeerClassLoadingExecutorService() */ public void setPeerClassLoadingExecutorService(ExecutorService p2pSvc) { this.p2pSvc = p2pSvc; } /** * Sets peer class loading executor service shutdown flag. * * @param p2pSvcShutdown Peer class loading executor service shutdown flag. * @see GridConfiguration#getPeerClassLoadingExecutorServiceShutdown() */ public void setPeerClassLoadingExecutorServiceShutdown(boolean p2pSvcShutdown) { this.p2pSvcShutdown = p2pSvcShutdown; } /** * Set executor service that will be used to process outgoing GGFS messages. * * @param ggfsSvc Executor service to use for outgoing GGFS messages. * @see GridConfiguration#getGgfsExecutorService() */ public void setGgfsExecutorService(ExecutorService ggfsSvc) { this.ggfsSvc = ggfsSvc; } /** * Sets GGFS executor service shutdown flag. * * @param ggfsSvcShutdown GGFS executor service shutdown flag. * @see GridConfiguration#getGgfsExecutorService() */ public void setGgfsExecutorServiceShutdown(boolean ggfsSvcShutdown) { this.ggfsSvcShutdown = ggfsSvcShutdown; } /** * Should return GridGain installation home folder. If not provided, the system will check * {@code GRIDGAIN_HOME} system property and environment variable in that order. If * {@code GRIDGAIN_HOME} still could not be obtained, then grid will not start and exception * will be thrown. * * @return GridGain installation home or {@code null} to make the system attempt to * infer it automatically. * @see GridSystemProperties#GG_HOME */ public String getGridGainHome() { return ggHome; } /** * Sets GridGain installation folder. * * @param ggHome {@code GridGain} installation folder. * @see GridConfiguration#getGridGainHome() * @see GridSystemProperties#GG_HOME */ public void setGridGainHome(String ggHome) { this.ggHome = ggHome; } /** * Gets GridGain work folder. If not provided, the method will use work folder under * {@code GRIDGAIN_HOME} specified by {@link GridConfiguration#setGridGainHome(String)} or * {@code GRIDGAIN_HOME} environment variable or system property. * <p> * If {@code GRIDGAIN_HOME} is not provided, then system temp folder is used. * * @return GridGain work folder or {@code null} to make the system attempt to infer it automatically. * @see GridConfiguration#getGridGainHome() * @see GridSystemProperties#GG_HOME */ public String getWorkDirectory() { return ggWork; } /** * Sets GridGain work folder. * * @param ggWork {@code GridGain} work folder. * @see GridConfiguration#getWorkDirectory() */ public void setWorkDirectory(String ggWork) { this.ggWork = ggWork; } /** * Should return MBean server instance. If not provided, the system will use default * platform MBean server. * * @return MBean server instance or {@code null} to make the system create a default one. * @see ManagementFactory#getPlatformMBeanServer() */ public MBeanServer getMBeanServer() { return mbeanSrv; } /** * Sets initialized and started MBean server. * * @param mbeanSrv Initialized and started MBean server. */ public void setMBeanServer(MBeanServer mbeanSrv) { this.mbeanSrv = mbeanSrv; } /** * Unique identifier for this node within grid. * * @return Unique identifier for this node within grid. */ public UUID getNodeId() { return nodeId; } /** * Sets unique identifier for local node. * * @param nodeId Unique identifier for local node. * @see GridConfiguration#getNodeId() */ public void setNodeId(UUID nodeId) { this.nodeId = nodeId; } /** * Should return an instance of marshaller to use in grid. If not provided, * {@link GridOptimizedMarshaller} will be used on Java HotSpot VM, and * {@link GridJdkMarshaller} will be used on other VMs. * * @return Marshaller to use in grid. */ public GridMarshaller getMarshaller() { return marsh; } /** * Sets marshaller to use within grid. * * @param marsh Marshaller to use within grid. * @see GridConfiguration#getMarshaller() */ public void setMarshaller(GridMarshaller marsh) { this.marsh = marsh; } /** * Returns {@code true} if peer class loading is enabled, {@code false} * otherwise. Default value is {@code false} specified by {@link #DFLT_P2P_ENABLED}. * <p> * When peer class loading is enabled and task is not deployed on local node, * local node will try to load classes from the node that initiated task * execution. This way, a task can be physically deployed only on one node * and then internally penetrate to all other nodes. * <p> * See {@link GridComputeTask} documentation for more information about task deployment. * * @return {@code true} if peer class loading is enabled, {@code false} * otherwise. */ public boolean isPeerClassLoadingEnabled() { return p2pEnabled; } /** * If this flag is set to {@code true}, jobs mapped to local node will be * marshalled as if it was remote node. * <p> * If not provided, default value is defined by {@link #DFLT_MARSHAL_LOCAL_JOBS}. * * @return {@code True} if local jobs should be marshalled. */ public boolean isMarshalLocalJobs() { return marshLocJobs; } /** * Sets marshal local jobs flag. * * @param marshLocJobs {@code True} if local jobs should be marshalled. */ public void setMarshalLocalJobs(boolean marshLocJobs) { this.marshLocJobs = marshLocJobs; } /** * Enables/disables peer class loading. * * @param p2pEnabled {@code true} if peer class loading is * enabled, {@code false} otherwise. */ public void setPeerClassLoadingEnabled(boolean p2pEnabled) { this.p2pEnabled = p2pEnabled; } /** * Should return list of packages from the system classpath that need to * be peer-to-peer loaded from task originating node. * '*' is supported at the end of the package name which means * that all sub-packages and their classes are included like in Java * package import clause. * * @return List of peer-to-peer loaded package names. */ public String[] getPeerClassLoadingLocalClassPathExclude() { return p2pLocClsPathExcl; } /** * Sets list of packages in a system class path that should be P2P * loaded even if they exist locally. * * @param p2pLocClsPathExcl List of P2P loaded packages. Package * name supports '*' at the end like in package import clause. */ public void setPeerClassLoadingLocalClassPathExclude(String... p2pLocClsPathExcl) { this.p2pLocClsPathExcl = p2pLocClsPathExcl; } /** * Number of node metrics to keep in memory to calculate totals and averages. * If not provided (value is {@code 0}), then default value * {@link #DFLT_METRICS_HISTORY_SIZE} is used. * * @return Metrics history size. * @see #DFLT_METRICS_HISTORY_SIZE */ public int getMetricsHistorySize() { return metricsHistSize; } /** * Sets number of metrics kept in history to compute totals and averages. * If not explicitly set, then default value is {@code 10,000}. * * @param metricsHistSize Number of metrics kept in history to use for * metric totals and averages calculations. * @see #DFLT_METRICS_HISTORY_SIZE */ public void setMetricsHistorySize(int metricsHistSize) { this.metricsHistSize = metricsHistSize; } /** * Gets job metrics update frequency in milliseconds. * <p> * Updating metrics too frequently may have negative performance impact. * <p> * The following values are accepted: * <ul> * <li>{@code -1} job metrics are never updated.</li> * <li>{@code 0} job metrics are updated on each job start and finish.</li> * <li>Positive value defines the actual update frequency. If not provided, then default value * {@link #DFLT_METRICS_UPDATE_FREQ} is used.</li> * </ul> * If not provided, then default value {@link #DFLT_METRICS_UPDATE_FREQ} is used. * * @return Job metrics update frequency in milliseconds. * @see #DFLT_METRICS_UPDATE_FREQ */ public long getMetricsUpdateFrequency() { return metricsUpdateFreq; } /** * Sets job metrics update frequency in milliseconds. * <p> * If set to {@code -1} job metrics are never updated. * If set to {@code 0} job metrics are updated on each job start and finish. * Positive value defines the actual update frequency. * If not provided, then default value * {@link #DFLT_METRICS_UPDATE_FREQ} is used. * * @param metricsUpdateFreq Job metrics update frequency in milliseconds. */ public void setMetricsUpdateFrequency(long metricsUpdateFreq) { this.metricsUpdateFreq = metricsUpdateFreq; } /** * Elapsed time in milliseconds after which node metrics are considered expired. * If not provided, then default value * {@link #DFLT_METRICS_EXPIRE_TIME} is used. * * @return Metrics expire time. * @see #DFLT_METRICS_EXPIRE_TIME */ public long getMetricsExpireTime() { return metricsExpTime; } /** * Sets time in milliseconds after which a certain metric value is considered expired. * If not set explicitly, then default value is {@code 600,000} milliseconds (10 minutes). * * @param metricsExpTime The metricsExpTime to set. * @see #DFLT_METRICS_EXPIRE_TIME */ public void setMetricsExpireTime(long metricsExpTime) { this.metricsExpTime = metricsExpTime; } /** * Maximum timeout in milliseconds for network requests. * <p> * If not provided, then default value * {@link #DFLT_NETWORK_TIMEOUT} is used. * * @return Maximum timeout for network requests. * @see #DFLT_NETWORK_TIMEOUT */ public long getNetworkTimeout() { return netTimeout; } /** * Maximum timeout in milliseconds for network requests. * <p> * If not provided (value is {@code 0}), then default value * {@link #DFLT_NETWORK_TIMEOUT} is used. * * @param netTimeout Maximum timeout for network requests. * @see #DFLT_NETWORK_TIMEOUT */ public void setNetworkTimeout(long netTimeout) { this.netTimeout = netTimeout; } /** * Interval in milliseconds between message send retries. * <p> * If not provided, then default value * {@link #DFLT_SEND_RETRY_DELAY} is used. * * @return Interval between message send retries. * @see #getNetworkSendRetryCount() * @see #DFLT_SEND_RETRY_DELAY */ public long getNetworkSendRetryDelay() { return sndRetryDelay; } /** * Sets interval in milliseconds between message send retries. * <p> * If not provided, then default value * {@link #DFLT_SEND_RETRY_DELAY} is used. * * @param sndRetryDelay Interval between message send retries. */ public void setNetworkSendRetryDelay(long sndRetryDelay) { this.sndRetryDelay = sndRetryDelay; } /** * Message send retries count. * <p> * If not provided, then default value * {@link #DFLT_SEND_RETRY_CNT} is used. * * @return Message send retries count. * @see #getNetworkSendRetryDelay() * @see #DFLT_SEND_RETRY_CNT */ public int getNetworkSendRetryCount() { return sndRetryCnt; } /** * Sets message send retries count. * <p> * If not provided, then default value * {@link #DFLT_SEND_RETRY_CNT} is used. * * @param sndRetryCnt Message send retries count. */ public void setNetworkSendRetryCount(int sndRetryCnt) { this.sndRetryCnt = sndRetryCnt; } /** * Gets number of samples used to synchronize clocks between different nodes. * <p> * Clock synchronization is used for cache version assignment in {@code CLOCK} order mode. * * @return Number of samples for one synchronization round. */ public int getClockSyncSamples() { return clockSyncSamples; } /** * Sets number of samples used for clock synchronization. * * @param clockSyncSamples Number of samples. */ public void setClockSyncSamples(int clockSyncSamples) { this.clockSyncSamples = clockSyncSamples; } /** * Gets frequency at which clock is synchronized between nodes, in milliseconds. * <p> * Clock synchronization is used for cache version assignment in {@code CLOCK} order mode. * * @return Clock synchronization frequency, in milliseconds. */ public long getClockSyncFrequency() { return clockSyncFreq; } /** * Sets clock synchronization frequency in milliseconds. * * @param clockSyncFreq Clock synchronization frequency. */ public void setClockSyncFrequency(long clockSyncFreq) { this.clockSyncFreq = clockSyncFreq; } /** * Returns a collection of life-cycle beans. These beans will be automatically * notified of grid life-cycle events. Use life-cycle beans whenever you * want to perform certain logic before and after grid startup and stopping * routines. * * @return Collection of life-cycle beans. * @see GridLifecycleBean * @see GridLifecycleEventType */ public GridLifecycleBean[] getLifecycleBeans() { return lifecycleBeans; } /** * Sets a collection of lifecycle beans. These beans will be automatically * notified of grid lifecycle events. Use lifecycle beans whenever you * want to perform certain logic before and after grid startup and stopping * routines. * * @param lifecycleBeans Collection of lifecycle beans. * @see GridLifecycleEventType */ public void setLifecycleBeans(GridLifecycleBean... lifecycleBeans) { this.lifecycleBeans = lifecycleBeans; } /** * Should return fully configured event SPI implementation. If not provided, * {@link GridMemoryEventStorageSpi} will be used. * * @return Grid event SPI implementation or {@code null} to use default implementation. */ public GridEventStorageSpi getEventStorageSpi() { return evtSpi; } /** * Sets fully configured instance of {@link GridEventStorageSpi}. * * @param evtSpi Fully configured instance of {@link GridEventStorageSpi}. * @see GridConfiguration#getEventStorageSpi() */ public void setEventStorageSpi(GridEventStorageSpi evtSpi) { this.evtSpi = evtSpi; } /** * Should return fully configured discovery SPI implementation. If not provided, * {@link GridTcpDiscoverySpi} will be used by default. * * @return Grid discovery SPI implementation or {@code null} to use default implementation. */ public GridDiscoverySpi getDiscoverySpi() { return discoSpi; } /** * Sets fully configured instance of {@link GridDiscoverySpi}. * * @param discoSpi Fully configured instance of {@link GridDiscoverySpi}. * @see GridConfiguration#getDiscoverySpi() */ public void setDiscoverySpi(GridDiscoverySpi discoSpi) { this.discoSpi = discoSpi; } /** * Returns segmentation policy. Default is {@link #DFLT_SEG_PLC}. * * @return Segmentation policy. */ public GridSegmentationPolicy getSegmentationPolicy() { return segPlc; } /** * Sets segmentation policy. * * @param segPlc Segmentation policy. */ public void setSegmentationPolicy(GridSegmentationPolicy segPlc) { this.segPlc = segPlc; } /** * Gets wait for segment on startup flag. Default is {@link #DFLT_WAIT_FOR_SEG_ON_START}. * <p> * Returns {@code true} if node should wait for correct segment on start. * If node detects that segment is incorrect on startup and this method * returns {@code true}, node waits until segment becomes correct. * If segment is incorrect on startup and this method returns {@code false}, * exception is thrown. * * @return {@code True} to wait for segment on startup, {@code false} otherwise. */ public boolean isWaitForSegmentOnStart() { return waitForSegOnStart; } /** * Sets wait for segment on start flag. * * @param waitForSegOnStart {@code True} to wait for segment on start. */ public void setWaitForSegmentOnStart(boolean waitForSegOnStart) { this.waitForSegOnStart = waitForSegOnStart; } /** * Gets all segmentation resolvers pass required flag. * <p> * Returns {@code true} if all segmentation resolvers should succeed * for node to be in correct segment. * Returns {@code false} if at least one segmentation resolver should succeed * for node to be in correct segment. * <p> * Default is {@link #DFLT_ALL_SEG_RESOLVERS_PASS_REQ}. * * @return {@code True} if all segmentation resolvers should succeed, * {@code false} if only one is enough. */ public boolean isAllSegmentationResolversPassRequired() { return allResolversPassReq; } /** * Sets all segmentation resolvers pass required flag. * * @param allResolversPassReq {@code True} if all segmentation resolvers should * succeed for node to be in the correct segment. */ public void setAllSegmentationResolversPassRequired(boolean allResolversPassReq) { this.allResolversPassReq = allResolversPassReq; } /** * Gets segmentation resolve attempts. Each configured resolver will have * this attempts number to pass segmentation check prior to check failure. * * Default is {@link #DFLT_SEG_RESOLVE_ATTEMPTS}. * * @return Segmentation resolve attempts. */ public int getSegmentationResolveAttempts() { return segResolveAttempts; } /** * Sets segmentation resolve attempts count. * * @param segResolveAttempts Segmentation resolve attempts. */ public void setSegmentationResolveAttempts(int segResolveAttempts) { this.segResolveAttempts = segResolveAttempts; } /** * Returns a collection of segmentation resolvers. * <p> * If array is {@code null} or empty, periodical and on-start network * segment checks do not happen. * * @return Segmentation resolvers. */ public GridSegmentationResolver[] getSegmentationResolvers() { return segResolvers; } /** * Sets segmentation resolvers. * * @param segResolvers Segmentation resolvers. */ public void setSegmentationResolvers(GridSegmentationResolver... segResolvers) { this.segResolvers = segResolvers; } /** * Returns frequency of network segment check by discovery manager. * <p> * if 0, periodic segment check is disabled and segment is checked only * on topology changes (if segmentation resolvers are configured). * <p> * Default is {@link #DFLT_SEG_CHK_FREQ}. * * @return Segment check frequency. */ public long getSegmentCheckFrequency() { return segChkFreq; } /** * Sets network segment check frequency. * * @param segChkFreq Segment check frequency. */ public void setSegmentCheckFrequency(long segChkFreq) { this.segChkFreq = segChkFreq; } /** * Should return fully configured SPI communication implementation. If not provided, * {@link GridTcpCommunicationSpi} will be used by default. * * @return Grid communication SPI implementation or {@code null} to use default implementation. */ public GridCommunicationSpi getCommunicationSpi() { return commSpi; } /** * Sets fully configured instance of {@link GridCommunicationSpi}. * * @param commSpi Fully configured instance of {@link GridCommunicationSpi}. * @see GridConfiguration#getCommunicationSpi() */ public void setCommunicationSpi(GridCommunicationSpi commSpi) { this.commSpi = commSpi; } /** * Should return fully configured collision SPI implementation. If not provided, * {@link GridNoopCollisionSpi} is used and jobs get activated immediately * on arrive to mapped node. This approach suits well for large amount of small * jobs (which is a wide-spread use case). User still can control the number * of concurrent jobs by setting maximum thread pool size defined by * GridConfiguration.getExecutorService() configuration property. * * @return Grid collision SPI implementation or {@code null} to use default implementation. */ public GridCollisionSpi getCollisionSpi() { return colSpi; } /** * Sets fully configured instance of {@link GridCollisionSpi}. * * @param colSpi Fully configured instance of {@link GridCollisionSpi} or * {@code null} if no SPI provided. * @see GridConfiguration#getCollisionSpi() */ public void setCollisionSpi(GridCollisionSpi colSpi) { this.colSpi = colSpi; } /** * Should return fully configured authentication SPI implementation. If not provided, * {@link GridNoopAuthenticationSpi} will be used. * * @return Grid authentication SPI implementation or {@code null} to use default implementation. */ public GridAuthenticationSpi getAuthenticationSpi() { return authSpi; } /** * Sets fully configured instance of {@link GridAuthenticationSpi}. * * @param authSpi Fully configured instance of {@link GridAuthenticationSpi} or * {@code null} if no SPI provided. * @see GridConfiguration#getAuthenticationSpi() */ public void setAuthenticationSpi(GridAuthenticationSpi authSpi) { this.authSpi = authSpi; } /** * Should return fully configured secure session SPI implementation. If not provided, * {@link GridNoopSecureSessionSpi} will be used. * * @return Grid secure session SPI implementation or {@code null} to use default implementation. */ public GridSecureSessionSpi getSecureSessionSpi() { return sesSpi; } /** * Sets fully configured instance of {@link GridSecureSessionSpi}. * * @param sesSpi Fully configured instance of {@link GridSecureSessionSpi} or * {@code null} if no SPI provided. * @see GridConfiguration#getSecureSessionSpi() */ public void setSecureSessionSpi(GridSecureSessionSpi sesSpi) { this.sesSpi = sesSpi; } /** * Should return fully configured deployment SPI implementation. If not provided, * {@link GridLocalDeploymentSpi} will be used. * * @return Grid deployment SPI implementation or {@code null} to use default implementation. */ public GridDeploymentSpi getDeploymentSpi() { return deploySpi; } /** * Sets fully configured instance of {@link GridDeploymentSpi}. * * @param deploySpi Fully configured instance of {@link GridDeploymentSpi}. * @see GridConfiguration#getDeploymentSpi() */ public void setDeploymentSpi(GridDeploymentSpi deploySpi) { this.deploySpi = deploySpi; } /** * Should return fully configured checkpoint SPI implementation. If not provided, * {@link GridNoopCheckpointSpi} will be used. * * @return Grid checkpoint SPI implementation or {@code null} to use default implementation. */ public GridCheckpointSpi[] getCheckpointSpi() { return cpSpi; } /** * Sets fully configured instance of {@link GridCheckpointSpi}. * * @param cpSpi Fully configured instance of {@link GridCheckpointSpi}. * @see GridConfiguration#getCheckpointSpi() */ public void setCheckpointSpi(GridCheckpointSpi... cpSpi) { this.cpSpi = cpSpi; } /** * Should return fully configured failover SPI implementation. If not provided, * {@link GridAlwaysFailoverSpi} will be used. * * @return Grid failover SPI implementation or {@code null} to use default implementation. */ public GridFailoverSpi[] getFailoverSpi() { return failSpi; } /** * Sets fully configured instance of {@link GridFailoverSpi}. * * @param failSpi Fully configured instance of {@link GridFailoverSpi} or * {@code null} if no SPI provided. * @see GridConfiguration#getFailoverSpi() */ public void setFailoverSpi(GridFailoverSpi... failSpi) { this.failSpi = failSpi; } /** * Should return fully configured load balancing SPI implementation. If not provided, * {@link GridRoundRobinLoadBalancingSpi} will be used. * * @return Grid load balancing SPI implementation or {@code null} to use default implementation. */ public GridLoadBalancingSpi[] getLoadBalancingSpi() { return loadBalancingSpi; } /** * This value is used to expire messages from waiting list whenever node * discovery discrepancies happen. * <p> * During startup, it is possible for some SPIs to have a small time window when * <tt>Node A</tt> has discovered <tt>Node B</tt>, but <tt>Node B</tt> * has not discovered <tt>Node A</tt> yet. Such time window is usually very small, * a matter of milliseconds, but certain JMS providers, for example, may be very slow * and hence have larger discovery delay window. * <p> * The default value of this property is {@code 60,000} specified by * {@link #DFLT_DISCOVERY_STARTUP_DELAY}. This should be good enough for vast * majority of configurations. However, if you do anticipate an even larger * delay, you should increase this value. * * @return Time in milliseconds for when nodes can be out-of-sync. */ public long getDiscoveryStartupDelay() { return discoStartupDelay; } /** * Sets time in milliseconds after which a certain metric value is considered expired. * If not set explicitly, then default value is {@code 600,000} milliseconds (10 minutes). * * @param discoStartupDelay Time in milliseconds for when nodes * can be out-of-sync during startup. */ public void setDiscoveryStartupDelay(long discoStartupDelay) { this.discoStartupDelay = discoStartupDelay; } /** * Sets fully configured instance of {@link GridLoadBalancingSpi}. * * @param loadBalancingSpi Fully configured instance of {@link GridLoadBalancingSpi} or * {@code null} if no SPI provided. * @see GridConfiguration#getLoadBalancingSpi() */ public void setLoadBalancingSpi(GridLoadBalancingSpi... loadBalancingSpi) { this.loadBalancingSpi = loadBalancingSpi; } /** * Sets fully configured instances of {@link GridSwapSpaceSpi}. * * @param swapSpaceSpi Fully configured instances of {@link GridSwapSpaceSpi} or * <tt>null</tt> if no SPI provided. * @see GridConfiguration#getSwapSpaceSpi() */ public void setSwapSpaceSpi(GridSwapSpaceSpi swapSpaceSpi) { this.swapSpaceSpi = swapSpaceSpi; } /** * Should return fully configured swap space SPI implementation. If not provided, * {@link GridFileSwapSpaceSpi} will be used. * <p> * Note that user can provide one or multiple instances of this SPI (and select later which one * is used in a particular context). * * @return Grid swap space SPI implementation or <tt>null</tt> to use default implementation. */ public GridSwapSpaceSpi getSwapSpaceSpi() { return swapSpaceSpi; } /** * Sets fully configured instances of {@link GridIndexingSpi}. * * @param indexingSpi Fully configured instances of {@link GridIndexingSpi}. * @see GridConfiguration#getIndexingSpi() */ public void setIndexingSpi(GridIndexingSpi... indexingSpi) { this.indexingSpi = indexingSpi; } /** * Should return fully configured indexing SPI implementations. If not provided, * {@gglink org.gridgain.grid.spi.indexing.h2.GridH2IndexingSpi} will be used. * <p> * Note that user can provide one or multiple instances of this SPI (and select later which one * is used in a particular context). * * @return Indexing SPI implementation or <tt>null</tt> to use default implementation. */ public GridIndexingSpi[] getIndexingSpi() { return indexingSpi; } /** * Gets address resolver for addresses mapping determination. * * @return Address resolver. */ public GridAddressResolver getAddressResolver() { return addrRslvr; } /* * Sets address resolver for addresses mapping determination. * * @param addrRslvr Address resolver. */ public void setAddressResolver(GridAddressResolver addrRslvr) { this.addrRslvr = addrRslvr; } /** * Sets task classes and resources sharing mode. * * @param deployMode Task classes and resources sharing mode. */ public void setDeploymentMode(GridDeploymentMode deployMode) { this.deployMode = deployMode; } /** * Gets deployment mode for deploying tasks and other classes on this node. * Refer to {@link GridDeploymentMode} documentation for more information. * * @return Deployment mode. */ public GridDeploymentMode getDeploymentMode() { return deployMode; } /** * Sets size of missed resources cache. Set 0 to avoid * missed resources caching. * * @param p2pMissedCacheSize Size of missed resources cache. */ public void setPeerClassLoadingMissedResourcesCacheSize(int p2pMissedCacheSize) { this.p2pMissedCacheSize = p2pMissedCacheSize; } /** * Returns missed resources cache size. If size greater than {@code 0}, missed * resources will be cached and next resource request ignored. If size is {@code 0}, * then request for the resource will be sent to the remote node every time this * resource is requested. * * @return Missed resources cache size. */ public int getPeerClassLoadingMissedResourcesCacheSize() { return p2pMissedCacheSize; } /** * Gets configuration (descriptors) for all caches. * * @return Array of fully initialized cache descriptors. */ public GridCacheConfiguration[] getCacheConfiguration() { return cacheCfg; } /** * Sets cache configurations. * * @param cacheCfg Cache configurations. */ @SuppressWarnings({"ZeroLengthArrayAllocation"}) public void setCacheConfiguration(GridCacheConfiguration... cacheCfg) { this.cacheCfg = cacheCfg == null ? new GridCacheConfiguration[0] : cacheCfg; } /** * Gets flag indicating whether cache sanity check is enabled. If enabled, then GridGain * will perform the following checks and throw an exception if check fails: * <ul> * <li>Cache entry is not externally locked with {@code lock(...)} or {@code lockAsync(...)} * methods when entry is enlisted to transaction.</li> * <li>Each entry in affinity group-lock transaction has the same affinity key as was specified on * affinity transaction start.</li> * <li>Each entry in partition group-lock transaction belongs to the same partition as was specified * on partition transaction start.</li> * </ul> * <p> * These checks are not required for cache operation, but help to find subtle bugs. Disabling of this checks * usually yields a noticeable performance gain. * <p> * If not provided, default value is {@link #DFLT_CACHE_SANITY_CHECK_ENABLED}. * * @return {@code True} if group lock sanity check is enabled. */ public boolean isCacheSanityCheckEnabled() { return cacheSanityCheckEnabled; } /** * Sets cache sanity check flag. * * @param cacheSanityCheckEnabled {@code True} if cache sanity check is enabled. * @see #isCacheSanityCheckEnabled() */ public void setCacheSanityCheckEnabled(boolean cacheSanityCheckEnabled) { this.cacheSanityCheckEnabled = cacheSanityCheckEnabled; } /** * Gets array of event types, which will be recorded. * <p> * Note that by default all events in GridGain are disabled. GridGain can and often does generate thousands * events per seconds under the load and therefore it creates a significant additional load on the system. * If these events are not needed by the application this load is unnecessary and leads to significant * performance degradation. So it is <b>highly recommended</b> to enable only those events that your * application logic requires. Note that certain events are required for GridGain's internal operations * and such events will still be generated but not stored by event storage SPI if they are disabled * in GridGain configuration. * * @return Include event types. */ public int[] getIncludeEventTypes() { return inclEvtTypes; } /** * Sets array of event types, which will be recorded by {@link GridEventStorageManager#record(GridEvent)}. * Note, that either the include event types or the exclude event types can be established. * * @param inclEvtTypes Include event types. */ public void setIncludeEventTypes(int... inclEvtTypes) { this.inclEvtTypes = inclEvtTypes; } /** * Sets path, either absolute or relative to {@code GRIDGAIN_HOME}, to {@code JETTY} * XML configuration file. {@code JETTY} is used to support REST over HTTP protocol for * accessing GridGain APIs remotely. * * @param jettyPath Path to {@code JETTY} XML configuration file. * @deprecated Use {@link GridClientConnectionConfiguration#setRestJettyPath(String)}. */ @Deprecated public void setRestJettyPath(String jettyPath) { this.jettyPath = jettyPath; } /** * Gets path, either absolute or relative to {@code GRIDGAIN_HOME}, to {@code Jetty} * XML configuration file. {@code Jetty} is used to support REST over HTTP protocol for * accessing GridGain APIs remotely. * <p> * If not provided, Jetty instance with default configuration will be started picking * {@link GridSystemProperties#GG_JETTY_HOST} and {@link GridSystemProperties#GG_JETTY_PORT} * as host and port respectively. * * @return Path to {@code JETTY} XML configuration file. * @see GridSystemProperties#GG_JETTY_HOST * @see GridSystemProperties#GG_JETTY_PORT * @deprecated Use {@link GridClientConnectionConfiguration#getRestJettyPath()}. */ @Deprecated public String getRestJettyPath() { return jettyPath; } /** * Sets flag indicating whether external {@code REST} access is enabled or not. * * @param restEnabled Flag indicating whether external {@code REST} access is enabled or not. * @deprecated Use {@link GridClientConnectionConfiguration}. */ @Deprecated public void setRestEnabled(boolean restEnabled) { this.restEnabled = restEnabled; } /** * Gets flag indicating whether external {@code REST} access is enabled or not. By default, * external {@code REST} access is turned on. * * @return Flag indicating whether external {@code REST} access is enabled or not. * @see GridSystemProperties#GG_JETTY_HOST * @see GridSystemProperties#GG_JETTY_PORT * @deprecated Use {@link GridClientConnectionConfiguration}. */ @Deprecated public boolean isRestEnabled() { return restEnabled; } /** * Gets host for TCP binary protocol server. This can be either an * IP address or a domain name. * <p> * If not defined, system-wide local address will be used * (see {@link #getLocalHost()}. * <p> * You can also use {@code 0.0.0.0} value to bind to all * locally-available IP addresses. * * @return TCP host. * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpHost()}. */ @Deprecated public String getRestTcpHost() { return restTcpHost; } /** * Sets host for TCP binary protocol server. * * @param restTcpHost TCP host. * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpHost(String)}. */ @Deprecated public void setRestTcpHost(String restTcpHost) { this.restTcpHost = restTcpHost; } /** * Gets port for TCP binary protocol server. * <p> * Default is {@link #DFLT_TCP_PORT}. * * @return TCP port. * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpPort()}. */ @Deprecated public int getRestTcpPort() { return restTcpPort; } /** * Sets port for TCP binary protocol server. * * @param restTcpPort TCP port. * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpPort(int)}. */ @Deprecated public void setRestTcpPort(int restTcpPort) { this.restTcpPort = restTcpPort; } /** * Gets flag indicating whether {@code TCP_NODELAY} option should be set for accepted client connections. * Setting this option reduces network latency and should be set to {@code true} in majority of cases. * For more information, see {@link Socket#setTcpNoDelay(boolean)} * <p/> * If not specified, default value is {@link #DFLT_TCP_NODELAY}. * * @return Whether {@code TCP_NODELAY} option should be enabled. * @deprecated Use {@link GridClientConnectionConfiguration#isRestTcpNoDelay()}. */ @Deprecated public boolean isRestTcpNoDelay() { return restTcpNoDelay; } /** * Sets whether {@code TCP_NODELAY} option should be set for all accepted client connections. * * @param restTcpNoDelay {@code True} if option should be enabled. * @see #isRestTcpNoDelay() * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpNoDelay(boolean)}. */ @Deprecated public void setRestTcpNoDelay(boolean restTcpNoDelay) { this.restTcpNoDelay = restTcpNoDelay; } /** * Gets flag indicating whether REST TCP server should use direct buffers. A direct buffer is a buffer * that is allocated and accessed using native system calls, without using JVM heap. Enabling direct * buffer <em>may</em> improve performance and avoid memory issues (long GC pauses due to huge buffer * size). * * @return Whether direct buffer should be used. * @deprecated Use {@link GridClientConnectionConfiguration#isRestTcpDirectBuffer()}. */ @Deprecated public boolean isRestTcpDirectBuffer() { return restTcpDirectBuf; } /** * Sets whether to use direct buffer for REST TCP server. * * @param restTcpDirectBuf {@code True} if option should be enabled. * @see #isRestTcpDirectBuffer() * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpDirectBuffer(boolean)}. */ @Deprecated public void setRestTcpDirectBuffer(boolean restTcpDirectBuf) { this.restTcpDirectBuf = restTcpDirectBuf; } /** * Gets REST TCP server send buffer size. * * @return REST TCP server send buffer size (0 for default). * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpSendBufferSize()}. */ @Deprecated public int getRestTcpSendBufferSize() { return restTcpSndBufSize; } /** * Sets REST TCP server send buffer size. * * @param restTcpSndBufSize Send buffer size. * @see #getRestTcpSendBufferSize() * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpSendBufferSize(int)}. */ @Deprecated public void setRestTcpSendBufferSize(int restTcpSndBufSize) { this.restTcpSndBufSize = restTcpSndBufSize; } /** * Gets REST TCP server receive buffer size. * * @return REST TCP server receive buffer size (0 for default). * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpReceiveBufferSize()}. */ @Deprecated public int getRestTcpReceiveBufferSize() { return restTcpRcvBufSize; } /** * Sets REST TCP server receive buffer size. * * @param restTcpRcvBufSize Receive buffer size. * @see #getRestTcpReceiveBufferSize() * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpReceiveBufferSize(int)}. */ @Deprecated public void setRestTcpReceiveBufferSize(int restTcpRcvBufSize) { this.restTcpRcvBufSize = restTcpRcvBufSize; } /** * Gets REST TCP server send queue limit. If the limit exceeds, all successive writes will * block until the queue has enough capacity. * * @return REST TCP server send queue limit (0 for unlimited). * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpSendQueueLimit()}. */ @Deprecated public int getRestTcpSendQueueLimit() { return restTcpSndQueueLimit; } /** * Sets REST TCP server send queue limit. * * @param restTcpSndQueueLimit REST TCP server send queue limit (0 for unlimited). * @see #getRestTcpSendQueueLimit() * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpSendQueueLimit(int)}. */ @Deprecated public void setRestTcpSendQueueLimit(int restTcpSndQueueLimit) { this.restTcpSndQueueLimit = restTcpSndQueueLimit; } /** * Gets number of selector threads in REST TCP server. Higher value for this parameter * may increase throughput, but also increases context switching. * * @return Number of selector threads for REST TCP server. * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpSelectorCount()}. */ @Deprecated public int getRestTcpSelectorCount() { return restTcpSelectorCnt; } /** * Sets number of selector threads for REST TCP server. * * @param restTcpSelectorCnt Number of selector threads for REST TCP server. * @see #getRestTcpSelectorCount() * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpSelectorCount(int)}. */ @Deprecated public void setRestTcpSelectorCount(int restTcpSelectorCnt) { this.restTcpSelectorCnt = restTcpSelectorCnt; } /** * Gets idle timeout for REST server. * <p> * This setting is used to reject half-opened sockets. If no packets * come within idle timeout, the connection is closed. * * @return Idle timeout in milliseconds. * @deprecated Use {@link GridClientConnectionConfiguration#getRestIdleTimeout()}. */ @Deprecated public long getRestIdleTimeout() { return restIdleTimeout; } /** * Sets idle timeout for REST server. * * @param restIdleTimeout Idle timeout in milliseconds. * @see #getRestIdleTimeout() * @deprecated Use {@link GridClientConnectionConfiguration#setRestIdleTimeout(long)}. */ @Deprecated public void setRestIdleTimeout(long restIdleTimeout) { this.restIdleTimeout = restIdleTimeout; } /** * Whether secure socket layer should be enabled on binary rest server. * <p> * Note that if this flag is set to {@code true}, an instance of {@link GridSslContextFactory} * should be provided, otherwise binary rest protocol will fail to start. * * @return {@code True} if SSL should be enabled. * @deprecated Use {@link GridClientConnectionConfiguration#isRestTcpSslEnabled()}. */ @Deprecated public boolean isRestTcpSslEnabled() { return restTcpSslEnabled; } /** * Sets whether Secure Socket Layer should be enabled for REST TCP binary protocol. * <p/> * Note that if this flag is set to {@code true}, then a valid instance of {@link GridSslContextFactory} * should be provided in {@code GridConfiguration}. Otherwise, TCP binary protocol will fail to start. * * @param restTcpSslEnabled {@code True} if SSL should be enabled. * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpSslEnabled(boolean)}. */ @Deprecated public void setRestTcpSslEnabled(boolean restTcpSslEnabled) { this.restTcpSslEnabled = restTcpSslEnabled; } /** * Gets a flag indicating whether or not remote clients will be required to have a valid SSL certificate which * validity will be verified with trust manager. * * @return Whether or not client authentication is required. * @deprecated Use {@link GridClientConnectionConfiguration#isRestTcpSslClientAuth()}. */ @Deprecated public boolean isRestTcpSslClientAuth() { return restTcpSslClientAuth; } /** * Sets flag indicating whether or not SSL client authentication is required. * * @param needClientAuth Whether or not client authentication is required. * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpSslClientAuth(boolean)}. */ @Deprecated public void setRestTcpSslClientAuth(boolean needClientAuth) { restTcpSslClientAuth = needClientAuth; } /** * Gets context factory that will be used for creating a secure socket layer of rest binary server. * * @return SslContextFactory instance. * @see GridSslContextFactory * @deprecated Use {@link GridClientConnectionConfiguration#getRestTcpSslContextFactory()}. */ @Deprecated public GridSslContextFactory getRestTcpSslContextFactory() { return restTcpSslCtxFactory; } /** * Sets instance of {@link GridSslContextFactory} that will be used to create an instance of {@code SSLContext} * for Secure Socket Layer on TCP binary protocol. This factory will only be used if * {@link #setRestTcpSslEnabled(boolean)} is set to {@code true}. * * @param restTcpSslCtxFactory Instance of {@link GridSslContextFactory} * @deprecated Use {@link GridClientConnectionConfiguration#setRestTcpSslContextFactory(GridSslContextFactory)}. */ @Deprecated public void setRestTcpSslContextFactory(GridSslContextFactory restTcpSslCtxFactory) { this.restTcpSslCtxFactory = restTcpSslCtxFactory; } /** * Gets number of ports to try if configured port is already in use. * * @return Number of ports to try. * @deprecated Use {@link GridClientConnectionConfiguration#getRestPortRange()}. */ @Deprecated public int getRestPortRange() { return restPortRange; } /** * Sets number of ports to try if configured one is in use. * * @param restPortRange Port range. * @deprecated Use {@link GridClientConnectionConfiguration#setRestPortRange(int)}. */ @Deprecated public void setRestPortRange(int restPortRange) { this.restPortRange = restPortRange; } /** * Gets list of folders that are accessible for log reading command. When remote client requests * a log file, file path is checked against this list. If requested file is not located in any * sub-folder of these folders, request is not processed. * <p> * By default, list consists of a single {@code GRIDGAIN_HOME} folder. If {@code GRIDGAIN_HOME} * could not be detected and property is not specified, no restrictions applied. * * @return Array of folders that are allowed be read by remote clients. * @deprecated Use {@link GridClientConnectionConfiguration#getRestAccessibleFolders()}. */ @Deprecated public String[] getRestAccessibleFolders() { return restAccessibleFolders; } /** * Sets array of folders accessible by REST processor for log reading command. * * @param restAccessibleFolders Array of folder paths. * @deprecated Use {@link GridClientConnectionConfiguration#setRestAccessibleFolders(String...)}. */ @Deprecated public void setRestAccessibleFolders(String... restAccessibleFolders) { this.restAccessibleFolders = restAccessibleFolders; } /** * Should return an instance of fully configured thread pool to be used for * processing of client messages (REST requests). * <p> * If not provided, new executor service will be created using the following * configuration: * <ul> * <li>Core pool size - {@link #DFLT_REST_CORE_THREAD_CNT}</li> * <li>Max pool size - {@link #DFLT_REST_MAX_THREAD_CNT}</li> * <li>Queue capacity - {@link #DFLT_REST_THREADPOOL_QUEUE_CAP}</li> * </ul> * * @return Thread pool implementation to be used for processing of client * messages. * @deprecated Use {@link GridClientConnectionConfiguration#getRestExecutorService()}. */ @Deprecated public ExecutorService getRestExecutorService() { return restExecSvc; } /** * Sets thread pool to use for processing of client messages (REST requests). * * @param restExecSvc Thread pool to use for processing of client messages. * @see GridConfiguration#getRestExecutorService() * @deprecated Use {@link GridClientConnectionConfiguration#setRestExecutorService(ExecutorService)}. */ @Deprecated public void setRestExecutorService(ExecutorService restExecSvc) { this.restExecSvc = restExecSvc; } /** * Sets REST executor service shutdown flag. * * @param restSvcShutdown REST executor service shutdown flag. * @see GridConfiguration#getRestExecutorService() * @deprecated Use {@link GridClientConnectionConfiguration#setRestExecutorServiceShutdown(boolean)}. */ @Deprecated public void setRestExecutorServiceShutdown(boolean restSvcShutdown) { this.restSvcShutdown = restSvcShutdown; } /** * Shutdown flag for REST executor service. * <p> * If not provided, default value {@code true} will be used which will shutdown * executor service when GridGain stops regardless whether it was started before GridGain * or by GridGain. * * @return REST executor service shutdown flag. * @deprecated Use {@link GridClientConnectionConfiguration#isRestExecutorServiceShutdown()}. */ @Deprecated public boolean getRestExecutorServiceShutdown() { return restSvcShutdown; } /** * Sets system-wide local address or host for all GridGain components to bind to. If provided it will * override all default local bind settings within GridGain or any of its SPIs. * * @param locHost Local IP address or host to bind to. */ public void setLocalHost(String locHost) { this.locHost = locHost; } /** * Gets system-wide local address or host for all GridGain components to bind to. If provided it will * override all default local bind settings within GridGain or any of its SPIs. * <p> * If {@code null} then GridGain tries to use local wildcard address. That means that * all services will be available on all network interfaces of the host machine. * <p> * It is strongly recommended to set this parameter for all production environments. * <p> * If not provided, default is {@code null}. * * @return Local address or host to bind to. */ public String getLocalHost() { return locHost; } /** * Gets base UPD port number for grid time server. Time server will be started on one of free ports in range * {@code [timeServerPortBase, timeServerPortBase + timeServerPortRange - 1]}. * <p> * Time server provides clock synchronization between nodes. * * @return Time */ public int getTimeServerPortBase() { return timeSrvPortBase; } /** * Sets time server port base. * * @param timeSrvPortBase Time server port base. */ public void setTimeServerPortBase(int timeSrvPortBase) { this.timeSrvPortBase = timeSrvPortBase; } /** * Defines port range to try for time server start. * * @return Number of ports to try before server initialization fails. */ public int getTimeServerPortRange() { return timeSrvPortRange; } /** * Sets time server port range. * * @param timeSrvPortRange Time server port range. */ public void setTimeServerPortRange(int timeSrvPortRange) { this.timeSrvPortRange = timeSrvPortRange; } /** * Sets secret key to authenticate REST requests. If key is {@code null} or empty authentication is disabled. * * @param restSecretKey REST secret key. * @deprecated Use {@link GridClientConnectionConfiguration#setRestSecretKey(String)}. */ @Deprecated public void setRestSecretKey(String restSecretKey) { this.restSecretKey = restSecretKey; } /** * Gets secret key to authenticate REST requests. If key is {@code null} or empty authentication is disabled. * * @return Secret key. * @see GridSystemProperties#GG_JETTY_HOST * @see GridSystemProperties#GG_JETTY_PORT * @deprecated Use {@link GridClientConnectionConfiguration#getRestSecretKey()}. */ @Deprecated public String getRestSecretKey() { return restSecretKey; } /** * Gets array of system or environment properties to include into node attributes. * If this array is {@code null}, which is default, then all system and environment * properties will be included. If this array is empty, then none will be included. * Otherwise, for every name provided, first a system property will be looked up, * and then, if it is not found, environment property will be looked up. * * @return Array of system or environment properties to include into node attributes. */ public String[] getIncludeProperties() { return includeProps; } /** * Sets array of system or environment property names to include into node attributes. * See {@link #getIncludeProperties()} for more info. * * @param includeProps Array of system or environment property names to include into node attributes. */ public void setIncludeProperties(String... includeProps) { this.includeProps = includeProps; } /** * Gets frequency of metrics log print out. * <p> * If {@code 0}, metrics print out is disabled. * <p> * If not provided, then default value {@link #DFLT_METRICS_LOG_FREQ} is used. * * @return Frequency of metrics log print out. */ public long getMetricsLogFrequency() { return metricsLogFreq; } /** * Sets frequency of metrics log print out. * <p> * If {@code 0}, metrics print out is disabled. * <p> * If not provided, then default value {@link #DFLT_METRICS_LOG_FREQ} is used. * * @param metricsLogFreq Frequency of metrics log print out. */ public void setMetricsLogFrequency(long metricsLogFreq) { this.metricsLogFreq = metricsLogFreq; } /** * Gets interceptor for objects, moving to and from remote clients. * If this method returns {@code null} then no interception will be applied. * <p> * Setting interceptor allows to transform all objects exchanged via REST protocol. * For example if you use custom serialisation on client you can write interceptor * to transform binary representations received from client to Java objects and later * access them from java code directly. * <p> * Default value is {@code null}. * * @see GridClientMessageInterceptor * @return Interceptor. * @deprecated Use {@link GridClientConnectionConfiguration#getClientMessageInterceptor()}. */ @Deprecated public GridClientMessageInterceptor getClientMessageInterceptor() { return clientMsgInterceptor; } /** * Sets client message interceptor. * <p> * Setting interceptor allows to transform all objects exchanged via REST protocol. * For example if you use custom serialisation on client you can write interceptor * to transform binary representations received from client to Java objects and later * access them from java code directly. * * @param interceptor Interceptor. * @deprecated Use {@link GridClientConnectionConfiguration#setClientMessageInterceptor(GridClientMessageInterceptor)}. */ @Deprecated public void setClientMessageInterceptor(GridClientMessageInterceptor interceptor) { clientMsgInterceptor = interceptor; } /** * Gets GGFS configurations. * * @return GGFS configurations. */ public GridGgfsConfiguration[] getGgfsConfiguration() { return ggfsCfg; } /** * Sets GGFS configurations. * * @param ggfsCfg GGFS configurations. */ public void setGgfsConfiguration(GridGgfsConfiguration... ggfsCfg) { this.ggfsCfg = ggfsCfg; } /** * Gets streamers configurations. * * @return Streamers configurations. */ public GridStreamerConfiguration[] getStreamerConfiguration() { return streamerCfg; } /** * Sets streamer configuration. * * @param streamerCfg Streamer configuration. */ public void setStreamerConfiguration(GridStreamerConfiguration... streamerCfg) { this.streamerCfg = streamerCfg; } /** * Set data center receiver hub configuration. * * @return Data center receiver hub configuration. */ public GridDrReceiverHubConfiguration getDrReceiverHubConfiguration() { return drRcvHubCfg; } /** * Set data center sender hub configuration. * * @param drRcvHubCfg Data center sender hub configuration. */ public void setDrReceiverHubConfiguration(GridDrReceiverHubConfiguration drRcvHubCfg) { this.drRcvHubCfg = drRcvHubCfg; } /** * Get data center sender hub configuration. * * @return Data center sender hub configuration. */ public GridDrSenderHubConfiguration getDrSenderHubConfiguration() { return drSndHubCfg; } /** * Set data center receiver hub configuration. * * @param drSndHubCfg Data center receiver hub configuration. */ public void setDrSenderHubConfiguration(GridDrSenderHubConfiguration drSndHubCfg) { this.drSndHubCfg = drSndHubCfg; } /** * Gets data center ID of the grid. * <p> * It is expected that data center ID will be unique among all the topologies participating in data center * replication and the same for all the nodes that belong the given topology. * * @return Data center ID or {@code 0} if it is not set. */ public byte getDataCenterId() { return dataCenterId; } /** * Sets data center ID of the grid. * <p> * It is expected that data center ID will be unique among all the topologies participating in data center * replication and the same for all the nodes that belong the given topology. * * @param dataCenterId Data center ID. */ public void setDataCenterId(byte dataCenterId) { this.dataCenterId = dataCenterId; } /** * Gets hadoop configuration. * * @return Hadoop configuration. */ public GridHadoopConfiguration getHadoopConfiguration() { return hadoopCfg; } /** * Sets hadoop configuration. * * @param hadoopCfg Hadoop configuration. */ public void setHadoopConfiguration(GridHadoopConfiguration hadoopCfg) { this.hadoopCfg = hadoopCfg; } /** * Gets security credentials. * * @return Security credentials. */ public GridSecurityCredentialsProvider getSecurityCredentialsProvider() { return securityCred; } /** * Sets security credentials. * * @param securityCred Security credentials. */ public void setSecurityCredentialsProvider(GridSecurityCredentialsProvider securityCred) { this.securityCred = securityCred; } /** * @return Client connection configuration. */ public GridClientConnectionConfiguration getClientConnectionConfiguration() { return clientCfg; } /** * @param clientCfg Client connection configuration. */ public void setClientConnectionConfiguration(GridClientConnectionConfiguration clientCfg) { this.clientCfg = clientCfg; } /** * @return Portable configuration. */ public GridPortableConfiguration getPortableConfiguration() { return portableCfg; } /** * @param portableCfg Portable configuration. */ public void setPortableConfiguration(GridPortableConfiguration portableCfg) { this.portableCfg = portableCfg; } /** * Gets configurations for services to be deployed on the grid. * * @return Configurations for services to be deployed on the grid. */ public GridServiceConfiguration[] getServiceConfiguration() { return svcCfgs; } /** * Sets configurations for services to be deployed on the grid. * * @param svcCfgs Configurations for services to be deployed on the grid. */ public void setServiceConfiguration(GridServiceConfiguration... svcCfgs) { this.svcCfgs = svcCfgs; } /** * Gets map of pre-configured local event listeners. * Each listener is mapped to array of event types. * * @return Pre-configured event listeners map. * @see GridEventType */ public Map<GridPredicate<? extends GridEvent>, int[]> getLocalEventListeners() { return lsnrs; } /** * Sets map of pre-configured local event listeners. * Each listener is mapped to array of event types. * * @param lsnrs Pre-configured event listeners map. */ public void setLocalEventListeners(Map<GridPredicate<? extends GridEvent>, int[]> lsnrs) { this.lsnrs = lsnrs; } /** * Gets grid warmup closure. This closure will be executed before actual grid instance start. Configuration of * a starting instance will be passed to the closure so it can decide what operations to warm up. * * @return Warmup closure to execute. */ public GridInClosure<GridConfiguration> getWarmupClosure() { return warmupClos; } /** * Sets warmup closure to execute before grid startup. * * @param warmupClos Warmup closure to execute. * @see #getWarmupClosure() */ public void setWarmupClosure(GridInClosure<GridConfiguration> warmupClos) { this.warmupClos = warmupClos; } /** * Returns configuration for .Net nodes. * @return Configuration for .Net nodes. */ @Nullable public GridDotNetConfiguration getDotNetConfiguration() { return dotNetCfg; } /** * Sets configuration for .Net nodes. * @param dotNetCfg Configuration for .Net nodes */ public void setDotNetConfiguration(@Nullable GridDotNetConfiguration dotNetCfg) { this.dotNetCfg = dotNetCfg; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridConfiguration.class, this); } }
package org.neo4j.kernel.ha; import java.util.HashMap; import java.util.Map; import org.neo4j.kernel.CommonFactories; import org.neo4j.kernel.IdGeneratorFactory; import org.neo4j.kernel.IdType; import org.neo4j.kernel.ha.zookeeper.ZooKeeperException; import org.neo4j.kernel.impl.ha.Broker; import org.neo4j.kernel.impl.ha.IdAllocation; import org.neo4j.kernel.impl.ha.ResponseReceiver; import org.neo4j.kernel.impl.nioneo.store.IdGenerator; import org.neo4j.kernel.impl.nioneo.store.NeoStore; public class SlaveIdGenerator implements IdGenerator { private static final long VALUE_REPRESENTING_NULL = -1; public static class SlaveIdGeneratorFactory implements IdGeneratorFactory { private final Broker broker; private final ResponseReceiver receiver; private final Map<IdType, IdGenerator> generators = new HashMap<IdType, IdGenerator>(); private final IdGeneratorFactory localFactory = CommonFactories.defaultIdGeneratorFactory(); public SlaveIdGeneratorFactory( Broker broker, ResponseReceiver receiver ) { this.broker = broker; this.receiver = receiver; } public IdGenerator open( String fileName, int grabSize, IdType idType, long highestIdInUse ) { IdGenerator localIdGenerator = localFactory.open( fileName, grabSize, idType, highestIdInUse ); IdGenerator generator = new SlaveIdGenerator( idType, highestIdInUse, broker, receiver, localIdGenerator ); generators.put( idType, generator ); return generator; } public void create( String fileName ) { localFactory.create( fileName ); } public IdGenerator get( IdType idType ) { return generators.get( idType ); } public void updateIdGenerators( NeoStore store ) { store.updateIdGenerators(); } }; private final Broker broker; private final ResponseReceiver receiver; private volatile long highestIdInUse; private volatile long defragCount; private LongArrayIterator idQueue = new LongArrayIterator( new long[0] ); private final IdType idType; private final IdGenerator localIdGenerator; public SlaveIdGenerator( IdType idType, long highestIdInUse, Broker broker, ResponseReceiver receiver, IdGenerator localIdGenerator ) { this.idType = idType; this.highestIdInUse = highestIdInUse; this.broker = broker; this.receiver = receiver; this.localIdGenerator = localIdGenerator; } public void close() { this.localIdGenerator.close(); } public void freeId( long id ) { } public long getHighId() { return this.highestIdInUse; } public long getNumberOfIdsInUse() { return this.highestIdInUse - this.defragCount; } public synchronized long nextId() { try { long nextId = nextLocalId(); if ( nextId == VALUE_REPRESENTING_NULL ) { // If we dont have anymore grabbed ids from master, grab a bunch IdAllocation allocation = receiver.receive( broker.getMaster().allocateIds( receiver.getSlaveContext(), idType ) ); nextId = storeLocally( allocation ); } return nextId; } catch ( ZooKeeperException e ) { receiver.somethingIsWrong( e ); throw e; } catch ( HaCommunicationException e ) { receiver.somethingIsWrong( e ); throw e; } } private long storeLocally( IdAllocation allocation ) { this.highestIdInUse = allocation.getHighestIdInUse(); this.defragCount = allocation.getDefragCount(); this.idQueue = new LongArrayIterator( allocation.getIds() ); updateLocalIdGenerator(); return idQueue.next(); } private void updateLocalIdGenerator() { long localHighId = this.localIdGenerator.getHighId(); if ( this.highestIdInUse > localHighId ) { this.localIdGenerator.setHighId( this.highestIdInUse ); } } private long nextLocalId() { return this.idQueue.next(); } public void setHighId( long id ) { this.highestIdInUse = id; this.localIdGenerator.setHighId( id ); } public long getDefragCount() { return this.defragCount; } private static class LongArrayIterator { private int position; private final long[] array; LongArrayIterator( long[] array ) { this.array = array; } long next() { return position < array.length ? array[position++] : VALUE_REPRESENTING_NULL; } } }
package rs_project; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class RS_Project extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Wake up, Artem!'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Wake up, Artem!"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package agu.bitmap; import static agu.caching.ResourcePool.MATRIX; import static agu.caching.ResourcePool.OPTIONS; import static agu.caching.ResourcePool.PAINT; import java.io.InputStream; import agu.bitmap.decoder.AguDecoder; import agu.util.Cloner; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory.Options; import android.graphics.BitmapRegionDecoder; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.os.Build; public abstract class ExternalBitmapDecoder extends BitmapDecoder { public static final int SIZE_AUTO = 0; protected Options opts; protected boolean mutable; private boolean scaleFilter = true; private boolean useBuiltInDecoder = false; private int width; private int height; private MemCacheEnabler<?> memCacheEnabler; // Temporary variables private float adjustedDensityRatio; private float adjustedWidthRatio; private float adjustedHeightRatio; protected ExternalBitmapDecoder() { super(); opts = OPTIONS.obtain(); opts.inScaled = false; } protected ExternalBitmapDecoder(ExternalBitmapDecoder other) { super(other); opts = Cloner.clone(other.opts); mutable = other.mutable; scaleFilter = other.scaleFilter; useBuiltInDecoder = other.useBuiltInDecoder; width = other.width; height = other.height; if (other.memCacheEnabler != null) { setMemCacheEnabler(other.memCacheEnabler.clone()); } } @Override protected void finalize() throws Throwable { try { OPTIONS.recycle(opts); } finally { super.finalize(); } } protected void decodeBounds() { opts.inJustDecodeBounds = true; decode(opts); opts.inJustDecodeBounds = false; width = opts.outWidth; height = opts.outHeight; } @Override public int sourceWidth() { if (width == 0) { decodeBounds(); } return width; } @Override public int sourceHeight() { if (height == 0) { decodeBounds(); } return height; } void setMemCacheEnabler(MemCacheEnabler<?> enabler) { enabler.setBitmapDecoder(this); memCacheEnabler = enabler; } private Object getCacheKey() { return memCacheEnabler != null ? memCacheEnabler : this; } public Bitmap getCachedBitmap() { synchronized (sMemCacheLock) { if (sMemCache == null) return null; return sMemCache.get(getCacheKey()); } } @Override public Bitmap decode() { final boolean memCacheSupported = (memCacheEnabler != null || isMemCacheSupported()); if (memCacheSupported) { final Bitmap cachedBitmap = getCachedBitmap(); if (cachedBitmap != null) { return cachedBitmap; } } // reset opts.mCancel = false; adjustedDensityRatio = 0; resolveQueries(); // Setup sample size. final boolean postScaleBy = (ratioWidth != 1 || ratioHeight != 1); if (postScaleBy) { opts.inSampleSize = calculateInSampleSizeByRatio(); } else { opts.inSampleSize = 1; } // Execute actual decoding if (opts.mCancel) return null; Bitmap bitmap = executeDecoding(); if (bitmap == null) return null; // Scale it finally. if (postScaleBy) { bitmap.setDensity(Bitmap.DENSITY_NONE); Bitmap bitmap2; Matrix m = MATRIX.obtain(); m.setScale(adjustedWidthRatio, adjustedHeightRatio); bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, scaleFilter); MATRIX.recycle(m); if (bitmap != bitmap2) { bitmap.recycle(); } bitmap2.setDensity(opts.inTargetDensity); bitmap = bitmap2; } if (memCacheSupported) { synchronized (sMemCacheLock) { if (sMemCache != null) { sMemCache.put(getCacheKey(), bitmap); } } } return bitmap; } private int calculateInSampleSizeByRatio() { adjustedWidthRatio = ratioWidth; adjustedHeightRatio = ratioHeight; int sampleSize = 1; while (adjustedWidthRatio <= 0.5f && adjustedHeightRatio <= 0.5f) { sampleSize *= 2; adjustedWidthRatio *= 2f; adjustedHeightRatio *= 2f; } return sampleSize; } private Bitmap decodeDontResizeButSample(int targetWidth, int targetHeight) { resolveQueries(); opts.inSampleSize = calculateInSampleSize(regionWidth(), regionHeight(), targetWidth, targetHeight); return executeDecoding(); } /** * Simulate native decoding. * @return */ @SuppressLint("NewApi") protected Bitmap executeDecoding() { final boolean regional = region != null && !(region.left == 0 && region.top == 0 && region.width() == sourceWidth() && region.height() == sourceHeight()); final boolean useBuiltInDecoder = this.useBuiltInDecoder || (mutable && (Build.VERSION.SDK_INT < 11 || regional)) || (opts.inSampleSize > 1 && !scaleFilter); onDecodingStarted(useBuiltInDecoder); try { if (useBuiltInDecoder) { return aguDecode(region); } else { if (regional) { return decodeRegional(opts, region); } else { return decode(opts); } } } finally { onDecodingFinished(); } } private int regionWidth() { if (region != null) { return region.width(); } else { return sourceWidth(); } } private int regionHeight() { if (region != null) { return region.height(); } else { return sourceHeight(); } } @SuppressLint("NewApi") @Override public ExternalBitmapDecoder mutable(boolean mutable) { this.mutable = mutable; if (Build.VERSION.SDK_INT >= 11) { opts.inMutable = mutable; } return this; } protected abstract Bitmap decode(Options opts); protected abstract InputStream getInputStream(); protected abstract BitmapRegionDecoder createBitmapRegionDecoder(); protected abstract boolean isMemCacheSupported(); protected void onDecodingStarted(boolean builtInDecoder) { } protected void onDecodingFinished() { } @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) protected Bitmap decodeRegional(Options opts, Rect region) { adjustDensityRatio(false); final BitmapRegionDecoder d = createBitmapRegionDecoder(); return (d == null ? null : d.decodeRegion(region, opts)); } private static int calculateInSampleSize(int width, int height, int reqWidth, int reqHeight) { // Raw height and width of image int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } protected Bitmap aguDecode(Rect region) { final InputStream in = getInputStream(); if (in == null) return null; adjustDensityRatio(true); final AguDecoder d = new AguDecoder(in); d.setRegion(region); d.setUseFilter(scaleFilter); d.setSampleSize(opts.inSampleSize); final Bitmap bitmap = d.decode(opts); d.close(); return mutable ? bitmap : Bitmap.createBitmap(bitmap); } @Override public void cancel() { opts.requestCancelDecode(); } @Override public void draw(Canvas cv, Rect rectDest) { final Bitmap bitmap = decodeDontResizeButSample(rectDest.width(), rectDest.height()); final Paint p = PAINT.obtain(Paint.FILTER_BITMAP_FLAG); cv.drawBitmap(bitmap, null, rectDest, p); PAINT.recycle(p); bitmap.recycle(); } @Override public BitmapDecoder useBuiltInDecoder(boolean force) { this.useBuiltInDecoder = force; return this; } @Override public BitmapDecoder config(Config config) { opts.inPreferredConfig = config; return this; } private void adjustDensityRatio(boolean checkRatio) { if (adjustedDensityRatio == 0) { if (checkRatio && (ratioWidth != 1 || ratioHeight != 1)) { adjustedDensityRatio = 1; } else { adjustedDensityRatio = getDensityRatio(); while (adjustedDensityRatio <= 0.5) { opts.inSampleSize *= 2; adjustedDensityRatio *= 2; } } } } @Override public int hashCode() { final int hashRegion = (region == null ? HASHCODE_NULL_REGION : region.hashCode()); final int hashOptions = (mutable ? 0x55555555 : 0) | (scaleFilter ? 0xAAAAAAAA : 0); final int hashConfig = (opts.inPreferredConfig == null ? HASHCODE_NULL_BITMAP_OPTIONS : opts.inPreferredConfig.hashCode()); return hashRegion ^ hashOptions ^ hashConfig ^ queriesHash(); } @Override public boolean equals(Object o) { if (!(o instanceof ExternalBitmapDecoder)) return false; final ExternalBitmapDecoder d = (ExternalBitmapDecoder) o; final Config config1 = opts.inPreferredConfig; final Config config2 = d.opts.inPreferredConfig; return (region == null ? d.region == null : region.equals(d.region)) && (config1 == null ? config2 == null : config1.equals(config2)) && mutable == d.mutable && scaleFilter == d.scaleFilter && queriesEquals(d); } @Override public BitmapDecoder filterBitmap(boolean filter) { scaleFilter = filter; return this; } }
package net.keabotstudios.superin; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.nio.file.attribute.UserPrincipalLookupService; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.java.games.input.Component; import net.java.games.input.Controller; import net.java.games.input.ControllerEnvironment; import net.java.games.input.Event; import net.java.games.input.EventQueue; public class Input implements KeyListener, MouseMotionListener, MouseListener, FocusListener { private static final int NUM_KEYS = KeyEvent.KEY_LAST; private static final int NUM_MBTNS = MouseEvent.MOUSE_LAST; private boolean[] keys = new boolean[NUM_KEYS]; private boolean[] lastKeys = new boolean[NUM_KEYS]; private boolean[] mouseButtons = new boolean[NUM_MBTNS]; private boolean[] lastMouseButtons = new boolean[NUM_MBTNS]; private int mouseX = 0, mouseY = 0; private Controller activeController = null; private HashMap<Component.Identifier, Float> controllerAxes = new HashMap<Component.Identifier, Float>(); private HashMap<Component.Identifier, Float> lastControllerAxes = new HashMap<Component.Identifier, Float>(); private List<String> currentAxesPressed = new ArrayList<String>(); private boolean hasFocus = false; private boolean useXInputController = false; private Controllable controllable; private InputAxis[] inputAxes; public Input(Controllable controllable, boolean useXInputController) { this.useXInputController = useXInputController; setControllable(controllable); scanControllers(); } private void scanControllers() { if (usingController()) { if (!activeController.poll()) { activeController = null; controllable.getLogger().infoLn("Controller disconnected."); } return; } Controller[] ca = ControllerEnvironment.getDefaultEnvironment().getControllers(); for (int i = 0; i < ca.length; i++) { if (ca[i].getType() == Controller.Type.GAMEPAD) { activeController = ca[i]; break; } } if (!usingController()) { controllable.getLogger().infoLn("No gamepad detected."); } else { controllable.getLogger().infoLn("Gamepad detected: " + activeController.getName()); Component[] components = activeController.getComponents(); controllerAxes.clear(); lastControllerAxes.clear(); for (Component c : components) { controllerAxes.put(c.getIdentifier(), 0.0f); lastControllerAxes.put(c.getIdentifier(), 0.0f); } } } public void setControllable(Controllable controllable) { if (this.controllable != null) { this.controllable.getComponent().removeKeyListener(this); this.controllable.getComponent().removeMouseMotionListener(this); this.controllable.getComponent().removeMouseListener(this); this.controllable.getComponent().removeFocusListener(this); } this.controllable = controllable; this.controllable.getComponent().addKeyListener(this); this.controllable.getComponent().addMouseMotionListener(this); this.controllable.getComponent().addMouseListener(this); this.controllable.getComponent().addFocusListener(this); } public void setInputs(InputAxis[] inputAxes) { this.inputAxes = inputAxes; } public void update() { for (int i = 0; i < NUM_KEYS; i++) { if (lastKeys[i] != keys[i]) { lastKeys[i] = keys[i]; } } for (int i = 0; i < NUM_MBTNS; i++) { if (lastMouseButtons[i] != mouseButtons[i]) { lastMouseButtons[i] = mouseButtons[i]; } } scanControllers(); if (usingController()) { for (Component comp : activeController.getComponents()) { if (lastControllerAxes.get(comp.getIdentifier()) != controllerAxes.get(comp.getIdentifier())) { lastControllerAxes.replace(comp.getIdentifier(), controllerAxes.get(comp.getIdentifier())); } } } updateAxesPressed(); } /** * <b>IMPORTANT:</b> Run this before you call Input.update()!!! Run all * methods that need input after this method, and then call Input.update() * after that. */ public void updateControllerInput() { if (usingController()) { activeController.poll(); EventQueue queue = activeController.getEventQueue(); Event event = new Event(); while (queue.getNextEvent(event)) { Component comp = event.getComponent(); float value = event.getValue(); controllerAxes.replace(comp.getIdentifier(), value); } } } public boolean getInput(String name) { InputAxis axis = getInputAxisFromName(name); if (!hasFocus) return false; if (axis.getKeyCode() != InputAxis.EMPTY) { if (keys[axis.getKeyCode()]) return true; } if (axis.getMouseCode() != InputAxis.EMPTY) { if (mouseButtons[axis.getMouseCode()]) return true; } if (usingController()) { float value = 0.0f; if (axis.getIdentifier() != null) { value = controllerAxes.get(axis.getIdentifier()).floatValue(); if (axis.getActZone() > 0) { if (value >= axis.getActZone()) return true; } else { if (value <= axis.getActZone()) return true; } } } return false; } public float getInputValue(String name) { InputAxis axis = getInputAxisFromName(name); if (!hasFocus) return 0.0f; if (axis.getKeyCode() != InputAxis.EMPTY) { if (keys[axis.getKeyCode()]) return 1.0f; } if (axis.getMouseCode() != InputAxis.EMPTY) { if (mouseButtons[axis.getMouseCode()]) return 1.0f; } if (usingController()) { if (axis.getIdentifier() != null) { return controllerAxes.get(axis.getIdentifier()).floatValue(); } } return 0.0f; } public boolean getInputTapped(String name) { InputAxis axis = getInputAxisFromName(name); if (!hasFocus) return false; if (axis.getKeyCode() != InputAxis.EMPTY) { if (keys[axis.getKeyCode()] != lastKeys[axis.getKeyCode()] && keys[axis.getKeyCode()]) return true; } if (axis.getMouseCode() != InputAxis.EMPTY) { if (mouseButtons[axis.getMouseCode()] != lastMouseButtons[axis.getMouseCode()] && mouseButtons[axis.getMouseCode()]) return true; } if (usingController()) { float value = 0.0f; float lastValue = 0.0f; if (axis.getIdentifier() != null) { value = controllerAxes.get(axis.getIdentifier()).floatValue(); lastValue = lastControllerAxes.get(axis.getIdentifier()).floatValue(); if (axis.getActZone() > 0) { if (value >= axis.getActZone() && lastValue != value) return true; } else { if (lastValue != value && value <= axis.getActZone()) return true; } } } return false; } public int getMouseX() { return mouseX; } public int getMouseY() { return mouseY; } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { if (e.getButton() >= mouseButtons.length) return; mouseButtons[e.getButton()] = true; } public void mouseReleased(MouseEvent e) { if (e.getButton() >= mouseButtons.length) return; mouseButtons[e.getButton()] = false; } public void mouseDragged(MouseEvent e) { handleMouse(e); } public void mouseMoved(MouseEvent e) { handleMouse(e); } private void handleMouse(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() >= keys.length) return; keys[e.getKeyCode()] = true; } public void keyReleased(KeyEvent e) { if (e.getKeyCode() >= keys.length) return; keys[e.getKeyCode()] = false; } public void keyTyped(KeyEvent e) {} public void focusGained(FocusEvent e) { hasFocus = true; } public void focusLost(FocusEvent e) { for (int i = 0; i < NUM_KEYS; i++) { keys[i] = false; } for (int i = 0; i < NUM_MBTNS; i++) { mouseButtons[i] = false; } hasFocus = false; } public boolean usingController() { return activeController != null && useXInputController; } public boolean hasFocus() { return hasFocus; } public InputAxis getInputAxisFromName(String name) { if (inputAxes != null && inputAxes.length != 0) { for (int i = 0; i < inputAxes.length; i++) { if (inputAxes[i].getName().equalsIgnoreCase(name)) { return inputAxes[i]; } } } controllable.getLogger().fatalLn("Cannot get axis from name: " + name); System.exit(-1); return null; } private void updateAxesPressed() { currentAxesPressed.clear(); if (inputAxes != null) { for (InputAxis a : inputAxes) { if (getInput(a.getName())) { currentAxesPressed.add(a.getName()); } } } } public List<String> getAxesPressed() { return new ArrayList<String>(currentAxesPressed); } }
package fi.vincit.babyschedule.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Environment; import android.util.Log; import fi.vincit.babyschedule.R; public class ScheduleDatabase { private static final String DATABASE_CREATE_BABY_NAMES = "create table if not exists babynames (_id integer primary key autoincrement, babyname text not null );"; private static final String DATABASE_CREATE_BABY_SCHEDULE = "(_id integer primary key autoincrement, babyname text not null, activityname text not null, time timestamp not null, duration int, freevalue int, freevalue2 int, freeText text, freeData image );"; private static final int BABY_NAME_COLUMN = 1; private static final int ACTIVITY_NAME_COLUMN = 2; private static final int TIME_COLUMN = 3; private static final int DURATION_COLUMN = 4; private static final int FREEVALUE = 5; private static final int FREEVALUE2 = 6; private static final int FREETEXT = 7; private static final int FREEDATA = 8; private static final String DATABASE_NAME = "BabySchedule"; private static final int DATABASE_VERSION = 13; private static final String TABLE_BABY_NAMES = "babynames"; private static Context mCtx = null; private static DatabaseHelper mDbHelper = null; private static SQLiteDatabase mDb = null; private static boolean mOpen = false; public static void open(Context ctx) throws SQLException { if( !mOpen ) { mCtx = ctx; mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); Log.w("Babyschedule", "database at: " + mDb.getPath()); backupDbToSdCard(); //restoreBackupDb(); mOpen = true; } } private static void restoreBackupDb() { try { File sd = Environment.getExternalStorageDirectory(); if (sd.canWrite()) { Date date = new Date(); String backupFileStr = "backupDbBabySched"; String currentDBPath = mDb.getPath(); File currentDB = new File(currentDBPath); File backupDB = new File(sd, backupFileStr); //backupDB.mkdirs(); if (currentDB.exists()) { Log.w("Babyschedule", "Restoring db from " + backupDB.getAbsolutePath() + "\nto " + currentDB.getAbsolutePath()); FileChannel src = new FileInputStream(backupDB).getChannel(); FileChannel dst = new FileOutputStream(currentDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Log.w("Babyschedule", "Restore successfull!"); } } } catch (Exception e) { Log.w("Babyschedule", e.getMessage()); } } private static void backupDbToSdCard() { try { File sd = Environment.getExternalStorageDirectory(); if (sd.canWrite()) { Date date = new Date(); String dateStr = date.getDate() + "_" + date.getMonth() + "_" + date.getYear() + "_" + date.getTime(); String currentDBPath = mDb.getPath(); String backupDBPath = "//mnt//sdcard//Android//data//fi.vincit.babyschedule//files//"; File currentDB = new File(currentDBPath); File backupDB = new File(sd, dateStr); //backupDB.mkdirs(); if (currentDB.exists()) { Log.w("Babyschedule", "Backing up db from " + currentDB.getAbsolutePath() + "\nto " + backupDB.getAbsolutePath()); FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Log.w("Babyschedule", "Backup successfull!"); } } } catch (Exception e) { Log.w("Babyschedule", e.getMessage()); } } public static boolean isOpen() { return mOpen; } public static void close() { mDbHelper.close(); mOpen = false; } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create tables Log.w("Babyschedule", "Creating database!!!"); db.execSQL(DATABASE_CREATE_BABY_NAMES); }; @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("Babyschedule", "Upgrading database from version " + oldVersion + " to " + newVersion); db.execSQL("DROP TABLE IF EXISTS Verneri"); db.execSQL("DROP TABLE IF EXISTS testk"); db.execSQL("DROP TABLE IF EXISTS babynames"); db.execSQL(DATABASE_CREATE_BABY_NAMES); } } public static ArrayList<String> getBabyNames() { //Log.w("Babyschedule", "getBabyNames()"); ArrayList<String> nameList = new ArrayList<String>(); Cursor names = mDb.query(TABLE_BABY_NAMES, new String[] {"_id", "babyname"}, null, null, null, null, null); if( names.moveToFirst() ) { while( !names.isAfterLast() ) { //Log.w("Babyschedule", "getBabyNames(): " + names.getString(BABY_NAME_COLUMN)); nameList.add(names.getString(BABY_NAME_COLUMN)); names.moveToNext(); } } names.close(); return nameList; } public static void addNewBaby(String babyName) { Log.w("Babyschedule", "Adding new baby: " + babyName); Cursor nameCursor = getBabyNameCursor(babyName); if( nameCursor.getCount() == 0 ) { ContentValues values = new ContentValues(); values.put("babyname", babyName); mDb.insert(TABLE_BABY_NAMES, null, values); mDb.execSQL("create table " + babyName + " " + DATABASE_CREATE_BABY_SCHEDULE); } } public static void removeBaby(String babyName) { Log.w("Babyschedule", "Removing baby: " + babyName); Cursor nameCursor = getBabyNameCursor(babyName); if( nameCursor.getCount() > 0 ) { int deleted = mDb.delete(TABLE_BABY_NAMES, "babyname = '" + babyName + "'", null); Log.i("Babyschedule", "Deleted " + deleted + " rows from db."); mDb.execSQL("DROP TABLE IF EXISTS " + babyName); } nameCursor.close(); } public static void renameBaby(String oldName, String newName) { Log.w("Babyschedule", "Renaming baby: " + oldName + " -> " + newName); Cursor oldNameCursor = getBabyNameCursor(oldName); Cursor newNameCursor = getBabyNameCursor(newName); if( oldNameCursor.getCount() > 0 && newNameCursor.getCount() == 0 ) { mDb.delete(TABLE_BABY_NAMES, "babyname = '" + oldName + "'", null); ContentValues values = new ContentValues(); values.put("babyname", newName); mDb.insert(TABLE_BABY_NAMES, null, values); mDb.execSQL("ALTER TABLE " + oldName + " RENAME TO " + newName); } } private static Cursor getBabyNameCursor(String babyName) { return mDb.query(TABLE_BABY_NAMES, new String[] {"_id", "babyname"}, "babyname = '" + babyName + "'", null, null, null, null); } public static long insertBabyAction(String babyName, String actionname, Date time) { Log.i("Babyschedule", "creating baby schedule to with activity name: " + actionname); ContentValues values = createContentValuesFor(babyName, actionname, time); return mDb.insert(babyName, null, values); } public static long insertBabyActionWithDuration(String babyName, String actionname, Date time, int durationInSeconds) { Log.i("Babyschedule", "creating baby schedule to with activity name: " + actionname + " and duration: " + durationInSeconds); ContentValues values = createContentValuesFor(babyName, actionname, time); values.put("duration", durationInSeconds); return mDb.insert(babyName, null, values); } public static long insertBabyActionWithFreeVal(String babyName, String actionname, Date time, int freeValue) { Log.i("Babyschedule", "creating baby schedule to with activity name: " + actionname + " and freeValue: " + freeValue); ContentValues values = createContentValuesFor(babyName, actionname, time); values.put("freevalue", freeValue); return mDb.insert(babyName, null, values); } private static ContentValues createContentValuesFor(String babyName, String actionname, Date time) { ContentValues values = new ContentValues(); values.put("babyname", babyName); values.put("activityname", actionname); values.put("time", time.getTime()); return values; } public static Cursor fetchEntireTable(String tableName){ return mDb.query(tableName, new String[] {"_id", "babyname", "activityname", "time", "duration", "freevalue"}, null, null, null, null, null); } public static void removeFromDb(String tableName, Cursor cursor) { int amountDeleted = mDb.delete(tableName, ""+cursor.getPosition(), null); Log.i("Babyschedule", "Deleted " + amountDeleted + " rows from db."); } public static void deleteEntryBasedOnDate(String babyName, Date date) { if( date != null ) { long datems = date.getTime(); int deleted = mDb.delete(babyName, "time = '" + datems + "'", null); Log.i("Babyschedule", "found " + deleted + " rows to be deleted in db."); } } public static BabyEvent getEventBasedOnDateTime(String babyName, Date date) { long datems = date.getTime(); BabyEvent event = null; Cursor cursor = mDb.query(babyName, new String[] {"_id", "babyname", "activityname", "time", "duration", "freevalue"}, "time = '" + datems + "'", null, null, null, null); if( cursor.moveToFirst() ) { event = new BabyEvent(getRowActionName(cursor), getRowTime(cursor), getRowDuration(cursor), getRowFreeValue(cursor)); } cursor.close(); return event; } public static int getFreeValueAttachedToEvent(String babyName, Date date) { long datems = date.getTime(); int freeVal = 0; Cursor cursor = mDb.query(babyName, new String[] {"_id", "freeValue"}, "time = '" + datems + "'", null, null, null, null); if( cursor.moveToFirst() ) { freeVal = cursor.getInt(1); } cursor.close(); return freeVal; } public static ArrayList<BabyEvent> getAllDbActionsSortedByDate(String babyName) { Cursor everything = fetchEntireTable(babyName); ArrayList<BabyEvent> actions = new ArrayList<BabyEvent>(); if( everything.moveToFirst() ) { while( !everything.isAfterLast() ) { actions.add(new BabyEvent(getRowActionName(everything), getRowTime(everything), getRowDuration(everything), getRowFreeValue(everything))); everything.moveToNext(); } } Collections.sort(actions); everything.close(); return actions; } public static ArrayList<BabyEvent> getAllDbActionsByActionName(String babyName, String actionName) { //Log.i("Babyschedule", "requesting actions for actionName " + actionName); Cursor cursor = mDb.query(babyName, new String[] {"_id", "babyname", "activityname", "time", "duration", "freevalue"}, "activityname = '" + actionName + "'", null, null, null, null); ArrayList<BabyEvent> actions = new ArrayList<BabyEvent>(); //Log.i("Babyschedule", "found " + cursor.getCount() + " rows in db."); if( cursor.moveToFirst() ) { while( !cursor.isAfterLast() ) { actions.add(new BabyEvent(getRowActionName(cursor), getRowTime(cursor), getRowDuration(cursor), getRowFreeValue(cursor))); cursor.moveToNext(); } } Collections.sort(actions); cursor.close(); return actions; } public static ArrayList<BabyEvent> getAllDbActionsFromNumberOfDaysAgo(String babyName, String actionName, long daysAgo) { //Log.i("Babyschedule", "requesting actions for actionName " + actionName + "from " + daysAgo + " days ago."); Date tomorrowAtMidnight = new Date(); tomorrowAtMidnight.setHours(0); tomorrowAtMidnight.setMinutes(0); tomorrowAtMidnight.setSeconds(0); tomorrowAtMidnight.setTime(tomorrowAtMidnight.getTime()+24*60*60*1000); long tomorrowAtMidnightMs = tomorrowAtMidnight.getTime(); long upperLimitTimestamp = tomorrowAtMidnightMs - daysAgo*24*60*60*1000; long lowerLimitTimeStamp = upperLimitTimestamp - 24*60*60*1000; String where = " activityname = '" + actionName + "' " + " AND time > " + lowerLimitTimeStamp + " AND time < " + upperLimitTimestamp; //Log.i("BabySchedule", "Query Where: " + where); Cursor cursor = mDb.query(babyName, new String[] {"_id", "babyname", "activityname", "time", "duration", "freevalue"}, where, null, null, null, null); ArrayList<BabyEvent> actions = new ArrayList<BabyEvent>(); //Log.i("Babyschedule", "found " + cursor.getCount() + " rows in db."); if( cursor.moveToFirst() ) { while( !cursor.isAfterLast() ) { actions.add(new BabyEvent(getRowActionName(cursor), getRowTime(cursor), getRowDuration(cursor), getRowFreeValue(cursor))); cursor.moveToNext(); } } Collections.sort(actions); cursor.close(); return actions; } public static ArrayList<Date> getActionDatesForAction(String babyName, String activityName){ //Log.i("Babyschedule", "requesting dates for activity " + activityName); Cursor cursor = mDb.query(babyName, new String[] {"_id", "babyname", "activityname", "time", "duration", "freevalue"}, "activityname = '" + activityName + "'", null, null, null, null); ArrayList<Date> dateList = new ArrayList<Date>(); //Log.i("Babyschedule", "found " + cursor.getCount() + " rows in db."); if( cursor.moveToFirst() ) { while( !cursor.isAfterLast() ) { dateList.add(getRowTime(cursor)); cursor.moveToNext(); } } Collections.sort(dateList); cursor.close(); return dateList; } public static Date getLastActionOfType(String babyName, String actionName){ ArrayList<Date> dates = getActionDatesForAction(babyName, actionName); if( dates.size() > 0 ) { return (Date) dates.get(dates.size()-1); } else { return null; } } public static int getDurationOfNursingStartedAt(String babyName, Date nursingStarted) { BabyEvent event = getEventBasedOnDateTime(babyName, nursingStarted); return event.getDurationInSeconds(); } public static ConsumedTime getDurationOfSleepStartedAt(String babyName, Date sleepStartTime) { Date wakeUpDate = getWakeUpDateFromSleepDate(babyName, sleepStartTime); if( wakeUpDate == null ) { return null; //wakeUpDate = new Date(); } BabyEvent sleepOrNapEvent = getEventBasedOnDateTime(babyName, sleepStartTime); assert(sleepOrNapEvent != null); return new ConsumedTime(wakeUpDate, sleepStartTime); } public static Date getWakeUpDateFromSleepDate(String babyname, Date sleepStartDate) { ArrayList<Date> dates = getActionDatesForAction(babyname, mCtx.getString(R.string.woke_up)); for( Date current : dates ) { if( current.after(sleepStartDate) ) { return current; } } return null; } private static Date getRowTime(Cursor cursor) { long timems = cursor.getLong(TIME_COLUMN); //Log.i("Babyschedule", "trying to parse row time with time string val: " + timems); Date date = new Date(); date.setTime(timems); return date; } private static int getRowDuration(Cursor cursor) { int duration = 0; try { duration = cursor.getInt(DURATION_COLUMN); } catch(Exception e) { // do nothing, just return 0 as default } return duration; } private static String getRowActionName(Cursor cursor) { return cursor.getString(ACTIVITY_NAME_COLUMN); } private static int getRowFreeValue(Cursor cursor) { int freeVal = 0; try { freeVal = cursor.getInt(FREEVALUE); } catch(Exception e) { // do nothing, just return 0 as default } return freeVal; } }
package org.torquebox.web.servlet; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.core.ApplicationFilterChain; import org.jboss.logging.Logger; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jruby.Ruby; import org.jruby.exceptions.RaiseException; import org.projectodd.polyglot.web.servlet.HttpServletResponseCapture; import org.torquebox.core.component.ComponentResolver; import org.torquebox.core.runtime.RubyRuntimePool; import org.torquebox.web.component.RackApplicationComponent; import org.torquebox.web.rack.RackEnvironment; import org.torquebox.web.rack.processors.RackWebApplicationInstaller; public class RackFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { ServiceRegistry registry = (ServiceRegistry) filterConfig.getServletContext().getAttribute( "service.registry" ); ServiceName componentResolverServiceName = (ServiceName) filterConfig.getServletContext().getAttribute( "component.resolver.service-name" ); this.componentResolver = (ComponentResolver) registry.getService( componentResolverServiceName ).getValue(); if (this.componentResolver == null) { throw new ServletException( "Unable to obtain Rack component resolver: " + componentResolverServiceName ); } ServiceName runtimePoolServiceName = (ServiceName) filterConfig.getServletContext().getAttribute( "runtime.pool.service-name" ); this.runtimePool = (RubyRuntimePool) registry.getService( runtimePoolServiceName ).getValue(); if (this.runtimePool == null) { throw new ServletException( "Unable to obtain runtime pool: " + runtimePoolServiceName ); } this.servletContext = filterConfig.getServletContext(); } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter( (HttpServletRequest) request, (HttpServletResponse) response, chain ); } } protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (((request.getPathInfo() == null) || (request.getPathInfo().equals( "/" ))) && !(request.getRequestURI().endsWith( "/" ))) { String redirectUri = request.getRequestURI() + "/"; String queryString = request.getQueryString(); if (queryString != null) { redirectUri = redirectUri + "?" + queryString; } redirectUri = response.encodeRedirectURL( redirectUri ); response.sendRedirect( redirectUri ); return; } String servletName = ""; try { servletName = ((ApplicationFilterChain) chain).getServlet().getServletConfig().getServletName(); } catch (Exception e) { // If we can't fetch the name, we can be pretty sure it's not one of our servlets, in which case it really // doesn't matter what the name is. } if (servletName.equals(RackWebApplicationInstaller.FIVE_HUNDRED_SERVLET_NAME) || servletName.equals(RackWebApplicationInstaller.STATIC_RESROUCE_SERVLET_NAME)) { // Only hand off requests to Rack if they're handled by one of the // TorqueBox servlets HttpServletResponseCapture responseCapture = new HttpServletResponseCapture( response ); try { chain.doFilter( request, responseCapture ); if (responseCapture.isError()) { response.reset(); } else if (!request.getMethod().equals( "OPTIONS" )) { // Pass HTTP OPTIONS requests through to the Rack application return; } } catch (ServletException e) { log.error( "Error performing request", e ); } doRack( request, response ); } else { // Bypass our Rack stack entirely for any servlets defined in a // user's WEB-INF/web.xml chain.doFilter( request, response ); } } protected void doRack(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { RackEnvironment rackEnv = null; Ruby runtime = null; RackApplicationComponent rackApp; try { runtime = this.runtimePool.borrowRuntime( "rack" ); rackApp = (RackApplicationComponent) this.componentResolver.resolve( runtime ); rackEnv = new RackEnvironment( runtime, servletContext, request ); rackApp.call( rackEnv ).respond( response ); } catch (RaiseException e) { log.error( "Error invoking Rack filter", e ); log.error( "Underlying Ruby exception", e.getCause() ); throw new ServletException( e ); } catch (Exception e) { log.error( "Error invoking Rack filter", e ); throw new ServletException( e ); } finally { if (rackEnv != null) { rackEnv.close(); } if (runtime != null) { this.runtimePool.returnRuntime( runtime ); } } } private static final Logger log = Logger.getLogger( RackFilter.class ); public static final String RACK_APP_DEPLOYMENT_INIT_PARAM = "torquebox.rack.app.deployment.name"; private ComponentResolver componentResolver; private RubyRuntimePool runtimePool; private ServletContext servletContext; }
package net.somethingdreadful.MAL; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.TextView; import net.somethingdreadful.MAL.adapters.DetailViewRelationsAdapter; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.response.GenericRecord; import java.io.Serializable; public class DetailViewDetails extends Fragment implements Serializable, ExpandableListView.OnChildClickListener { public SwipeRefreshLayout swipeRefresh; DetailView activity; View view; Card cardSynopsis; Card cardMediainfo; Card cardMediaStats; Card cardRelations; Card cardTitles; TextView synopsis; TextView type; TextView episodes; TextView episodesLabel; TextView volumes; TextView volumesLabel; TextView status; TextView genres; TextView classification; TextView classificationLabel; TextView score; TextView ranked; TextView popularity; TextView members; TextView favorites; ExpandableListView relations; ExpandableListView titles; DetailViewRelationsAdapter relation; DetailViewRelationsAdapter title; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); view = inflater.inflate(R.layout.activity_detailview_details, container, false); setViews(); setListener(); activity.setDetails(this); if (activity.isDone()) setText(); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = ((DetailView) activity); } /* * Set all views once */ public void setViews() { swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh); // set all the card views cardSynopsis = (Card) view.findViewById(R.id.synopsis); cardMediainfo = (Card) view.findViewById(R.id.mediainfo); cardMediaStats = (Card) view.findViewById(R.id.mediastats); cardRelations = (Card) view.findViewById(R.id.relations); cardTitles = (Card) view.findViewById(R.id.titles); cardSynopsis.setContent(R.layout.card_detailview_synopsis); cardMediainfo.setContent(R.layout.card_detailview_details_mediainfo); cardMediaStats.setContent(R.layout.card_detailview_details_mediastats); cardRelations.setContent(R.layout.card_detailview_details_relations); cardTitles.setContent(R.layout.card_detailview_details_relations); // set all the views synopsis = (TextView) view.findViewById(R.id.SynopsisContent); type = (TextView) view.findViewById(R.id.type); episodes = (TextView) view.findViewById(R.id.episodes); episodesLabel = (TextView) view.findViewById(R.id.episodesLabel); volumes = (TextView) view.findViewById(R.id.volumes); volumesLabel = (TextView) view.findViewById(R.id.volumesLabel); status = (TextView) view.findViewById(R.id.status); genres = (TextView) view.findViewById(R.id.genres); classification = (TextView) view.findViewById(R.id.classification); classificationLabel = (TextView) view.findViewById(R.id.classificationLabel); score = (TextView) view.findViewById(R.id.score); ranked = (TextView) view.findViewById(R.id.ranked); popularity = (TextView) view.findViewById(R.id.popularity); members = (TextView) view.findViewById(R.id.members); favorites = (TextView) view.findViewById(R.id.favorites); relation = new DetailViewRelationsAdapter(activity.getApplicationContext()); relations = (ExpandableListView) cardRelations.findViewById(R.id.ListView); relations.setOnChildClickListener(this); relations.setAdapter(relation); title = new DetailViewRelationsAdapter(activity.getApplicationContext()); titles = (ExpandableListView) cardTitles.findViewById(R.id.ListView); titles.setAdapter(title); clickListeners(); } /* * set all the ClickListeners */ public void setListener() { swipeRefresh.setOnRefreshListener(activity); swipeRefresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); swipeRefresh.setEnabled(true); } /* * Place all the text in the right textview */ public void setText() { if (activity.type == null || (activity.animeRecord == null && activity.mangaRecord == null)) // not enough data to do anything return; GenericRecord record; record = (activity.type.equals(MALApi.ListType.ANIME) ? activity.animeRecord : activity.mangaRecord); activity.setMenu(); synopsis.setText(record.getSpannedSynopsis()); synopsis.setMovementMethod(LinkMovementMethod.getInstance()); genres.setText("\u200F" + TextUtils.join(", ", activity.getGenresString(record.getGenresInt()))); if (activity.type.equals(MALApi.ListType.ANIME)) { type.setText(activity.getTypeString(activity.animeRecord.getTypeInt())); episodes.setText(activity.animeRecord.getEpisodes() == 0 ? "?" : Integer.toString(activity.animeRecord.getEpisodes())); volumes.setVisibility(View.GONE); volumesLabel.setVisibility(View.GONE); status.setText(activity.getStatusString(activity.animeRecord.getStatusInt())); classification.setText(activity.getClassificationString(activity.animeRecord.getClassificationInt())); } else { type.setText(activity.getTypeString(activity.mangaRecord.getTypeInt())); episodes.setText(activity.mangaRecord.getChapters() == 0 ? "?" : Integer.toString(activity.mangaRecord.getChapters())); episodesLabel.setText(R.string.label_Chapters); volumes.setText(activity.mangaRecord.getVolumes() == 0 ? "?" : Integer.toString(activity.mangaRecord.getVolumes())); status.setText(activity.getStatusString(activity.mangaRecord.getStatusInt())); classification.setVisibility(View.GONE); classificationLabel.setVisibility(View.GONE); } score.setText(Float.toString(record.getMembersScore())); ranked.setText(Integer.toString(record.getRank())); popularity.setText(Integer.toString(record.getPopularityRank())); members.setText(Integer.toString(record.getMembersCount())); favorites.setText(Integer.toString(record.getFavoritedCount())); relation.clear(); if (activity.type.equals(MALApi.ListType.ANIME)) { relation.addRelations(activity.animeRecord.getMangaAdaptions(), getString(R.string.card_content_adaptions)); relation.addRelations(activity.animeRecord.getParentStory(), getString(R.string.card_content_parentstory)); relation.addRelations(activity.animeRecord.getPrequels(), getString(R.string.card_content_prequel)); relation.addRelations(activity.animeRecord.getSequels(), getString(R.string.card_content_sequel)); relation.addRelations(activity.animeRecord.getSideStories(), getString(R.string.card_content_sidestories)); relation.addRelations(activity.animeRecord.getSpinOffs(), getString(R.string.card_content_spinoffs)); relation.addRelations(activity.animeRecord.getSummaries(), getString(R.string.card_content_summaries)); relation.addRelations(activity.animeRecord.getCharacterAnime(), getString(R.string.card_content_character)); relation.addRelations(activity.animeRecord.getAlternativeVersions(), getString(R.string.card_content_alternativeversions)); } else { relation.addRelations(activity.mangaRecord.getAnimeAdaptations(), getString(R.string.card_content_adaptions)); relation.addRelations(activity.mangaRecord.getRelatedManga(), getString(R.string.card_content_related)); relation.addRelations(activity.mangaRecord.getAlternativeVersions(), getString(R.string.card_content_alternativeversions)); } title.addTitles(activity.animeRecord.getOtherTitlesJapanese(), getString(R.string.card_content_japanese)); title.addTitles(activity.animeRecord.getOtherTitlesEnglish(), getString(R.string.card_content_english)); title.addTitles(activity.animeRecord.getOtherTitlesSynonyms(), getString(R.string.card_content_synonyms)); relation.notifyDataSetChanged(); title.notifyDataSetChanged(); cardRelations.refreshList(relation); cardTitles.refreshList(title); } @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPos, int childPos, long id) { Intent detailView = new Intent(activity, DetailView.class); detailView.putExtra("recordID", relation.getRecordStub(groupPos, childPos).getId()); detailView.putExtra("recordType", relation.getRecordStub(groupPos, childPos).getType()); startActivity(detailView); return true; } public void clickListeners(){ titles.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int i) { title.expand(i); cardTitles.refreshList(title); } }); titles.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() { @Override public void onGroupCollapse(int i) { title.collapse(i); cardTitles.refreshList(title); } }); relations.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int i) { relation.expand(i); cardRelations.refreshList(relation); } }); relations.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() { @Override public void onGroupCollapse(int i) { relation.collapse(i); cardRelations.refreshList(relation); } }); } }
package de.htwg.battleship.aview.gui; import de.htwg.battleship.controller.IMasterController; import de.htwg.battleship.observer.IObserver; import static de.htwg.battleship.util.StatCollection.HEIGTH_LENGTH; import static de.htwg.battleship.util.State.GETNAME1; import static de.htwg.battleship.util.State.PLACE1; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** * Graphical User Interface. */ @SuppressWarnings("serial") public final class GUI extends JFrame implements IObserver { /** * Constant that indicates how long the JPopupDialogs should be shown * before they close automatically. */ private static final long displaytime = 2000L; /** * JButton to start or later to restart the Game. */ private final JButton start = new JButton("Start Game"); // /** // * JButton to configure the options of the game. // * Currently not in use // */ // private final JButton options = new JButton("Options"); /** * JButton to exit the whole game right at the beginning or at the end. */ private final JButton exit = new JButton("Exit"); /** * JButton[][] for the Field. * Button named with: 'x + " " + y' */ private final JButton[][] buttonField = new JButton[HEIGTH_LENGTH][HEIGTH_LENGTH]; /** * To save the MasterController for all of the several UIs. */ private final IMasterController master; /** * ComboBox to indicate which orientation the ship that now * should be placed. */ private final JComboBox<String> orientation = new JComboBox<>(); /** * JPanel. */ private JPanel east; /** * JButton where the Ship should be placed. */ private JButton shipPlacePosition; /** * JDialog which has to be saved that the program can dispose them * after its not in use anymore. */ private JDialog notifyframe; /** * JTextField where the player should input his name. */ private JTextField player; /** * JTextField where */ private JTextField ausgabe; private JPopupDialog jpd = null; private final Container container; private final JFrame menuFrame; private final Container startContainer; /** * Public Contructor to create a GUI. * @param master MasterController which is the same for all UI */ public GUI(final IMasterController master) { master.addObserver(this); this.master = master; // initialize menu this.menuFrame = new JFrame("Battleship"); // close operations this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.menuFrame.setDefaultCloseOperation(EXIT_ON_CLOSE); // get the contentpanes of both frames this.container = this.getContentPane(); this.startContainer = this.menuFrame.getContentPane(); this.menuFrame.setLayout(new GridLayout(2, 1)); // set buttonsizes this.start.setSize(80, 50); this.exit.setSize(80, 50); // add actionlisteners this.start.addActionListener(new MenuListener()); this.exit.addActionListener(new MenuListener()); // add buttons to container this.startContainer.add(start); this.startContainer.add(exit); // set frame size this.menuFrame.setSize(800, 500); // set options this.menuFrame.setResizable(false); this.menuFrame.setLocationRelativeTo(null); // show this.menuFrame.setVisible(true); // initialize field this.newGame(HEIGTH_LENGTH); } /** * Method to initialize the GUI for the fields. * @param boardsize usually StatCollection.HEIGTH_LENGTH */ public void newGame(final int boardsize) { //new Layout this.setLayout(new BorderLayout()); JPanel main = new JPanel(); container.add(main, BorderLayout.CENTER); //panel for the left description JPanel beschriftung1 = new JPanel(); beschriftung1.setLayout(new GridLayout(boardsize, 1)); beschriftung1.setPreferredSize(new Dimension(30, 30)); container.add(beschriftung1, BorderLayout.WEST); //panel for top description JPanel beschriftung2 = new JPanel(); beschriftung2.setLayout(new GridLayout(1, boardsize)); beschriftung2.setPreferredSize(new Dimension(30, 30)); //panel for the place in the higher left corner JPanel left_higher_corner = new JPanel(); left_higher_corner.setSize(5, 5); beschriftung2.add(left_higher_corner); container.add(beschriftung2, BorderLayout.NORTH); //center GridLayout gl = new GridLayout(boardsize, boardsize); main.setLayout(gl); for (int y = 0; y < boardsize; y++) { JLabel xLabel = new JLabel("" + y); beschriftung1.add(xLabel); beschriftung2.add(xLabel); for (int x = 0; x < boardsize; x++) { String name = x + " " + y; buttonField[x][y] = new JButton(); buttonField[x][y].setName(name); main.add(buttonField[x][y]); } } //bottom JPanel bottom = new JPanel(); bottom.setLayout(new GridLayout(1, 3)); container.add(bottom, BorderLayout.SOUTH); ausgabe = new JTextField(); ausgabe.setEditable(false); bottom.add(ausgabe); this.setSize(800, 500); this.setLocationRelativeTo(null); } /** * Utility-Method to create a JDialog where the user should insert his name. * @param playernumber HEIGHT_LENGTH */ private void getPlayername(final int playernumber) { PlayerListener pl = new PlayerListener(); player = new JTextField(); JButton submit = new JButton("OK"); submit.addActionListener(pl); notifyframe = new JDialog(); notifyframe.setModal(true); notifyframe.setSize(300, 150); notifyframe.setLayout(new GridLayout(3, 1)); notifyframe.add(new JLabel("please insert playername " + playernumber)); notifyframe.add(player); notifyframe.add(submit); notifyframe.setResizable(false); notifyframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE); notifyframe.setLocationRelativeTo(getParent()); notifyframe.setVisible(true); } /** * Utility-Method to add the 'place'-Button and a * ComboBox to the main frame. */ private void placeShip() { this.setVisible(false); JButton place = new JButton("place"); place.addActionListener(new PlaceListener()); east = new JPanel(); east.setLayout(new GridLayout(3, 1)); container.add(east, BorderLayout.EAST); orientation.addItem("horizontal"); orientation.addItem("vertical"); orientation.setPreferredSize(new Dimension(90, 15)); east.add(orientation); east.add(place); this.setVisible(true); } @Override public void update() { switch (master.getCurrentState()) { case START: break; case GETNAME1: menuFrame.dispose(); getPlayername(1); break; case GETNAME2: notifyframe.dispose(); getPlayername(2); break; case PLACE1: notifyframe.dispose(); resetPlaceButton(); activateListener(new PlaceListener()); placeShip(); ausgabe.setText(master.getPlayer1().getName() + " now place the ship with the length of " + (master.getPlayer1().getOwnBoard().getShips() + 2)); break; case PLACE2: resetPlaceButton(); activateListener(new PlaceListener()); ausgabe.setText(master.getPlayer2().getName() + "now place the ship with the length of " + (master.getPlayer2().getOwnBoard().getShips() + 2)); break; case FINALPLACE1: resetPlaceButton(); break; case FINALPLACE2: resetPlaceButton(); break; case PLACEERR: jpd = new JPopupDialog(this, "Placement error", "Cannot place a ship there due to a collision or " + "the ship is out of the field!", displaytime, false); break; case SHOOT1: this.setVisible(false); container.remove(east); this.setVisible(true); activateListener(new ShootListener()); ausgabe.setText(master.getPlayer1().getName() + " is now at the turn to shoot"); break; case SHOOT2: activateListener(new ShootListener()); ausgabe.setText(master.getPlayer2().getName() + " is now at the turn to shoot"); break; case HIT: jpd = new JPopupDialog(this, "Shot Result", "Your shot was a Hit!!", displaytime, false); break; case MISS: jpd = new JPopupDialog(this, "Shot Result", "Your shot was a Miss!!", displaytime, false); break; case WIN1: String msg = master.getPlayer1().getName() + " has won!!"; jpd = new JPopupDialog(this, "Winner!", msg, displaytime, false); break; case WIN2: msg = master.getPlayer2().getName() + " has won!!"; jpd = new JPopupDialog(this, "Winner!", msg, displaytime, false); break; case END: this.setVisible(false); this.start.setText("Start a new Game"); this.menuFrame.setVisible(true); this.menuFrame.toBack(); break; case WRONGINPUT: // isn't needed in the GUI, help-state for a UI where you // can give input at the false states break; default: break; } } /** * Method to activate a new Action Listener to the JButton[][]-Matrix. * uses the removeListener-Method * @param newListener the new Listener of the button matrix */ private void activateListener(final ActionListener newListener) { for (JButton[] buttonArray : buttonField) { for (JButton button : buttonArray) { removeListener(button); button.addActionListener(newListener); } } } /** * Method which removes all Listener from a button. * @param button specified button */ private void removeListener(final JButton button) { if (button == null) { return; } ActionListener[] actionList = button.getActionListeners(); for (ActionListener acLst : actionList) { button.removeActionListener(acLst); } } /** * ActionListener for the State of the Game in which the Player has to set * his Ships on the field. PLACE1 / PLACE2 / FINALPLACE1 / FINALPLACE2 */ private class PlaceListener implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { JButton button = (JButton) e.getSource(); if ("place".equals(button.getText())) { if (shipPlacePosition != null) { String[] parts = shipPlacePosition.getName().split(" "); if (orientation.getSelectedItem() == "horizontal") { master.placeShip(new Integer(parts[0]), new Integer(parts[1]), true); } else { master.placeShip(new Integer(parts[0]), new Integer(parts[1]), false); } } else { throw new UnsupportedOperationException("Not " + "supported yet."); } } else { if (shipPlacePosition != null && shipPlacePosition != button) { switchColor(shipPlacePosition); } String[] parts = button.getName().split(" "); JButton select = buttonField[new Integer(parts[0])] [new Integer(parts[1])]; switchColor(select); } } /** * Method to switch the colour of a button. * @param select specified Button */ private void switchColor(final JButton select) { JButton defaultColor = new JButton(); if (select.getBackground() == defaultColor.getBackground()) { select.setBackground(Color.BLUE); shipPlacePosition = select; } else { select.setBackground(defaultColor.getBackground()); shipPlacePosition = null; } } } /** * ActionListener for the State of the Game in which the Player has to shoot * on the other Players board. SHOOT1 / SHOOT2 */ private class ShootListener implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { JButton button = (JButton) e.getSource(); String[] name = button.getName().split(" "); int x = Integer.parseInt(name[0]); int y = Integer.parseInt(name[1]); master.shoot(x, y); } } /** * ActionListener for the State of the game where the game is * over and the game starts. * START / END */ private class MenuListener implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { menuFrame.setVisible(false); JButton target = (JButton) e.getSource(); switch (target.getText()) { case "Start Game": master.setCurrentState(GETNAME1); setVisible(true); break; case "Exit": System.exit(0); break; case "Start a new Game": setVisible(true); master.setCurrentState(PLACE1); break; default: break; } } } /** * ActionListener for the GETNAME 1 / 2 - States. */ private class PlayerListener implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { notifyframe.setVisible(false); master.setPlayerName(player.getText()); notifyframe.dispose(); } } /** * Utility-Method to reset the selected button in the place states. */ private void resetPlaceButton() { if (shipPlacePosition != null) { shipPlacePosition.setBackground((new JButton()).getBackground()); shipPlacePosition = null; } } }
package acs.benchmark.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import si.ijs.maci.ComponentSpec; import alma.ACS.ACSComponentOperations; import alma.JavaContainerError.wrappers.AcsJContainerServicesEx; import alma.acs.component.ComponentLifecycle; import alma.acs.component.ComponentLifecycleException; import alma.acs.container.ContainerServices; import alma.acs.container.ContainerServices.ComponentReleaseCallback; import alma.acs.container.ContainerServices.ComponentReleaseCallbackWithLogging; import alma.acs.logging.AcsLogLevel; /** * A reflection-based convenience class that retrieves components either from the container services * or from its own component cache. * <p> * Features: * <ul> * <li>It restricts the interface to the IDL-derived "xxxOperations" class in order to allow * unit testing with mock components or actual component impl classes, without requiring container/corba support. * <li>Hides the Corba helper class that performs the "narrow". Together with the above point, corba is then completely hidden. * <li>(TODO) It optionally installs a transparent client-side interceptor that detects runtime problems. * <li>(TODO) Configurable timeout disconnect from components, with transparent reconnect. * </ul> * @TODO: To identify containers/hosts, use collocated dummy target components instead of the deprecated * {@link ContainerServices#getDynamicComponent(ComponentSpec, boolean)}. * <p> * This class is thread-safe, so that a client can activate or release several components at once. */ public class ComponentAccessUtil { protected final Logger logger; protected final ContainerServices contSrv; /** * Component reference plus synchronization support for other threads * that request the same component reference but must wait until the shared component * has been activated. */ protected static class CompRefHelper { ACSComponentOperations compRef; final CountDownLatch activationSync; boolean isReleasing; CompRefHelper() { this.activationSync = new CountDownLatch(1); isReleasing = false; } /** * Should be called by the first thread that requested the component, * to unblock the other threads. */ void setCompRef(ACSComponentOperations compRef) { this.compRef = compRef; activationSync.countDown(); } boolean awaitCompActivation(long timeout, TimeUnit unit) throws InterruptedException { return activationSync.await(timeout, unit); } } /** * key = component instance name, * value = component reference + sync support for other threads that request the same component. * <p> * This map must be protected from concurrent access. */ protected final Map<String, CompRefHelper> compName2Comp; public ComponentAccessUtil(ContainerServices contSrv) { this.contSrv = contSrv; this.logger = contSrv.getLogger(); this.compName2Comp = new HashMap<String, CompRefHelper>(); } /** * Returns the cached reference or the component retrieved from the container services * @param <T> The IDL-derived component interface * @param compSpec * @param idlOpInterface * @return * @throws AcsJContainerServicesEx */ public <T extends ACSComponentOperations> T getDynamicComponent(ComponentSpec compSpec, Class<T> idlOpInterface) throws AcsJContainerServicesEx { T comp = null; boolean foundInCache = false; boolean mustActivateComp = false; CompRefHelper compRefHelper = null; synchronized (compName2Comp) { // try the cache first compRefHelper = compName2Comp.get(compSpec.component_name); if (compRefHelper == null) { mustActivateComp = true; compRefHelper = new CompRefHelper(); compName2Comp.put(compSpec.component_name, compRefHelper); } else { if (compRefHelper.compRef != null) { if (compRefHelper.isReleasing) { AcsJContainerServicesEx ex = new AcsJContainerServicesEx(); ex.setContextInfo("Component '" + compSpec.component_name + "' is being released and thus cannot be activated."); throw ex; } foundInCache = true; comp = idlOpInterface.cast(compRefHelper.compRef); } } } // must keep this synchronized block short, to not prevent parallel activation of different components! try { if (!foundInCache) { if (mustActivateComp) { comp = getDynamicComponentFromContainerServices(compSpec, idlOpInterface); compRefHelper.setCompRef(comp); // this will free other threads waiting for the same comp. } else { // wait if another thread is already activating this comp boolean waitOK = false; try { waitOK = compRefHelper.awaitCompActivation(5, TimeUnit.MINUTES); } catch (InterruptedException ex) { // just leave waitOK = false } if (!waitOK) { AcsJContainerServicesEx ex = new AcsJContainerServicesEx(); ex.setContextInfo("Timed out or got interrupted while waiting for activation of component '" + compSpec.component_name + "'."); throw ex; } } } return comp; } finally { logger.log(AcsLogLevel.DEBUG, "Retrieved component '" + compSpec.component_name + "' from " + (foundInCache ? "cache." : "container services.") ); } } /** * Gets the component via {@link #contSrv}, without using the cache. * Can be overridden for tests, to bypass the container services. * @throws AcsJContainerServicesEx */ protected <T extends ACSComponentOperations> T getDynamicComponentFromContainerServices(ComponentSpec compSpec, Class<T> idlOpInterface) throws AcsJContainerServicesEx { // infer the corba helper class Class<?> corbaHelperClass = null; try { int classBaseNameEnd = idlOpInterface.getName().lastIndexOf("Operations"); String classBaseName = idlOpInterface.getName().substring(0, classBaseNameEnd); corbaHelperClass = Class.forName(classBaseName + "Helper"); } catch (Exception ex) { String msg = "Failed to find Corba Helper class matching " + idlOpInterface.getName(); logger.log(Level.FINE, msg, ex); throw new IllegalArgumentException(msg, ex); // TODO throw better ex } org.omg.CORBA.Object compRaw = contSrv.getDynamicComponent(compSpec, false); // narrow the component reference Object comp = null; try { Method narrowMethod = corbaHelperClass.getMethod("narrow", org.omg.CORBA.Object.class); comp = narrowMethod.invoke(null, compRaw); } catch (Exception ex) { String msg = "Failed to Corba-narrow component " + compSpec.component_name; logger.log(Level.FINE, msg, ex); throw new IllegalArgumentException(msg, ex); // TODO throw better ex } if (!idlOpInterface.isInstance(comp)) { String msg = "Narrowed component " + compSpec.component_name + " is not of type " + idlOpInterface; logger.log(Level.FINE, msg); throw new IllegalArgumentException(msg); // TODO throw better ex } return idlOpInterface.cast(comp); } /** * Lists the names of the component instances that have already been retrieved. */ public List<String> getCachedComponentNames() { List<String> ret = new ArrayList<String>(); synchronized (compName2Comp) { for (String name : compName2Comp.keySet()) { ret.add(name); } } return ret; } public List<ACSComponentOperations> getCachedComponents() { List<ACSComponentOperations> ret = new ArrayList<ACSComponentOperations>(); synchronized (compName2Comp) { for (CompRefHelper compRefHelper : compName2Comp.values()) { ret.add(compRefHelper.compRef); } } return ret; } /** * Should be called when a component is no longer needed. * * @param waitForCompRelease If <code>true</code> this method waits for the complete component release * otherwise returns immediately * */ public void releaseComponent(String compName, boolean waitForCompRelease) { // Mark this comp in the cache synchronized (compName2Comp) { CompRefHelper compRefHelper = compName2Comp.get(compName); if (compRefHelper != null) { compRefHelper.isReleasing = true; } } ComponentReleaseCallback callback = new ComponentReleaseCallbackWithLogging(logger, AcsLogLevel.DEBUG); contSrv.releaseComponent(compName, callback); try { if (waitForCompRelease) { boolean waitOK = callback.awaitComponentRelease(60, TimeUnit.SECONDS); if (!waitOK) { logger.warning("Timed out (60s) waiting for release of component " + compName); } } } catch (InterruptedException ex) { logger.log(AcsLogLevel.DEBUG, "Interrupted while waiting for release of component " + compName); } // remove comp reference from the cache synchronized (compName2Comp) { compName2Comp.remove(compName); } } /** * Should be called when none of the components are needed any more. * * @param waitForCompsRelease * If <code>true</code> this method waits for the complete components release, otherwise returns immediately. */ public void releaseAllComponents(boolean waitForCompsRelease) { List<String> compNames; synchronized (compName2Comp) { compNames = new ArrayList<String>(compName2Comp.keySet()); // to avoid ConcurrentModificationException } releaseComponents(compNames, waitForCompsRelease); } /** * Releases a set of components sequentially. * <p> * Subclasses may override this method, see for example {@link ConcurrentComponentAccessUtil#releaseComponents(Collection, boolean)}, * to implement concurrent component release calls, which then also affects {@link #releaseAllComponents(boolean)}. * * @param componentNames The name of the components to release * @param waitForCompsRelease If <code>true</code> this method waits for the complete components release * otherwise returns immediately */ public void releaseComponents(Collection<String> componentNames, boolean waitForCompsRelease) { if (componentNames==null || componentNames.isEmpty()) { // Nothing to do return; } for (String compName : componentNames) { releaseComponent(compName, waitForCompsRelease); } } public void logInfo() { int nElem = compName2Comp.size(); String message = "Components in the list: " + nElem + " ("; List<String> compNames = new ArrayList<String>(compName2Comp.keySet()); // to avoid ConcurrentModificationException for (String compName : compNames) { message = message + compName + " "; } logger.info(message + ")"); } protected <T, U extends ACSComponentOperations & ComponentLifecycle> T initCompImpl(U compImpl, Class<T> idlOpInterface) throws ComponentLifecycleException { compImpl.initialize(contSrv); compImpl.execute(); return idlOpInterface.cast(compImpl); } }
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> package com.sharefile.api.entities; import com.sharefile.api.entities.*; import com.sharefile.api.models.*; import com.sharefile.api.models.internal.*; import com.sharefile.api.SFApiQuery; import com.sharefile.api.interfaces.ISFQuery; import java.io.InputStream; import java.util.ArrayList; import java.net.URI; import java.util.Date; import com.google.gson.annotations.SerializedName; import com.sharefile.api.enumerations.SFSafeEnum; public class SFSharesEntity extends SFODataEntityBase { public ISFQuery<SFODataFeed<SFShare>> get() { SFApiQuery<SFODataFeed<SFShare>> sfApiQuery = new SFApiQuery<SFODataFeed<SFShare>>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Get Share * Retrieve a single Share entity. If the Share allows anonymous access, then this method will not * require authentication. * @param url * @return A single Share */ public ISFQuery<SFShare> get(URI url) { SFApiQuery<SFShare> sfApiQuery = new SFApiQuery<SFShare>(); sfApiQuery.setFrom("Shares"); sfApiQuery.addIds(url); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Get Recipients of a Share * Retrieve the list of Recipients in the share. Recipients represent the target users of the Share, containing * access information, such as number of times that user downloaded files from the share. Each Recipient is * identified by an Alias, which is an unique ID given to each user - allowing tracking of downloads for * non-authenticated users. * @param url * @return A feed of Share Aliases representing recipients of the Share */ public ISFQuery<SFODataFeed<SFShareAlias>> getRecipients(URI url) { SFApiQuery<SFODataFeed<SFShareAlias>> sfApiQuery = new SFApiQuery<SFODataFeed<SFShareAlias>>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Recipients"); sfApiQuery.addIds(url); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Get Recipient of a Share * Retrieve a single Share Recipient identified by the alias id. * @param parentUrl * @param id * @return A Share Alias representing a single recipient of the Share */ public ISFQuery<SFShareAlias> getRecipients(URI parentUrl, String id) { SFApiQuery<SFShareAlias> sfApiQuery = new SFApiQuery<SFShareAlias>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Recipients"); sfApiQuery.addIds(parentUrl); sfApiQuery.addActionIds(id); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Create Recipient for a Share * To create a Recipient for Shares that require user informaion ( Email, First Name, Last Name and Company), make sure * pass those parameters * @param parentUrl * @param Email * @param FirstName * @param LastName * @param Company * @return A Share Alias representing a single recipient of the Share */ public ISFQuery<SFShareAlias> createRecipients(URI parentUrl, String Email, String FirstName, String LastName, String Company) { SFApiQuery<SFShareAlias> sfApiQuery = new SFApiQuery<SFShareAlias>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Recipients"); sfApiQuery.addIds(parentUrl); sfApiQuery.addQueryString("Email", Email); sfApiQuery.addQueryString("FirstName", FirstName); sfApiQuery.addQueryString("LastName", LastName); sfApiQuery.addQueryString("Company", Company); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Get Items of a Share * Retrieve the list of Items (files and folders) in the Share. * @param url * @return A feed of Items of the Share */ public ISFQuery<SFODataFeed<SFItem>> getItems(URI url) { SFApiQuery<SFODataFeed<SFItem>> sfApiQuery = new SFApiQuery<SFODataFeed<SFItem>>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Items"); sfApiQuery.addIds(url); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Get Items of a Share * Retrieve a single Item in the Share * @param shareUrl * @param itemid * @return An item in the Share */ public ISFQuery<SFItem> getItems(URI shareUrl, String itemid) { SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Items"); sfApiQuery.addIds(shareUrl); sfApiQuery.addActionIds(itemid); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Downloads Share Items * Downloads items from the Share. The default action will download all Items in the Share. * If a Share has a single item, the download attachment name * will use the item name. Otherwise, the download will contain a ZIP archive containing all * files and folders in the share, named Files.zip.To download Shares that require authentication, make sure this request is authenticated. To download * shares that require require user information, provide the Name, Email and Company parameters in the URI * query. Anyone can download files from anonymous shares.You can also download individual Items in the Share. Use the Share(id)/Items(id)/Download action. The * item ID must be a top-level item in the Share - i.e., you cannot download or address files contained inside * a shared folder. * @param shareUrl * @param itemId * @param Name * @param Email * @param Company * @param redirect * @return Redirects the caller (302) to the download address for the share contents. */ public ISFQuery<InputStream> download(URI shareUrl, String id, String Name, String Email, String Company, Boolean redirect) { SFApiQuery<InputStream> sfApiQuery = new SFApiQuery<InputStream>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Download"); sfApiQuery.addIds(shareUrl); sfApiQuery.addQueryString("itemId", id); sfApiQuery.addQueryString("Name", Name); sfApiQuery.addQueryString("Email", Email); sfApiQuery.addQueryString("Company", Company); sfApiQuery.addQueryString("redirect", redirect); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } public ISFQuery<InputStream> download(URI shareUrl, String aliasid, String id, Boolean redirect) { SFApiQuery<InputStream> sfApiQuery = new SFApiQuery<InputStream>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Recipients"); sfApiQuery.addIds(shareUrl); sfApiQuery.addActionIds(aliasid); sfApiQuery.addSubAction("Download"); sfApiQuery.addQueryString("itemId", id); sfApiQuery.addQueryString("redirect", redirect); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } /** * Download Multiple Items from a Share for a Recipient * ["id1","id2",...] * Download Multiple Items from a Share for a Recipient. The download will contain a ZIP archive containing all * files and folders in the share, named Files.zip.To download Shares that require user informaion ( Email, First Name, Last Name and Company), make sure * to create an Recipient (alias) and pass in the alaisId.To download Shares that require authentication, make sure this request is authenticated. * Anyone can download files from anonymous shares. * @param shareUrl * @param aliasid * @param ids * @param redirect * @return Redirects the caller (302) to the download address for the share contents. */ public ISFQuery bulkDownload(URI shareUrl, String aliasid, ArrayList<String> ids, Boolean redirect) { SFApiQuery sfApiQuery = new SFApiQuery(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Recipients"); sfApiQuery.addIds(shareUrl); sfApiQuery.addActionIds(aliasid); sfApiQuery.addSubAction("BulkDownload"); sfApiQuery.addQueryString("redirect", redirect); sfApiQuery.setBody(ids); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } public ISFQuery<SFShare> create(SFShare share, Boolean notify) { SFApiQuery<SFShare> sfApiQuery = new SFApiQuery<SFShare>(); sfApiQuery.setFrom("Shares"); sfApiQuery.addQueryString("notify", notify); sfApiQuery.setBody(share); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Modify Share * { * "Title": "New Title", * "ExpirationDate": "2013-07-23", * "RequireLogin": false, * "Items": [ { "Id":"itemid" }, {...} ], * } * Modifies an existing Share. If Items are specified they are added to the share. * @param url * @param share * @return The modified Share */ public ISFQuery<SFShare> update(URI url, SFShare share) { SFApiQuery<SFShare> sfApiQuery = new SFApiQuery<SFShare>(); sfApiQuery.setFrom("Shares"); sfApiQuery.addIds(url); sfApiQuery.setBody(share); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Delete Share * Removes an existing Share * @param url */ public ISFQuery delete(URI url) { SFApiQuery sfApiQuery = new SFApiQuery(); sfApiQuery.setFrom("Shares"); sfApiQuery.addIds(url); sfApiQuery.setHttpMethod("DELETE"); return sfApiQuery; } /** * Create Share Alias * Creates a share alias for the specified share ID and user email. If a user with the given email address does not * exist it is created first. * For shares requiring login an activation email is sent to the created user. If 'notify' is enabled, the user activation is * included in the share notification email. * @param url * @param email * @param notify * @return Share with the AliasID property set to the created alias ID */ public ISFQuery<SFShare> createAlias(URI url, String email, Boolean notify) { SFApiQuery<SFShare> sfApiQuery = new SFApiQuery<SFShare>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Alias"); sfApiQuery.addIds(url); sfApiQuery.addQueryString("email", email); sfApiQuery.addQueryString("notify", notify); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Deliver Send a File Email * Sends an Email to the specified list of addresses, containing a link to the specified Items. * The default number of expiration days is 30. -1 disables share expiration. * @param parameters */ public ISFQuery createSend(SFShareSendParams parameters) { SFApiQuery sfApiQuery = new SFApiQuery(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Send"); sfApiQuery.setBody(parameters); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Deliver Request a File Email * Sends an Email to the specified list of addresses, containing a link to files upload. * The default number of expiration days is 30. -1 disables share expiration. * @param parameters */ public ISFQuery createRequest(SFShareRequestParams parameters) { SFApiQuery sfApiQuery = new SFApiQuery(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Request"); sfApiQuery.setBody(parameters); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Deliver an existing share link to one or more recipients * Sends an Email to the specified list of addresses, containing a link to a download or an upload. * @param parameters */ public ISFQuery resend(SFShareResendParams parameters) { SFApiQuery sfApiQuery = new SFApiQuery(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Resend"); sfApiQuery.setBody(parameters); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Upload File to Request Share * Prepares the links for uploading files to the target Share. * This method returns an Upload Specification object. The fields are * populated based on the upload method, provider, and resume parameters passed to the * upload call. * The Method determines how the URLs must be called. * * Standard uploads use a single HTTP POST message to the ChunkUri address provided in * the response. All other fields will be empty. Standard uploads do not support Resume. * * Streamed uploads use multiple HTTP POST calls to the ChunkUri address. The client must * append the parameters index, offset and hash to the end of the ChunkUri address. Index * is a sequential number representing the data block (zero-based); Offset represents the * byte offset for the block; and hash contains the MD5 hash of the block. The last HTTP * POST must also contain finish=true parameter. * * Threaded uploads use multiple HTTP POST calls to ChunkUri, and can have a number of * threads issuing blocks in parallel. Clients must append index, offset and hash to * the end of ChunkUri, as explained in Streamed. After all chunks were sent, the client * must call the FinishUri provided in this spec. * * For all uploaders, the contents of the POST Body can either be "raw", if the "Raw" parameter * was provided to the Uploader, or use MIME multi-part form encoding otherwise. Raw uploads * simply put the block content in the POST body - Content-Length specifies the size. Multi-part * form encoding has to pass the File as a Form parameter named "File1". * * For streamed and threaded, if Resume options were provided to the Upload call, then the * fields IsResume, ResumeIndex, ResumeOffset and ResumeFileHash MAY be populated. If they are, * it indicates that the server has identified a partial upload with that specification, and is * ready to resume on the provided parameters. The clients can then verify the ResumeFileHash to * ensure the file has not been modified; and continue issuing ChunkUri calls from the ResumeIndex * ResumeOffset parameters. If the client decides to restart, it should simply ignore the resume * parameters and send the blocks from Index 0. * * For all uploaders: the result code for the HTTP POST calls to Chunk and Finish Uri can either * be a 401 - indicating authentication is required; 4xx/5xx indicating some kind of error; or * 200 with a Content Body of format 'ERROR:message'. Successful calls will return either a 200 * response with no Body, or with Body of format 'OK'. * @param url * @param method * @param raw * @param fileName * @param fileSize * @param batchId * @param batchLast * @param canResume * @param startOver * @param unzip * @param tool * @param overwrite * @param title * @param details * @param isSend * @param sendGuid * @param opid * @param threadCount * @param responseFormat * @param notify * @return an Upload Specification element, containing the links for uploading, and the parameters for resume. The caller must know the protocol for sending the prepare, chunk and finish URLs returned in the spec; as well as negotiate the resume upload. */ public ISFQuery<SFUploadSpecification> upload(URI url, SFSafeEnum<SFUploadMethod> method, Boolean raw, String fileName, Long fileSize, String batchId, Boolean batchLast, Boolean canResume, Boolean startOver, Boolean unzip, String tool, Boolean overwrite, String title, String details, Boolean isSend, String sendGuid, String opid, Integer threadCount, String responseFormat, Boolean notify, Date clientCreatedDateUTC, Date clientModifiedDateUTC, Integer expirationDays) { SFApiQuery<SFUploadSpecification> sfApiQuery = new SFApiQuery<SFUploadSpecification>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Upload"); sfApiQuery.addIds(url); sfApiQuery.addQueryString("method", method); sfApiQuery.addQueryString("raw", raw); sfApiQuery.addQueryString("fileName", fileName); sfApiQuery.addQueryString("fileSize", fileSize); sfApiQuery.addQueryString("batchId", batchId); sfApiQuery.addQueryString("batchLast", batchLast); sfApiQuery.addQueryString("canResume", canResume); sfApiQuery.addQueryString("startOver", startOver); sfApiQuery.addQueryString("unzip", unzip); sfApiQuery.addQueryString("tool", tool); sfApiQuery.addQueryString("overwrite", overwrite); sfApiQuery.addQueryString("title", title); sfApiQuery.addQueryString("details", details); sfApiQuery.addQueryString("isSend", isSend); sfApiQuery.addQueryString("sendGuid", sendGuid); sfApiQuery.addQueryString("opid", opid); sfApiQuery.addQueryString("threadCount", threadCount); sfApiQuery.addQueryString("responseFormat", responseFormat); sfApiQuery.addQueryString("notify", notify); sfApiQuery.addQueryString("clientCreatedDateUTC", clientCreatedDateUTC); sfApiQuery.addQueryString("clientModifiedDateUTC", clientModifiedDateUTC); sfApiQuery.addQueryString("expirationDays", expirationDays); sfApiQuery.setHttpMethod("POST"); return sfApiQuery; } /** * Get Redirection endpoint Information * Returns the redirection endpoint for this Share. * @param url * @return The Redirection endpoint Information */ public ISFQuery<SFRedirection> getRedirection(URI url) { SFApiQuery<SFRedirection> sfApiQuery = new SFApiQuery<SFRedirection>(); sfApiQuery.setFrom("Shares"); sfApiQuery.setAction("Redirection"); sfApiQuery.addIds(url); sfApiQuery.setHttpMethod("GET"); return sfApiQuery; } }
package clarifai2.internal; import clarifai2.Func1; import clarifai2.api.ClarifaiClient; import clarifai2.dto.PointF; import clarifai2.exception.ClarifaiException; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.reflect.TypeToken; import okhttp3.MediaType; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; public final class InternalUtil { public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf8"); private InternalUtil() { throw new UnsupportedOperationException("No instances"); } public static boolean isRawType(@NotNull TypeToken<?> token) { return token.getType() instanceof Class; } @Contract("null -> fail") @NotNull public static <T> T assertNotNull(@Nullable T in) { if (in == null) { throw new NullPointerException(); } return in; } @NotNull public static JsonElement coerceJsonNull(@Nullable JsonElement in) { return in == null ? JsonNull.INSTANCE : in; } /** * Asserts that the given JSON is of the type expected, and casts it to that type. * * @param json the JSON in question. If {@code null} is passed, it is coerced to {@link JsonNull#INSTANCE} * @param expectedType the type that we are asserting this JSON is * @param <T> the type that we are asserting this JSON is * @return this JSON, casted to the asserted type * @throws JsonParseException if the JSON was not of the asserted type */ @NotNull public static <T extends JsonElement> T assertJsonIs( @Nullable JsonElement json, @NotNull Class<T> expectedType ) throws JsonParseException { if (json == null) { json = JsonNull.INSTANCE; } if (expectedType.isInstance(json)) { return expectedType.cast(json); } throw new JsonParseException(String.format("This JSON must be a %s, but it was a %s", expectedType.getSimpleName(), json.getClass().getSimpleName() )); } @NotNull public static JsonElement coerceJsonNull(@Nullable JsonElement in) { return in == null ? JsonNull.INSTANCE : in; } /** * Asserts that the given JSON is of the type expected, and casts it to that type. * * @param json the JSON in question. If {@code null} is passed, it is coerced to {@link JsonNull#INSTANCE} * @param expectedType the type that we are asserting this JSON is * @param <T> the type that we are asserting this JSON is * @return this JSON, casted to the asserted type * @throws JsonParseException if the JSON was not of the asserted type */ @NotNull public static <T extends JsonElement> T assertJsonIs( @Nullable JsonElement json, @NotNull Class<T> expectedType ) throws JsonParseException { if (json == null) { json = JsonNull.INSTANCE; } if (expectedType.isInstance(json)) { return expectedType.cast(json); } throw new JsonParseException(String.format("This JSON must be a %s, but it was a %s", expectedType.getSimpleName(), json.getClass().getSimpleName() )); } public static void assertMetadataHasNoNulls(@NotNull JsonObject json) { if (areNullsPresentInDictionaries(json)) { throw new IllegalArgumentException("You cannot use null as an entry's value in your metadata!"); } } /** * @param json the JSON to check * @return {@code true} if this JSON is a {@link JsonNull} or if any of the elements it contains, recursively, are {@link JsonNull}s */ public static boolean areNullsPresentInDictionaries(@NotNull JsonElement json) { if (!json.isJsonObject()) { return json.isJsonNull(); } for (final Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) { if (areNullsPresentInDictionaries(entry.getValue())) { return true; } } return false; } @NotNull public static <T> List<T> copyArray(@NotNull JsonArray in, @NotNull Func1<JsonElement, T> mapper) { final List<T> out = new ArrayList<>(in.size()); for (final JsonElement element : in) { out.add(mapper.call(element == null ? JsonNull.INSTANCE : element)); } return out; } @SuppressWarnings("unchecked") @NotNull public static <E extends JsonElement> E jsonDeepCopy(@NotNull E in) { if (in instanceof JsonObject) { final JsonObject out = new JsonObject(); for (final Map.Entry<String, JsonElement> entry : ((JsonObject) in).entrySet()) { out.add(entry.getKey(), jsonDeepCopy(entry.getValue())); } return (E) out; } if (in instanceof JsonArray) { final JsonArray out = new JsonArray(); for (final JsonElement element : (JsonArray) in) { out.add(jsonDeepCopy(element)); } return (E) out; } if (in instanceof JsonPrimitive || in instanceof JsonNull) { return in; } throw new IllegalArgumentException("Input JSON is of type " + in.getClass() + " and cannot be deep-copied"); } @NotNull public static JsonObject asGeoPointJson(@NotNull PointF geoPoint) { return new JSONObjectBuilder() .add("latitude", geoPoint.x()) .add("longitude", geoPoint.y()) .build(); } public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { throw new RuntimeException(e); } } @NotNull public static ClarifaiClient clientInstance(@NotNull Gson gson) { return gson.fromJson(new JsonObject(), ClarifaiClient.class); } @Nullable public static <T> T fromJson(@NotNull Gson gson, @Nullable JsonElement element, @NotNull Class<T> type) { return gson.fromJson(element, type); } @NotNull public static <T> JsonElement toJson(@NotNull Gson gson, @Nullable T obj, @NotNull Class<T> type) { return coerceJsonNull(gson.toJsonTree(obj, type)); } @Nullable public static <T> T fromJson(@NotNull Gson gson, @Nullable JsonElement element, @NotNull TypeToken<T> type) { return gson.fromJson(element, type.getType()); } @NotNull public static <T> JsonElement toJson(@NotNull Gson gson, @Nullable T obj, @NotNull TypeToken<T> type) { return coerceJsonNull(gson.toJsonTree(obj, type.getType())); } @Contract("null, null -> true; null, !null -> false; !null, null -> false") public static <T> boolean nullSafeEquals(@Nullable T o1, @Nullable T o2) { return o1 == null ? o2 == null : o1.equals(o2); } @NotNull public static byte[] read(File file) { if (!file.exists()) { throw new ClarifaiException("File " + file.getAbsolutePath() + " does not exist!"); } ByteArrayOutputStream ous = null; InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); ios = new FileInputStream(file); int read; while ((read = ios.read(buffer)) != -1) { ous.write(buffer, 0, read); } } catch (IOException e) { throw new ClarifaiException("Error while reading " + file.getName(), e); } finally { try { if (ous != null) { ous.close(); } } catch (IOException ignored) { } try { if (ios != null) { ios.close(); } } catch (IOException ignored) { } } return ous.toByteArray(); } }
package hudson.tasks; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.EnvVars; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Node; import hudson.model.TaskListener; import hudson.remoting.ChannelClosedException; import java.io.IOException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; /** * Common part between {@link Shell} and {@link BatchFile}. * * @author Kohsuke Kawaguchi */ public abstract class CommandInterpreter extends Builder { /** * Command to execute. The format depends on the actual {@link CommandInterpreter} implementation. */ protected final String command; public CommandInterpreter(String command) { this.command = command; } public final String getCommand() { return command; } @Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException { return perform(build,launcher,(TaskListener)listener); } public boolean perform(AbstractBuild<?,?> build, Launcher launcher, TaskListener listener) throws InterruptedException { FilePath ws = build.getWorkspace(); if (ws == null) { Node node = build.getBuiltOn(); if (node == null) { throw new NullPointerException("no such build node: " + build.getBuiltOnStr()); } throw new NullPointerException("no workspace from node " + node + " which is computer " + node.toComputer() + " and has channel " + node.getChannel()); } FilePath script=null; int r = -1; try { try { script = createScriptFile(ws); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToProduceScript())); return false; } try { EnvVars envVars = build.getEnvironment(listener); // on Windows environment variables are converted to all upper case, // but no such conversions are done on Unix, so to make this cross-platform, // convert variables to all upper cases. for(Map.Entry<String,String> e : build.getBuildVariables().entrySet()) envVars.put(e.getKey(),e.getValue()); r = launcher.launch().cmds(buildCommandLine(script)).envs(envVars).stdout(listener).pwd(ws).join(); } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_CommandFailed())); } return r==0; } finally { try { if(script!=null) script.delete(); } catch (IOException e) { if (r==-1 && e.getCause() instanceof ChannelClosedException) { // JENKINS-5073 // r==-1 only when the execution of the command resulted in IOException, // and we've already reported that error. A common error there is channel // losing a connection, and in that case we don't want to confuse users // by reporting the 2nd problem. Technically the 1st exception may not be // a channel closed error, but that's rare enough, and JENKINS-5073 is common enough // that this suppressing of the error would be justified LOGGER.log(Level.FINE, "Script deletion failed", e); } else { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script)) ); } } catch (Exception e) { e.printStackTrace( listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script)) ); } } } /** * Creates a script file in a temporary name in the specified directory. */ public FilePath createScriptFile(@Nonnull FilePath dir) throws IOException, InterruptedException { return dir.createTextTempFile("hudson", getFileExtension(), getContents(), false); } public abstract String[] buildCommandLine(FilePath script); protected abstract String getContents(); protected abstract String getFileExtension(); private static final Logger LOGGER = Logger.getLogger(CommandInterpreter.class.getName()); }
package hudson.util; import groovy.lang.GroovyShell; import hudson.Functions; import hudson.model.Hudson; import hudson.remoting.Callable; import hudson.remoting.VirtualChannel; import hudson.remoting.DelegatingCallable; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ThreadInfo; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; /** * Various remoting operations related to diagnostics. * * <p> * These code are useful whereever {@link VirtualChannel} is used, such as master, slaves, Maven JVMs, etc. * * @author Kohsuke Kawaguchi * @since 1.175 */ public final class RemotingDiagnostics { public static Map<Object,Object> getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException { if(channel==null) return Collections.<Object,Object>singletonMap("N/A","N/A"); return channel.call(new GetSystemProperties()); } private static final class GetSystemProperties implements Callable<Map<Object,Object>,RuntimeException> { public Map<Object,Object> call() { return new TreeMap<Object,Object>(System.getProperties()); } private static final long serialVersionUID = 1L; } public static Map<String,String> getThreadDump(VirtualChannel channel) throws IOException, InterruptedException { if(channel==null) return Collections.singletonMap("N/A","N/A"); return channel.call(new GetThreadDump()); } private static final class GetThreadDump implements Callable<Map<String,String>,RuntimeException> { public Map<String,String> call() { Map<String,String> r = new LinkedHashMap<String,String>(); try { ThreadInfo[] data = Functions.getThreadInfos(); Functions.ThreadGroupMap map = Functions.sortThreadsAndGetGroupMap(data); for (ThreadInfo ti : data) r.put(ti.getThreadName(),Functions.dumpThreadInfo(ti,map)); } catch (LinkageError _) { // not in JDK6. fall back to JDK5 r.clear(); for (Map.Entry<Thread,StackTraceElement[]> t : Functions.dumpAllThreads().entrySet()) { StringBuilder buf = new StringBuilder(); for (StackTraceElement e : t.getValue()) buf.append(e).append('\n'); r.put(t.getKey().getName(),buf.toString()); } } return r; } private static final long serialVersionUID = 1L; } /** * Executes Groovy script remotely. */ public static String executeGroovy(String script, VirtualChannel channel) throws IOException, InterruptedException { return channel.call(new Script(script)); } private static final class Script implements DelegatingCallable<String,RuntimeException> { private final String script; private transient ClassLoader cl; private Script(String script) { this.script = script; cl = getClassLoader(); } public ClassLoader getClassLoader() { return Hudson.getInstance().getPluginManager().uberClassLoader; } public String call() throws RuntimeException { // if we run locally, cl!=null. Otherwise the delegating classloader will be available as context classloader. if (cl==null) cl = Thread.currentThread().getContextClassLoader(); GroovyShell shell = new GroovyShell(cl); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); shell.setVariable("out", pw); try { Object output = shell.evaluate(script); if(output!=null) pw.println("Result: "+output); } catch (Throwable t) { t.printStackTrace(pw); } return out.toString(); } } }
package net.runelite.api; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public enum Quest { //Free Quests BLACK_KNIGHTS_FORTRESS(299, "Black Knights' Fortress"), COOKS_ASSISTANT(300, "Cook's Assistant"), THE_CORSAIR_CURSE(301, "The Corsair Curse"), DEMON_SLAYER(302, "Demon Slayer"), DORICS_QUEST(3138, "Doric's Quest"), DRAGON_SLAYER_I(3139, "Dragon Slayer I"), ERNEST_THE_CHICKEN(305, "Ernest the Chicken"), GOBLIN_DIPLOMACY(306, "Goblin Diplomacy"), IMP_CATCHER(307, "Imp Catcher"), THE_KNIGHTS_SWORD(308, "The Knight's Sword"), MISTHALIN_MYSTERY(309, "Misthalin Mystery"), PIRATES_TREASURE(310, "Pirate's Treasure"), PRINCE_ALI_RESCUE(311, "Prince Ali Rescue"), THE_RESTLESS_GHOST(312, "The Restless Ghost"), ROMEO__JULIET(313, "Romeo & Juliet"), RUNE_MYSTERIES(314, "Rune Mysteries"), SHEEP_SHEARER(315, "Sheep Shearer"), SHIELD_OF_ARRAV(316, "Shield of Arrav"), VAMPYRE_SLAYER(1278, "Vampyre Slayer"), WITCHS_POTION(318, "Witch's Potion"), X_MARKS_THE_SPOT(3155, "X Marks the Spot"), BELOW_ICE_MOUNTAIN(2874, "Below Ice Mountain"), //Members' Quests ANIMAL_MAGNETISM(331, "Animal Magnetism"), ANOTHER_SLICE_OF_HAM(332, "Another Slice of H.A.M."), BETWEEN_A_ROCK(333, "Between a Rock..."), BIG_CHOMPY_BIRD_HUNTING(334, "Big Chompy Bird Hunting"), BIOHAZARD(335, "Biohazard"), CABIN_FEVER(336, "Cabin Fever"), CLOCK_TOWER(337, "Clock Tower"), COLD_WAR(338, "Cold War"), CONTACT(339, "Contact!"), CREATURE_OF_FENKENSTRAIN(340, "Creature of Fenkenstrain"), DARKNESS_OF_HALLOWVALE(341, "Darkness of Hallowvale"), DEATH_PLATEAU(342, "Death Plateau"), DEATH_TO_THE_DORGESHUUN(343, "Death to the Dorgeshuun"), THE_DEPTHS_OF_DESPAIR(344, "The Depths of Despair"), DESERT_TREASURE(345, "Desert Treasure"), DEVIOUS_MINDS(346, "Devious Minds"), THE_DIG_SITE(347, "The Dig Site"), DRAGON_SLAYER_II(348, "Dragon Slayer II"), DREAM_MENTOR(349, "Dream Mentor"), DRUIDIC_RITUAL(350, "Druidic Ritual"), DWARF_CANNON(351, "Dwarf Cannon"), EADGARS_RUSE(352, "Eadgar's Ruse"), EAGLES_PEAK(353, "Eagles' Peak"), ELEMENTAL_WORKSHOP_I(354, "Elemental Workshop I"), ELEMENTAL_WORKSHOP_II(355, "Elemental Workshop II"), ENAKHRAS_LAMENT(356, "Enakhra's Lament"), ENLIGHTENED_JOURNEY(357, "Enlightened Journey"), THE_EYES_OF_GLOUPHRIE(358, "The Eyes of Glouphrie"), FAIRYTALE_I__GROWING_PAINS(359, "Fairytale I - Growing Pains"), FAIRYTALE_II__CURE_A_QUEEN(360, "Fairytale II - Cure a Queen"), FAMILY_CREST(361, "Family Crest"), THE_FEUD(362, "The Feud"), FIGHT_ARENA(363, "Fight Arena"), FISHING_CONTEST(364, "Fishing Contest"), FORGETTABLE_TALE(365, "Forgettable Tale..."), BONE_VOYAGE(3135, "Bone Voyage"), THE_FREMENNIK_ISLES(367, "The Fremennik Isles"), THE_FREMENNIK_TRIALS(368, "The Fremennik Trials"), GARDEN_OF_TRANQUILLITY(369, "Garden of Tranquillity"), GERTRUDES_CAT(370, "Gertrude's Cat"), GHOSTS_AHOY(371, "Ghosts Ahoy"), THE_GIANT_DWARF(372, "The Giant Dwarf"), THE_GOLEM(373, "The Golem"), THE_GRAND_TREE(374, "The Grand Tree"), THE_GREAT_BRAIN_ROBBERY(375, "The Great Brain Robbery"), GRIM_TALES(376, "Grim Tales"), THE_HAND_IN_THE_SAND(377, "The Hand in the Sand"), HAUNTED_MINE(378, "Haunted Mine"), HAZEEL_CULT(379, "Hazeel Cult"), HEROES_QUEST(3142, "Heroes' Quest"), HOLY_GRAIL(381, "Holy Grail"), HORROR_FROM_THE_DEEP(382, "Horror from the Deep"), ICTHLARINS_LITTLE_HELPER(383, "Icthlarin's Little Helper"), IN_AID_OF_THE_MYREQUE(384, "In Aid of the Myreque"), IN_SEARCH_OF_THE_MYREQUE(385, "In Search of the Myreque"), JUNGLE_POTION(386, "Jungle Potion"), KINGS_RANSOM(387, "King's Ransom"), LEGENDS_QUEST(3145, "Legends' Quest"), LOST_CITY(389, "Lost City"), THE_LOST_TRIBE(390, "The Lost Tribe"), LUNAR_DIPLOMACY(391, "Lunar Diplomacy"), MAKING_FRIENDS_WITH_MY_ARM(392, "Making Friends with My Arm"), MAKING_HISTORY(393, "Making History"), MERLINS_CRYSTAL(394, "Merlin's Crystal"), MONKEY_MADNESS_I(395, "Monkey Madness I"), MONKEY_MADNESS_II(396, "Monkey Madness II"), MONKS_FRIEND(397, "Monk's Friend"), MOUNTAIN_DAUGHTER(398, "Mountain Daughter"), MOURNINGS_END_PART_I(3147, "Mourning's End Part I"), MOURNINGS_END_PART_II(3148, "Mourning's End Part II"), MURDER_MYSTERY(401, "Murder Mystery"), MY_ARMS_BIG_ADVENTURE(402, "My Arm's Big Adventure"), NATURE_SPIRIT(403, "Nature Spirit"), OBSERVATORY_QUEST(3149, "Observatory Quest"), OLAFS_QUEST(3150, "Olaf's Quest"), ONE_SMALL_FAVOUR(406, "One Small Favour"), PLAGUE_CITY(407, "Plague City"), PRIEST_IN_PERIL(408, "Priest in Peril"), THE_QUEEN_OF_THIEVES(409, "The Queen of Thieves"), RAG_AND_BONE_MAN_I(3152, "Rag and Bone Man I"), RAG_AND_BONE_MAN_II(411, "Rag and Bone Man II"), RATCATCHERS(412, "Ratcatchers"), RECIPE_FOR_DISASTER(413, "Recipe for Disaster"), RECRUITMENT_DRIVE(414, "Recruitment Drive"), REGICIDE(415, "Regicide"), ROVING_ELVES(416, "Roving Elves"), ROYAL_TROUBLE(417, "Royal Trouble"), RUM_DEAL(418, "Rum Deal"), SCORPION_CATCHER(419, "Scorpion Catcher"), SEA_SLUG(420, "Sea Slug"), SHADES_OF_MORTTON(421, "Shades of Mort'ton"), SHADOW_OF_THE_STORM(422, "Shadow of the Storm"), SHEEP_HERDER(423, "Sheep Herder"), SHILO_VILLAGE(424, "Shilo Village"), THE_SLUG_MENACE(425, "The Slug Menace"), A_SOULS_BANE(426, "A Soul's Bane"), SPIRITS_OF_THE_ELID(427, "Spirits of the Elid"), SWAN_SONG(428, "Swan Song"), TAI_BWO_WANNAI_TRIO(429, "Tai Bwo Wannai Trio"), A_TAIL_OF_TWO_CATS(430, "A Tail of Two Cats"), TALE_OF_THE_RIGHTEOUS(431, "Tale of the Righteous"), A_TASTE_OF_HOPE(432, "A Taste of Hope"), TEARS_OF_GUTHIX(433, "Tears of Guthix"), TEMPLE_OF_IKOV(434, "Temple of Ikov"), THRONE_OF_MISCELLANIA(435, "Throne of Miscellania"), THE_TOURIST_TRAP(436, "The Tourist Trap"), TOWER_OF_LIFE(437, "Tower of Life"), TREE_GNOME_VILLAGE(438, "Tree Gnome Village"), TRIBAL_TOTEM(439, "Tribal Totem"), TROLL_ROMANCE(440, "Troll Romance"), TROLL_STRONGHOLD(441, "Troll Stronghold"), UNDERGROUND_PASS(442, "Underground Pass"), CLIENT_OF_KOUREND(3136, "Client of Kourend"), WANTED(444, "Wanted!"), WATCHTOWER(445, "Watchtower"), WATERFALL_QUEST(3154, "Waterfall Quest"), WHAT_LIES_BELOW(447, "What Lies Below"), WITCHS_HOUSE(448, "Witch's House"), ZOGRE_FLESH_EATERS(449, "Zogre Flesh Eaters"), THE_ASCENT_OF_ARCEUUS(542, "The Ascent of Arceuus"), THE_FORSAKEN_TOWER(543, "The Forsaken Tower"), SONG_OF_THE_ELVES(603, "Song of the Elves"), THE_FREMENNIK_EXILES(3141, "The Fremennik Exiles"), SINS_OF_THE_FATHER(1276, "Sins of the Father"), A_PORCINE_OF_INTEREST(3151, "A Porcine of Interest"), GETTING_AHEAD(752, "Getting Ahead"), A_KINGDOM_DIVIDED(2971, "A Kingdom Divided"), A_NIGHT_AT_THE_THEATRE(949, "A Night at the Theatre"), LAND_OF_THE_GOBLINS(4135, "Land of the Goblins"), //Miniquests ENTER_THE_ABYSS(3140, "Enter the Abyss"), ARCHITECTURAL_ALLIANCE(320, "Architectural Alliance"), BEAR_YOUR_SOUL(1275, "Bear Your Soul"), ALFRED_GRIMHANDS_BARCRAWL(322, "Alfred Grimhand's Barcrawl"), CURSE_OF_THE_EMPTY_LORD(3137, "Curse of the Empty Lord"), THE_ENCHANTED_KEY(324, "The Enchanted Key"), THE_GENERALS_SHADOW(325, "The General's Shadow"), SKIPPY_AND_THE_MOGRES(3153, "Skippy and the Mogres"), MAGE_ARENA_I(3146, "Mage Arena I"), LAIR_OF_TARN_RAZORLOR(3144, "Lair of Tarn Razorlor"), FAMILY_PEST(329, "Family Pest"), MAGE_ARENA_II(330, "Mage Arena II"), IN_SEARCH_OF_KNOWLEDGE(3143, "In Search of Knowledge"), DADDYS_HOME(1688, "Daddy's Home"), THE_FROZEN_DOOR(3768, "The Frozen Door"), HOPESPEARS_WILL(4136, "Hopespear's Will"), ; @Getter private final int id; @Getter private final String name; public QuestState getState(Client client) { client.runScript(ScriptID.QUEST_STATUS_GET, id); switch (client.getIntStack()[0]) { case 2: return QuestState.FINISHED; case 1: return QuestState.NOT_STARTED; default: return QuestState.IN_PROGRESS; } } }
package net.achalaggarwal.workerbee; import lombok.Getter; import net.achalaggarwal.workerbee.dr.selectfunction.Constant; import org.apache.avro.Schema; import org.apache.avro.specific.SpecificRecord; import org.apache.hadoop.io.Text; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static net.achalaggarwal.workerbee.Utils.fqTableName; import static net.achalaggarwal.workerbee.Utils.joinList; public class Row<T extends Table> { public static final int ZERO_BASED = 0; public static final int ONE_BASED = 1; protected Map<Column, Object> map; @Getter protected T table; public Row(T table){ this.table = table; } public Row(T table, ResultSet resultSet){ this(table); this.map = parseRecordUsing(resultSet, ONE_BASED); } public Row(T table, Row record) { this(table); for (Column column : table.getColumns()) { set(column, record.get(column)); } for (Column column : table.getPartitions()) { set(column, record.get(column)); } } public Row(T table, String record){ this(table); this.map = parseRecordUsing( new RecordParser(record, table.getColumnSeparator(), table.getHiveNull()), ZERO_BASED ); } private Map<Column, Object> parseRecordUsing( ResultSet resultSet, int startingIndex ) { Map<Column, Object> map = new HashMap<>(table.getColumns().size()); int index = startingIndex; for (Column column : table.getColumns()) { map.put(column, column.parseValueUsing(resultSet, index++)); } for (Column column : table.getPartitions()) { map.put(column, column.parseValueUsing(resultSet, index++)); } return map; } public Object get(Column column) { return map.get(column); } public String getString(Column column) { return (String) get(column); } public Integer getInt(Column column) { return (Integer) get(column); } public Float getFloat(Column column) { return (Float) get(column); } public Row set(Column column, Object value) { if (map.containsKey(column)){ map.put(column, column.convert(value)); } return this; } public Constant getC(Column column) { return new Constant(map.get(column)); } public Constant[] getConstants() { List<Constant> constants = new ArrayList<>(); for (Column column : table.getColumns()) { constants.add(getC(column)); } for (Column column : table.getPartitions()) { constants.add(getC(column)); } return constants.toArray(new Constant[constants.size()]); } @SuppressWarnings({"SimplifiableConditionalExpression", "SimplifiableIfStatement"}) @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Row row = (Row) o; if (!map.equals(row.map)) return false; return table.isNotTemporary() && row.table.isNotTemporary() ? table.equals(row.table) : true; } @Override public int hashCode() { int result = map.hashCode(); result = 31 * result + table.hashCode(); return result; } @Override public String toString() { List<String> sb = new ArrayList<>(); for (Column column : map.keySet()) { sb.add(column.getName() + ":" + map.get(column)); } return fqTableName(table) + "@{" + joinList(sb, ", ") + '}'; } public String generateRecord() { return RowUtils.generateRecordFor(table, this); } }
package se.kodapan.osm.xml; import org.apache.commons.lang3.StringEscapeUtils; import se.kodapan.osm.domain.*; import se.kodapan.osm.domain.root.PojoRoot; import java.io.IOException; import java.io.Writer; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * @author kalle * @since 2013-09-02 5:03 PM */ public class OsmXmlWriter extends Writer { private Writer xml; private String version = "0.6"; private Boolean upload = true; private String generator = getClass().getName(); public OsmXmlWriter(Writer xml) throws IOException { this.xml = xml; writeHeader(); } public void writeHeader() throws IOException { xml.write("<?xml version='1.0' encoding='UTF-8'?>\n"); xml.write("<osm version='"); xml.write(version); if (upload != null) { xml.write("' upload='"); xml.write(upload ? "true" : "false"); xml.write("'"); } xml.write(" generator='"); xml.write(generator); xml.write("'>\n"); } public void writeFooter() throws IOException { xml.write("</osm>\n"); } public void write(PojoRoot root) throws IOException { for (Node node : root.getNodes().values()) { write(node); } for (Way way : root.getWays().values()) { write(way); } for (Relation relation : root.getRelations().values()) { write(relation); } } public void writeTags(OsmObject osmObject) throws IOException { // <tag k='landuse' v='farmland' /> if (osmObject.getTags() != null) { for (Map.Entry<String, String> tag : osmObject.getTags().entrySet()) { xml.write("\t\t<tag k='"); xml.write(tag.getKey()); xml.write("' v='"); xml.write(StringEscapeUtils.escapeXml(tag.getValue())); xml.write("' />\n"); } } } public void write(Node node) throws IOException { writeObjectHead(node); xml.write(" lat='"); xml.write(new DecimalFormat(" xml.write("'"); xml.write(" lon='"); xml.write(new DecimalFormat(" xml.write("'"); xml.write(" >\n"); writeTags(node); xml.write("\t</node>\n"); } public void write(Way way) throws IOException { writeObjectHead(way); xml.write(" >\n"); for (Node node : way.getNodes()) { xml.append("\t\t<nd ref='"); xml.append(String.valueOf(node.getId())); xml.append("' />\n"); node.getId(); } writeTags(way); xml.write("\t</way>\n"); } private OsmObjectVisitor<String> getOsmObjectTypeName = new OsmObjectVisitor<String>() { @Override public String visit(Node node) { return "node"; } @Override public String visit(Way way) { return "way"; } @Override public String visit(Relation relation) { return "relation"; } }; public void write(Relation relation) throws IOException { // <relation id='3146471' timestamp='2013-08-16T01:39:33Z' uid='194367' user='Karl Wettin' visible='true' version='1' changeset='17366616'> writeObjectHead(relation); xml.write(" >\n"); for (RelationMembership membership : relation.getMembers()) { xml.write("\t\t<member type='"); xml.write(membership.getObject().accept(getOsmObjectTypeName)); xml.write("'"); xml.write(" ref='"); xml.write(String.valueOf(membership.getObject().getId())); xml.write("'"); xml.write(" role='"); xml.write(membership.getRole()); xml.write("'"); xml.write(" />\n"); } writeTags(relation); xml.write("\t</relation>\n"); } private void writeObjectHead(OsmObject osmObject) throws IOException { xml.write("\t<"); xml.append(osmObject.accept(getOsmObjectTypeName)); xml.write(" "); xml.write(" id='"); xml.write(String.valueOf(osmObject.getId())); xml.write("'"); if (osmObject.getId() > -1) { xml.write(" timestamp='"); xml.write(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date(osmObject.getTimestamp()))); xml.write("'"); xml.write(" uid='"); xml.write(String.valueOf(osmObject.getUid())); xml.write("'"); xml.write(" user='"); xml.write(String.valueOf(osmObject.getUser())); xml.write("'"); xml.write(" version='"); xml.write(String.valueOf(osmObject.getVersion())); xml.write("'"); xml.write(" changeset='"); xml.write(String.valueOf(osmObject.getChangeset())); xml.write("'"); } } private boolean wroteHeader = false; @Override public synchronized void write(char[] cbuf, int off, int len) throws IOException { if (!wroteHeader) { wroteHeader = true; writeHeader(); } xml.write(cbuf, off, len); } @Override public void flush() throws IOException { xml.flush(); } @Override public void close() throws IOException { writeFooter(); xml.close(); } }
package org.folio.okapi.service; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Handler; import org.folio.okapi.bean.ModuleDescriptor; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.folio.okapi.bean.ModuleInterface; import org.folio.okapi.bean.Tenant; import org.folio.okapi.bean.TenantModuleDescriptor; import static org.folio.okapi.common.ErrorType.*; import org.folio.okapi.common.ExtendedAsyncResult; import org.folio.okapi.common.Failure; import org.folio.okapi.common.Success; import org.folio.okapi.util.LockedTypedMap1; import org.folio.okapi.util.ModuleId; /** * Manages a list of modules known to Okapi's "/_/proxy". Maintains consistency * checks on module versions, etc. Stores them in the database too, if we have * one. */ public class ModuleManager { private final Logger logger = LoggerFactory.getLogger("okapi"); private TenantManager tenantManager = null; private String mapName = "modules"; LockedTypedMap1<ModuleDescriptor> modules = new LockedTypedMap1<>(ModuleDescriptor.class); ModuleStore moduleStore; public ModuleManager(ModuleStore moduleStore) { this.moduleStore = moduleStore; } /** * Force the map to be local. Even in cluster mode, will use a local memory * map. This way, the node will not share tenants with the cluster, and can * not proxy requests for anyone but the superTenant, to the InternalModule. * Which is just enough to act in the deployment mode. */ public void forceLocalMap() { mapName = null; } public void setTenantManager(TenantManager tenantManager) { this.tenantManager = tenantManager; } public void init(Vertx vertx, Handler<ExtendedAsyncResult<Void>> fut) { modules.init(vertx, mapName, ires -> { if (ires.failed()) { fut.handle(new Failure<>(ires.getType(), ires.cause())); } else { loadModules(fut); } }); } /** * Load the modules from the database, if not already loaded. * * @param fut */ private void loadModules(Handler<ExtendedAsyncResult<Void>> fut) { if (moduleStore == null) { logger.debug("No ModuleStorage to load from, starting with empty"); fut.handle(new Success<>()); return; } modules.getKeys(kres -> { if (kres.failed()) { fut.handle(new Failure<>(kres.getType(), kres.cause())); return; } Collection<String> keys = kres.result(); if (!keys.isEmpty()) { logger.debug("Not loading modules, looks like someone already did"); fut.handle(new Success<>()); return; } moduleStore.getAll(mres -> { if (mres.failed()) { fut.handle(new Failure<>(mres.getType(), mres.cause())); return; } List<Future> futures = new LinkedList<>(); for (ModuleDescriptor md : mres.result()) { Future f = Future.future(); modules.add(md.getId(), md, f); futures.add(f); } CompositeFuture.all(futures).setHandler(res -> { if (res.failed()) { fut.handle(new Failure<>(INTERNAL, res.cause())); } else { fut.handle(new Success<>()); } }); }); }); } /** * Check one dependency. * * @param md module to check * @param req required dependency * @param modlist the list to check against * @return "" if ok, or error message */ private String checkOneDependency(ModuleDescriptor md, ModuleInterface req, Map<String, ModuleDescriptor> modlist) { ModuleInterface seenversion = null; for (Map.Entry<String, ModuleDescriptor> entry : modlist.entrySet()) { ModuleDescriptor rm = entry.getValue(); for (ModuleInterface pi : rm.getProvidesList()) { logger.debug("Checking dependency of " + md.getId() + ": " + req.getId() + " " + req.getVersion() + " against " + pi.getId() + " " + pi.getVersion()); if (req.getId().equals(pi.getId())) { seenversion = pi; if (pi.isCompatible(req)) { logger.debug("Dependency OK"); return ""; } } } } if (seenversion == null) { return "Missing dependency: " + md.getId() + " requires " + req.getId() + ": " + req.getVersion(); } else { return "Incompatible version for " + req.getId() + ". " + "Need " + req.getVersion() + ". have " + seenversion.getVersion(); } } /** * Check that the dependencies are satisfied. * * @param md Module to be checked * @return "" if no problems, or an error message * * This could be done like we do conflicts, by building a map and checking * against that... */ private String checkDependencies(ModuleDescriptor md, Map<String, ModuleDescriptor> modlist) { logger.debug("Checking dependencies of " + md.getId()); for (ModuleInterface req : md.getRequiresList()) { String res = checkOneDependency(md, req, modlist); if (!res.isEmpty()) { return res; } } return ""; } private int checkInterfaceDependency(ModuleInterface req, Map<String, ModuleDescriptor> modsAvailable, Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml) { logger.info("checkInterfaceDependency1"); for (Map.Entry<String, ModuleDescriptor> entry : modsEnabled.entrySet()) { ModuleDescriptor md = entry.getValue(); for (ModuleInterface pi : md.getProvidesList()) { if (req.getId().equals(pi.getId()) && pi.isCompatible(req)) { logger.debug("Dependency OK"); return 0; } } } logger.info("checkInterfaceDependency2"); ModuleDescriptor foundMd = null; for (Map.Entry<String, ModuleDescriptor> entry : modsAvailable.entrySet()) { ModuleDescriptor md = entry.getValue(); for (ModuleInterface pi : md.getProvidesList()) { if (req.getId().equals(pi.getId()) && pi.isCompatible(req) && (foundMd == null || md.compareTo(foundMd) > 0)) {// newest module foundMd = md; } } } if (foundMd == null) { return -1; } return addModuleDependencies(foundMd, modsAvailable, modsEnabled, tml); } private int resolveModuleConflicts(ModuleDescriptor md, Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml, List<ModuleDescriptor> fromModule) { int v = 0; Iterator<String> it = modsEnabled.keySet().iterator(); while (it.hasNext()) { String runningmodule = it.next(); ModuleDescriptor rm = modsEnabled.get(runningmodule); for (ModuleInterface pi : rm.getProvidesList()) { if (pi.isRegularHandler()) { String confl = pi.getId(); for (ModuleInterface mi : md.getProvidesList()) { if (mi.getId().equals(confl) && modsEnabled.containsKey(runningmodule)) { if (md.getProduct().equals(rm.getProduct())) { logger.info("resolveModuleConflicts from " + runningmodule); fromModule.add(rm); } else { logger.info("resolveModuleConflicts remove " + runningmodule); TenantModuleDescriptor tm = new TenantModuleDescriptor(); tm.setAction("disable"); tm.setId(runningmodule); tml.add(tm); } modsEnabled.remove(runningmodule); it = modsEnabled.keySet().iterator(); v++; } } } } } return v; } public int addModuleDependencies(ModuleDescriptor md, Map<String, ModuleDescriptor> modsAvailable, Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml) { int sum = 0; logger.info("addModuleDependencies " + md.getId()); for (ModuleInterface req : md.getRequiresList()) { int v = checkInterfaceDependency(req, modsAvailable, modsEnabled, tml); if (v == -1) { return v; } sum += v; } List<ModuleDescriptor> fromModule = new LinkedList<>(); sum += resolveModuleConflicts(md, modsEnabled, tml, fromModule); logger.info("addModuleDependencies - add " + md.getId()); modsEnabled.put(md.getId(), md); TenantModuleDescriptor tm = new TenantModuleDescriptor(); tm.setAction("enable"); if (!fromModule.isEmpty()) { tm.setFrom(fromModule.get(0).getId()); } tm.setId(md.getId()); tml.add(tm); return sum + 1; } public int removeModuleDependencies(ModuleDescriptor md, Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml) { int sum = 0; logger.info("removeModuleDependencies " + md.getId()); if (!modsEnabled.containsKey(md.getId())) { return 0; } ModuleInterface[] provides = md.getProvidesList(); for (ModuleInterface prov : provides) { if (prov.isRegularHandler()) { Iterator<String> it = modsEnabled.keySet().iterator(); while (it.hasNext()) { String runningmodule = it.next(); ModuleDescriptor rm = modsEnabled.get(runningmodule); ModuleInterface[] requires = rm.getRequiresList(); for (ModuleInterface ri : requires) { if (prov.getId().equals(ri.getId())) { sum += removeModuleDependencies(rm, modsEnabled, tml); it = modsEnabled.keySet().iterator(); } } } } } modsEnabled.remove(md.getId()); TenantModuleDescriptor tm = new TenantModuleDescriptor(); tm.setAction("disable"); tm.setId(md.getId()); tml.add(tm); return sum + 1; } /** * Check that all dependencies are satisfied. Usually called with a copy of * the modules list, after making some change. * * @param modlist list to check * @return error message, or "" if all is ok */ public String checkAllDependencies(Map<String, ModuleDescriptor> modlist) { for (ModuleDescriptor md : modlist.values()) { String res = checkDependencies(md, modlist); if (!res.isEmpty()) { return res; } } return ""; } /** * Check a module list for conflicts. * * @param modlist modules to be checked * @return error message listing conflicts, or "" if no problems */ public String checkAllConflicts(Map<String, ModuleDescriptor> modlist) { Map<String, String> provs = new HashMap<>(); // interface name to module name StringBuilder conflicts = new StringBuilder(); for (ModuleDescriptor md : modlist.values()) { ModuleInterface[] provides = md.getProvidesList(); for (ModuleInterface mi : provides) { if (mi.isRegularHandler()) { String confl = provs.get(mi.getId()); if (confl == null || confl.isEmpty()) { provs.put(mi.getId(), md.getId()); } else { String msg = "Interface " + mi.getId() + " is provided by " + md.getId() + " and " + confl + ". "; conflicts.append(msg); } } } } logger.debug("checkAllConflicts: " + conflicts.toString()); return conflicts.toString(); } /** * Create a module. * * @param md * @param fut */ public void create(ModuleDescriptor md, Handler<ExtendedAsyncResult<Void>> fut) { List<ModuleDescriptor> l = new LinkedList<>(); l.add(md); createList(l, fut); } /** * Create a whole list of modules. * * @param list * @param fut */ public void createList(List<ModuleDescriptor> list, Handler<ExtendedAsyncResult<Void>> fut) { modules.getAll(ares -> { if (ares.failed()) { fut.handle(new Failure<>(ares.getType(), ares.cause())); return; } LinkedHashMap<String, ModuleDescriptor> tempList = ares.result(); LinkedList<ModuleDescriptor> nList = new LinkedList<>(); for (ModuleDescriptor md : list) { final String id = md.getId(); if (tempList.containsKey(id)) { ModuleDescriptor exMd = tempList.get(id); String exJson = Json.encodePrettily(exMd); String json = Json.encodePrettily(md); if (!json.equals(exJson)) { fut.handle(new Failure<>(USER, "create: module " + id + " exists already")); return; } } else { tempList.put(id, md); nList.add(md); } } String res = checkAllDependencies(tempList); if (!res.isEmpty()) { fut.handle(new Failure<>(USER, res)); return; } Iterator<ModuleDescriptor> it = nList.iterator(); createListR(it, fut); }); } /** * Recursive helper for createList. * * @param it iterator of the module to be created * @param fut */ private void createListR(Iterator<ModuleDescriptor> it, Handler<ExtendedAsyncResult<Void>> fut) { if (!it.hasNext()) { fut.handle(new Success<>()); return; } ModuleDescriptor md = it.next(); String id = md.getId(); if (moduleStore == null) { modules.add(id, md, ares -> { if (ares.failed()) { fut.handle(new Failure<>(ares.getType(), ares.cause())); return; } createListR(it, fut); }); return; } moduleStore.insert(md, ires -> { if (ires.failed()) { fut.handle(new Failure<>(ires.getType(), ires.cause())); return; } modules.add(id, md, ares -> { if (ares.failed()) { fut.handle(new Failure<>(ares.getType(), ares.cause())); return; } createListR(it, fut); }); }); } /** * Update a module. * * @param md * @param fut */ public void update(ModuleDescriptor md, Handler<ExtendedAsyncResult<Void>> fut) { final String id = md.getId(); modules.getAll(ares -> { if (ares.failed()) { fut.handle(new Failure<>(ares.getType(), ares.cause())); return; } LinkedHashMap<String, ModuleDescriptor> tempList = ares.result(); tempList.put(id, md); String res = checkAllDependencies(tempList); if (!res.isEmpty()) { fut.handle(new Failure<>(USER, "update: module " + id + ": " + res)); return; } tenantManager.getModuleUser(id, gres -> { if (gres.failed()) { if (gres.getType() == ANY) { String ten = gres.cause().getMessage(); fut.handle(new Failure<>(USER, "update: module " + id + " is used by tenant " + ten)); } else { // any other error fut.handle(new Failure<>(gres.getType(), gres.cause())); } return; } // all ok, we can update it if (moduleStore == null) { // no db, just upd shared memory modules.put(id, md, fut); } else { moduleStore.update(md, ures -> { // store in db first, if (ures.failed()) { fut.handle(new Failure<>(ures.getType(), ures.cause())); } else { modules.put(id, md, fut); } }); } }); // getModuleUser }); // get } /** * Delete a module. * * @param id * @param fut */ public void delete(String id, Handler<ExtendedAsyncResult<Void>> fut) { modules.getAll(ares -> { if (ares.failed()) { fut.handle(new Failure<>(ares.getType(), ares.cause())); return; } if (deleteCheckDep(id, fut, ares.result())) { return; } tenantManager.getModuleUser(id, ures -> { if (ures.failed()) { if (ures.getType() == ANY) { String ten = ures.cause().getMessage(); fut.handle(new Failure<>(USER, "delete: module " + id + " is used by tenant " + ten)); } else { fut.handle(new Failure<>(ures.getType(), ures.cause())); } } else if (moduleStore == null) { deleteInternal(id, fut); } else { moduleStore.delete(id, dres -> { if (dres.failed()) { fut.handle(new Failure<>(dres.getType(), dres.cause())); } else { deleteInternal(id, fut); } }); } }); }); } private boolean deleteCheckDep(String id, Handler<ExtendedAsyncResult<Void>> fut, LinkedHashMap<String, ModuleDescriptor> mods) { LinkedHashMap<String, ModuleDescriptor> tempList = mods; if (!tempList.containsKey(id)) { fut.handle(new Failure<>(NOT_FOUND, "delete: module does not exist")); return true; } tempList.remove(id); String res = checkAllDependencies(tempList); if (!res.isEmpty()) { fut.handle(new Failure<>(USER, "delete: module " + id + ": " + res)); return true; } else { return false; } } private void deleteInternal(String id, Handler<ExtendedAsyncResult<Void>> fut) { modules.remove(id, rres -> { if (rres.failed()) { fut.handle(new Failure<>(rres.getType(), rres.cause())); } else { fut.handle(new Success<>()); } }); } /** * Get a module. * * @param id to get. If null, returns a null. * @param fut */ public void get(String id, Handler<ExtendedAsyncResult<ModuleDescriptor>> fut) { if (id != null) { modules.get(id, fut); } else { fut.handle(new Success<>(null)); } } public void getLatest(String id, Handler<ExtendedAsyncResult<ModuleDescriptor>> fut) { ModuleId moduleId = id != null ? new ModuleId(id) : null; if (moduleId == null || moduleId.hasSemVer()) { get(id, fut); } else { modules.getKeys(res2 -> { if (res2.failed()) { fut.handle(new Failure<>(res2.getType(), res2.cause())); } else { String latest = moduleId.getLatest(res2.result()); get(latest, fut); } }); } } public void getModulesWithFilter(ModuleId filter, boolean preRelease, Handler<ExtendedAsyncResult<List<ModuleDescriptor>>> fut) { modules.getAll(kres -> { if (kres.failed()) { fut.handle(new Failure<>(kres.getType(), kres.cause())); } else { List<ModuleDescriptor> mdl = new LinkedList<>(); for (ModuleDescriptor md : kres.result().values()) { String id = md.getId(); ModuleId idThis = new ModuleId(id); if (filter != null && !idThis.hasPrefix(filter)) { ; } else if (!preRelease && idThis.hasPreRelease()) { ; } else { mdl.add(md); } } fut.handle(new Success<>(mdl)); } }); } /** * Get all modules that are enabled for the given tenant. * * @param ten tenant to check for * @param fut callback with a list of ModuleDescriptors (may be empty list) */ public void getEnabledModules(Tenant ten, Handler<ExtendedAsyncResult<List<ModuleDescriptor>>> fut) { List<ModuleDescriptor> mdl = new LinkedList<>(); getEnabledModulesR(ten.getEnabled().keySet().iterator(), mdl, fut); } /** * Recursive helper to get modules from an iterator of ids. * * @param it * @param mdl * @param fut */ private void getEnabledModulesR(Iterator<String> it, List<ModuleDescriptor> mdl, Handler<ExtendedAsyncResult<List<ModuleDescriptor>>> fut) { if (!it.hasNext()) { fut.handle(new Success<>(mdl)); return; } String id = it.next(); ModuleId idThis = new ModuleId(id); modules.get(id, gres -> { if (gres.failed()) { fut.handle(new Failure<>(gres.getType(), gres.cause())); } else { ModuleDescriptor md = gres.result(); mdl.add(md); getEnabledModulesR(it, mdl, fut); } }); } }
package com.mickare.xserver.net; import java.io.IOException; import java.net.UnknownHostException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.mickare.xserver.Message; import com.mickare.xserver.XServerManager; import com.mickare.xserver.exceptions.NotConnectedException; import com.mickare.xserver.exceptions.NotInitializedException; import com.mickare.xserver.util.Encryption; public class XServer { private final String name; private final String host; private final int port; private final String password; private Connection connection = null; private Connection connection2 = null; // Fix for HomeServer that is not connectable. private Lock conLock = new ReentrantLock(); public XServer(String name, String host, int port, String password) { this.name = name; this.host = host; this.port = port; this.password = Encryption.MD5(password); } public void connect() throws UnknownHostException, IOException, InterruptedException, NotInitializedException { conLock.lock(); try { if (isConnected()) { this.disconnect(); } connection = new Connection(XServerManager.getInstance() .getSocketFactory(), host, port); } finally { conLock.unlock(); } } protected void setConnection(Connection con) { conLock.lock(); try { if (this.connection != con && isConnected()) { this.disconnect(); } this.connection = con; } finally { conLock.unlock(); } } public void setReloginConnection(Connection con) throws NotInitializedException { conLock.lock(); try { if(XServerManager.getInstance().getHomeServer() == this) { if (this.connection2 != con && ( connection2 != null ? connection2.isConnected() : false )) { this.disconnect(); } this.connection2 = con; } else { this.connection = con; } } finally { conLock.unlock(); } } public boolean isConnected() { conLock.lock(); try { return connection != null ? connection.isConnected() : false; } finally { conLock.unlock(); } } public void disconnect() { conLock.lock(); try { connection.disconnect(); } finally { conLock.unlock(); } } public String getName() { return name; } public String getHost() { return host; } public int getPort() { return port; } public String getPassword() { return password; } public void sendMessage(Message message) throws NotConnectedException, IOException { conLock.lock(); try { if (!isConnected()) { throw new NotConnectedException("Not Connected to this server!"); } connection .send(new Packet(Packet.Types.Message, message.getData())); } finally { conLock.unlock(); } } public void ping(Ping ping) throws InterruptedException, IOException { conLock.lock(); if(isConnected()) { connection.ping(ping); } conLock.unlock(); } }
package com.drew.metadata.apple; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.drew.lang.annotations.NotNull; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.exif.makernotes.AppleMakernoteDirectory; import com.drew.metadata.exif.makernotes.AppleRunTimeMakernoteDirectory; import com.drew.metadata.plist.BplistReader; /** * Reads the <tt>AppleRunTime</tt> data and adds {@link AppleRunTimeMakernoteDirectory} to the * parent {@link AppleMakernoteDirectory} if it can be parsed with no errors. */ public class AppleRunTimeReader { public void extract(@NotNull byte[] bytes, @NotNull final Metadata metadata, @NotNull final Directory parentDirectory) { parentDirectory.setByteArray(AppleMakernoteDirectory.TAG_RUN_TIME, bytes); if (!BplistReader.isValid(bytes)) { parentDirectory.addError("Input array is not a bplist"); return; } AppleRunTimeMakernoteDirectory directory = new AppleRunTimeMakernoteDirectory(); directory.setParent(parentDirectory); try { processAppleRunTime(directory, bytes); if (directory.getTagCount() > 0) { metadata.addDirectory(directory); } } catch (IOException e) { parentDirectory.addError("Error processing TAG_RUN_TIME: " + e.getMessage()); } } /** * Process the BPLIST containing the RUN_TIME tag. The directory will only be populated with values * if the <tt>flag</tt> indicates that the CMTime structure is &quot;valid&quot;. * * @param directory The <tt>AppleRunTimeMakernoteDirectory</tt> to set values onto. * @param bplist The BPLIST * @throws IOException Thrown if an error occurs parsing the BPLIST as a CMTime structure. */ private static void processAppleRunTime(@NotNull final AppleRunTimeMakernoteDirectory directory, @NotNull final byte[] bplist) throws IOException { final BplistReader.PropertyListResults results = BplistReader.parse(bplist); final Set<Map.Entry<Byte, Byte>> entrySet = results.getEntrySet(); if (entrySet != null) { HashMap<String, Object> values = new HashMap<String, Object>(entrySet.size()); for (Map.Entry<Byte, Byte> entry : entrySet) { String key = (String)results.getObjects().get(entry.getKey()); Object value = results.getObjects().get(entry.getValue()); values.put(key, value); } byte flags = (Byte)values.get("flags"); if ((flags & 0x1) == 0x1) { directory.setInt(AppleRunTimeMakernoteDirectory.CMTimeFlags, flags); directory.setInt(AppleRunTimeMakernoteDirectory.CMTimeEpoch, (Byte)values.get("epoch")); directory.setLong(AppleRunTimeMakernoteDirectory.CMTimeScale, (Long)values.get("timescale")); directory.setLong(AppleRunTimeMakernoteDirectory.CMTimeValue, (Long)values.get("value")); } } } }
package example; // -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ import java.awt.*; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); SpinnerModel model = new SpinnerNumberModel(5, 0, 10, 1); JSpinner spinner0 = new JSpinner(model); UIManager.put("Spinner.arrowButtonSize", new Dimension(60, 0)); JSpinner spinner1 = new JSpinner(model); JSpinner spinner2 = new JSpinner(model) { @Override public void updateUI() { super.updateUI(); stream(this) .filter(JButton.class::isInstance).map(JButton.class::cast) .forEach(b -> { Dimension d = b.getPreferredSize(); d.width = 40; b.setPreferredSize(d); }); } }; JSpinner spinner3 = new JSpinner(model) { @Override public void setLayout(LayoutManager mgr) { super.setLayout(new SpinnerLayout()); } }; JPanel p = new JPanel(new GridLayout(2, 2)); p.add(makeTitledPanel("default", spinner0)); p.add(makeTitledPanel("Spinner.arrowButtonSize", spinner1)); p.add(makeTitledPanel("setPreferredSize", spinner2)); p.add(makeTitledPanel("setLayout", spinner3)); JSpinner spinner4 = new JSpinner(model) { @Override public void updateUI() { super.updateUI(); setFont(getFont().deriveFont(32f)); stream(this) .filter(JButton.class::isInstance).map(JButton.class::cast) .forEach(b -> { Dimension d = b.getPreferredSize(); d.width = 50; b.setPreferredSize(d); }); } }; Box box = Box.createVerticalBox(); box.add(p); box.add(makeTitledPanel("setPreferredSize + setFont", spinner4)); add(box, BorderLayout.NORTH); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } public static Stream<Component> stream(Container parent) { return Stream.of(parent.getComponents()) .filter(Container.class::isInstance).map(c -> stream(Container.class.cast(c))) .reduce(Stream.of(parent), Stream::concat); } private static Component makeTitledPanel(String title, Component c) { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(c); return p; } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JMenuBar mb = new JMenuBar(); mb.add(LookAndFeelUtil.createLookAndFeelMenu()); JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.setJMenuBar(mb); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // @see javax/swing/plaf/basic/BasicSpinnerUI.java class SpinnerLayout implements LayoutManager { private Component nextButton; private Component previousButton; private Component editor; @Override public void addLayoutComponent(String name, Component c) { if ("Next".equals(name)) { nextButton = c; } else if ("Previous".equals(name)) { previousButton = c; } else if ("Editor".equals(name)) { editor = c; } } @Override public void removeLayoutComponent(Component c) { if (Objects.equals(c, nextButton)) { nextButton = null; } else if (Objects.equals(c, previousButton)) { previousButton = null; } else if (Objects.equals(c, editor)) { editor = null; } } private static Dimension preferredSize(Component c) { return Optional.ofNullable(c).map(Component::getPreferredSize).orElseGet(() -> new Dimension()); } @Override public Dimension preferredLayoutSize(Container parent) { Dimension nextD = preferredSize(nextButton); Dimension previousD = preferredSize(previousButton); Dimension editorD = preferredSize(editor); // Force the editors height to be a multiple of 2 editorD.height = ((editorD.height + 1) / 2) * 2; Dimension size = new Dimension(editorD.width, editorD.height); size.width += Math.max(nextD.width, previousD.width); Insets insets = parent.getInsets(); size.width += insets.left + insets.right; size.height += insets.top + insets.bottom; return size; } @Override public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } private static void setBounds(Component c, int x, int y, int width, int height) { if (Objects.nonNull(c)) { c.setBounds(x, y, width, height); } } @Override public void layoutContainer(Container parent) { int width = parent.getWidth(); int height = parent.getHeight(); Insets insets = parent.getInsets(); if (nextButton == null && previousButton == null) { setBounds(editor, insets.left, insets.top, width - insets.left - insets.right, height - insets.top - insets.bottom); return; } // Dimension nextD = preferredSize(nextButton); // Dimension previousD = preferredSize(previousButton); int buttonsWidth = 100; // Math.max(nextD.width, previousD.width); int editorHeight = height - (insets.top + insets.bottom); // The arrowButtonInsets value is used instead of the JSpinner's // insets if not null. Defining this to be (0, 0, 0, 0) causes the // buttons to be aligned with the outer edge of the spinner's // border, and leaving it as "null" places the buttons completely // inside the spinner's border. Insets buttonInsets = UIManager.getInsets("Spinner.arrowButtonInsets"); if (buttonInsets == null) { buttonInsets = insets; } // Deal with the spinner's componentOrientation property. int editorX; int editorWidth; int buttonsX; if (parent.getComponentOrientation().isLeftToRight()) { editorX = insets.left; editorWidth = width - insets.left - buttonsWidth - buttonInsets.right; buttonsX = width - buttonsWidth - buttonInsets.right; } else { buttonsX = buttonInsets.left; editorX = buttonsX + buttonsWidth; editorWidth = width - buttonInsets.left - buttonsWidth - insets.right; } int nextY = buttonInsets.top; int nextHeight = height / 2 + height % 2 - nextY; int previousY = buttonInsets.top + nextHeight; int previousHeight = height - previousY - buttonInsets.bottom; setBounds(editor, editorX, insets.top, editorWidth, editorHeight); setBounds(nextButton, buttonsX, nextY, buttonsWidth, nextHeight); setBounds(previousButton, buttonsX, previousY, buttonsWidth, previousHeight); } } final class LookAndFeelUtil { private static String lookAndFeel = UIManager.getLookAndFeel().getClass().getName(); private LookAndFeelUtil() { /* Singleton */ } public static JMenu createLookAndFeelMenu() { JMenu menu = new JMenu("LookAndFeel"); ButtonGroup lafRadioGroup = new ButtonGroup(); for (UIManager.LookAndFeelInfo lafInfo: UIManager.getInstalledLookAndFeels()) { menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName(), lafRadioGroup)); } return menu; } private static JRadioButtonMenuItem createLookAndFeelItem(String lafName, String lafClassName, ButtonGroup lafRadioGroup) { JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(lafName, lafClassName.equals(lookAndFeel)); lafItem.setActionCommand(lafClassName); lafItem.setHideActionText(true); lafItem.addActionListener(e -> { ButtonModel m = lafRadioGroup.getSelection(); try { setLookAndFeel(m.getActionCommand()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } }); lafRadioGroup.add(lafItem); return lafItem; } private static void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { String oldLookAndFeel = LookAndFeelUtil.lookAndFeel; if (!oldLookAndFeel.equals(lookAndFeel)) { UIManager.setLookAndFeel(lookAndFeel); LookAndFeelUtil.lookAndFeel = lookAndFeel; updateLookAndFeel(); // firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel); } } private static void updateLookAndFeel() { for (Window window: Frame.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } } }
package io.tetrapod.core; import static io.tetrapod.protocol.core.CoreContract.*; import java.io.*; import java.lang.management.ManagementFactory; import java.net.ConnectException; import java.util.*; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Timer.Context; import ch.qos.logback.classic.LoggerContext; import io.netty.channel.socket.SocketChannel; import io.tetrapod.core.pubsub.Publisher; import io.tetrapod.core.pubsub.Topic; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.utils.*; import io.tetrapod.protocol.core.*; public class DefaultService implements Service, Fail.FailHandler, CoreContract.API, SessionFactory, EntityMessage.Handler, TetrapodContract.Cluster.API { private static final Logger logger = LoggerFactory.getLogger(DefaultService.class); protected final Set<Integer> dependencies = new HashSet<>(); public final Dispatcher dispatcher; protected final Client clusterClient; protected final Contract contract; protected final ServiceCache services; protected boolean terminated; protected int entityId; protected int parentId; protected String token; private int status; public final String buildName; protected final LogBuffer logBuffer; protected SSLContext sslContext; private ServiceConnector serviceConnector; protected final ServiceStats stats; protected boolean startPaused; private final LinkedList<ServerAddress> clusterMembers = new LinkedList<>(); private final MessageHandlers messageHandlers = new MessageHandlers(); private final Publisher publisher = new Publisher(this); public DefaultService() { this(null); } public DefaultService(Contract mainContract) { logBuffer = (LogBuffer) ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("ROOT").getAppender("BUFFER"); String m = getStartLoggingMessage(); logger.info(m); Session.commsLog.info(m); Fail.handler = this; synchronized (this) { status |= Core.STATUS_STARTING; } dispatcher = new Dispatcher(); clusterClient = new Client(this); stats = new ServiceStats(this); addContracts(new CoreContract()); addPeerContracts(new TetrapodContract()); addMessageHandler(new EntityMessage(), this); addSubscriptionHandler(new TetrapodContract.Cluster(), this); try { if (Util.getProperty("tetrapod.tls", true)) { sslContext = Util.createSSLContext(new FileInputStream(Util.getProperty("tetrapod.jks.file", "cfg/tetrapod.jks")), System.getProperty("tetrapod.jks.pwd", "4pod.dop4").toCharArray()); } } catch (Exception e) { fail(e); } if (getEntityType() != Core.TYPE_TETRAPOD) { services = new ServiceCache(); addSubscriptionHandler(new TetrapodContract.Services(), services); } else { services = null; } Runtime.getRuntime().addShutdownHook(new Thread("Shutdown Hook") { @Override public void run() { logger.info("Shutdown Hook"); if (!isShuttingDown()) { shutdown(false); } } }); String build = "Unknown"; try { build = Util.readFileAsString(new File("build_name.txt")); } catch (IOException e) {} buildName = build; checkHealth(); if (mainContract != null) addContracts(mainContract); this.contract = mainContract; } /** * Returns a prefix for all exported metrics from this service. */ private String getMetricsPrefix() { return Util.getProperty("devMode", "") + "." + Util.getProperty("product.name") + "." + Util.getHostName() + "." + getClass().getSimpleName(); } public byte getEntityType() { return Core.TYPE_SERVICE; } public synchronized int getStatus() { return status; } @Override public void messageEntity(EntityMessage m, MessageContext ctxA) { SessionMessageContext ctx = (SessionMessageContext) ctxA; if (ctx.session.getTheirEntityType() == Core.TYPE_TETRAPOD) { synchronized (this) { this.entityId = m.entityId; } ctx.session.setMyEntityId(m.entityId); } } @Override public void genericMessage(Message message, MessageContext ctx) { logger.error("Unhandled message handler: {}", message.dump()); assert false; } // Service protocol @Override public void startNetwork(ServerAddress server, String token, Map<String, String> otherOpts) throws Exception { this.token = token; this.startPaused = otherOpts.get("paused").equals("true"); clusterMembers.addFirst(server); connectToCluster(5); } /** * Called after we've registered and dependencies are all available */ public void onReadyToServe() {} private void onServiceRegistered() { registerServiceInformation(); stats.publishTopic(); logger.info("@@@@@ ServicesSubscribeRequest"); sendDirectRequest(new ServicesSubscribeRequest()).handle(res -> logger.info("{}", res.dump())); } public boolean dependenciesReady() { return services.checkDependencies(dependencies); } private final Object checkDependenciesLock = new Object(); public void checkDependencies() { synchronized (checkDependenciesLock) { if (!isShuttingDown() && isStartingUp()) { logger.info("Checking Dependencies..."); if (dependenciesReady()) { try { if (startPaused) { updateStatus(getStatus() | Core.STATUS_PAUSED); } AdminAuthToken.setSecret(Util.getProperty(AdminAuthToken.SHARED_SECRET_KEY)); onReadyToServe(); if (serviceConnector != null) { serviceConnector.shutdown(); } serviceConnector = new ServiceConnector(this, sslContext); } catch (Throwable t) { fail(t); } // ok, we're good to go updateStatus(getStatus() & ~Core.STATUS_STARTING); onStarted(); if (startPaused) { onPaused(); startPaused = false; // only start paused once } } else { dispatcher.dispatch(1, TimeUnit.SECONDS, () -> checkDependencies()); } } } } /** * Periodically checks service health, updates metrics */ private void checkHealth() { if (!isShuttingDown()) { if (dispatcher.workQueueSize.getCount() > 0) { logger.warn("DISPATCHER QUEUE SIZE = {} ({} threads busy)", dispatcher.workQueueSize.getCount(), dispatcher.getActiveThreads()); } if (logBuffer.hasErrors()) { updateStatus(getStatus() | Core.STATUS_ERRORS); } else { updateStatus(getStatus() & ~Core.STATUS_ERRORS); } if (logBuffer.hasWarnings()) { updateStatus(getStatus() | Core.STATUS_WARNINGS); } else { updateStatus(getStatus() & ~Core.STATUS_WARNINGS); } dispatcher.dispatch(1, TimeUnit.SECONDS, () -> checkHealth()); } } /** * Called before shutting down. Default implementation is to do nothing. Subclasses are expecting to close any resources they opened (for * example database connections or file handles). * * @param restarting true if we are shutting down in order to restart */ public void onShutdown(boolean restarting) {} public void onPaused() {} public void onPurged() {} public void onReleaseExcess() {} public void onRebalance() {} public void onUnpaused() {} public void onStarted() {} public void shutdown(boolean restarting) { updateStatus(getStatus() | Core.STATUS_STOPPING); try { onShutdown(restarting); } catch (Exception e) { logger.error(e.getMessage(), e); } if (restarting) { clusterClient.close(); dispatcher.shutdown(); setTerminated(true); try { Launcher.relaunch(getRelaunchToken()); } catch (Exception e) { logger.error(e.getMessage(), e); } } else { if (getEntityId() != 0 && clusterClient.getSession() != null) { sendDirectRequest(new UnregisterRequest(getEntityId())).handle(res -> { clusterClient.close(); dispatcher.shutdown(); setTerminated(true); }); } else { dispatcher.shutdown(); setTerminated(true); } } // If JVM doesn't gracefully terminate after 1 minute, explicitly kill the process final Thread hitman = new Thread(() -> { Util.sleep(Util.ONE_MINUTE); logger.warn("Service did not complete graceful termination. Force Killing JVM."); final Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces(); for (Thread t : map.keySet()) { logger.warn("{}", t); } System.exit(1); } , "Hitman"); hitman.setDaemon(true); hitman.start(); } public ServiceCache getServiceCache() { return services; } protected String getRelaunchToken() { return token; } /** * Session factory for our session to our parent TetrapodService */ @Override public Session makeSession(SocketChannel ch) { final Session ses = new WireSession(ch, DefaultService.this); ses.setMyEntityType(getEntityType()); ses.setTheirEntityType(Core.TYPE_TETRAPOD); ses.addSessionListener(new Session.Listener() { @Override public void onSessionStop(Session ses) { onDisconnectedFromCluster(); } @Override public void onSessionStart(Session ses) { onConnectedToCluster(); } }); return ses; } private void onConnectedToCluster() { final Request req = new RegisterRequest(token, getContractId(), getShortName(), getStatus(), Util.getHostName(), buildName); sendDirectRequest(req).handle(res -> { if (res.isError()) { logger.error("Unable to register: " + req.dump() + " ==> " + res); clusterClient.close(); } else { RegisterResponse r = (RegisterResponse) res; entityId = r.entityId; parentId = r.parentId; token = r.token; clusterClient.getSession().setMyEntityId(r.entityId); clusterClient.getSession().setTheirEntityId(r.parentId); clusterClient.getSession().setMyEntityType(getEntityType()); clusterClient.getSession().setTheirEntityType(Core.TYPE_TETRAPOD); logger.info(String.format("%s My entityId is 0x%08X", clusterClient.getSession(), r.entityId)); onServiceRegistered(); } }); } public void onDisconnectedFromCluster() { publisher.resetTopics(); if (!isShuttingDown()) { logger.info("Connection to tetrapod closed"); dispatcher.dispatch(3, TimeUnit.SECONDS, () -> connectToCluster(1)); } } public boolean isConnected() { return clusterClient.isConnected(); } protected void connectToCluster(final int retrySeconds) { if (!isShuttingDown() && !clusterClient.isConnected()) { synchronized (clusterMembers) { final ServerAddress server = clusterMembers.poll(); if (server != null) { try { if (sslContext != null) { clusterClient.enableTLS(sslContext); } clusterClient.connect(server.host, server.port, dispatcher).sync(); if (clusterClient.isConnected()) { clusterMembers.addFirst(server); return; } } catch (ConnectException e) { logger.info(e.getMessage()); } catch (Throwable e) { logger.error(e.getMessage(), e); } clusterMembers.addLast(server); } } // schedule a retry dispatcher.dispatch(retrySeconds, TimeUnit.SECONDS, () -> connectToCluster(retrySeconds)); } } // subclass utils protected void addContracts(Contract... contracts) { for (Contract c : contracts) { c.registerStructs(); } } protected void addPeerContracts(Contract... contracts) { for (Contract c : contracts) { c.registerPeerStructs(); } } public int getEntityId() { return entityId; } protected int getParentId() { return parentId; } public synchronized boolean isShuttingDown() { return (status & Core.STATUS_STOPPING) != 0; } public synchronized boolean isPaused() { return (status & Core.STATUS_PAUSED) != 0; } public synchronized boolean isStartingUp() { return (status & Core.STATUS_STARTING) != 0; } public synchronized boolean isNominal() { int nonRunning = Core.STATUS_STARTING | Core.STATUS_FAILED | Core.STATUS_BUSY | Core.STATUS_PAUSED | Core.STATUS_STOPPING; return (status & nonRunning) == 0; } public synchronized boolean isTerminated() { return terminated; } private synchronized void setTerminated(boolean val) { logger.info("TERMINATED"); terminated = val; } protected void updateStatus(int status) { boolean changed = false; synchronized (this) { changed = this.status != status; this.status = status; } if (changed && clusterClient.isConnected()) { sendDirectRequest(new ServiceStatusUpdateRequest(status)).log(); } } @Override public void fail(Throwable error) { logger.error(error.getMessage(), error); updateStatus(status | Core.STATUS_FAILED); } @Override public void fail(String reason) { logger.error("FAIL: {}", reason); updateStatus(status | Core.STATUS_FAILED); } /** * Get a URL for this service's icon to display in the admin apps. Subclasses should override this to customize */ public String getServiceIcon() { return "media/gear.gif"; } /** * Get any custom metadata for the service. Subclasses should override this to customize */ public String getServiceMetadata() { return null; } /** * Get any custom admin commands for the service to show in command menu of admin app. Subclasses should override this to customize */ public ServiceCommand[] getServiceCommands() { return null; } public String getShortName() { if (contract == null) { return null; } return contract.getName(); } protected String getFullName() { if (contract == null) { return null; } String s = contract.getClass().getCanonicalName(); return s.substring(0, s.length() - "Contract".length()); } public long getAverageResponseTime() { // TODO: verify this is correctly converting nanos to millis return (long) dispatcher.requestTimes.getSnapshot().getMean() / 1000000L; } /** * Services can override this to provide a service specific counter for display in the admin app */ public long getCounter() { return 0; } public long getNumRequestsHandled() { return dispatcher.requestsHandledCounter.getCount(); } public long getNumMessagesSent() { return dispatcher.messagesSentCounter.getCount(); } /** * Dispatches a request to ourselves */ @Override public Async dispatchRequest(final RequestHeader header, final Request req, final Session fromSession) { final Async async = new Async(req, header, fromSession); final ServiceAPI svc = getServiceHandler(header.contractId); if (svc != null) { final long start = System.nanoTime(); final Context context = dispatcher.requestTimes.time(); if (!dispatcher.dispatch(() -> { final long dispatchTime = System.nanoTime(); try { if (Util.nanosToMillis(dispatchTime - start) > 2500) { if ((getStatus() & Core.STATUS_OVERLOADED) == 0) { logger.warn("Service is overloaded. Dispatch time is {}ms", Util.nanosToMillis(dispatchTime - start)); } // If it took a while to get dispatched, so set STATUS_OVERLOADED flag as a back-pressure signal updateStatus(getStatus() | Core.STATUS_OVERLOADED); } else { updateStatus(getStatus() & ~Core.STATUS_OVERLOADED); } final RequestContext ctx = fromSession != null ? new SessionRequestContext(header, fromSession) : new InternalRequestContext(header, new ResponseHandler() { @Override public void onResponse(Response res) { try { assert res != Response.PENDING; async.setResponse(res); } catch (Throwable e) { logger.error(e.getMessage(), e); async.setResponse(new Error(ERROR_UNKNOWN)); } } }); Response res = req.securityCheck(ctx); if (res == null) { res = req.dispatch(svc, ctx); } if (res != null) { if (res != Response.PENDING) { async.setResponse(res); } } else { async.setResponse(new Error(ERROR_UNKNOWN)); } } catch (ErrorResponseException e) { async.setResponse(new Error(e.errorCode)); } catch (Throwable e) { logger.error(e.getMessage(), e); async.setResponse(new Error(ERROR_UNKNOWN)); } finally { final long elapsed = System.nanoTime() - dispatchTime; stats.recordRequest(header.fromId, req, elapsed); context.stop(); dispatcher.requestsHandledCounter.mark(); if (Util.nanosToMillis(elapsed) > 1000) { logger.warn("Request took {} {} millis", req, Util.nanosToMillis(elapsed)); } } } , Session.DEFAULT_OVERLOAD_THRESHOLD)) { // too many items queued, full-force back-pressure async.setResponse(new Error(ERROR_SERVICE_OVERLOADED)); updateStatus(getStatus() | Core.STATUS_OVERLOADED); } } else { logger.warn("{} No handler found for {}", this, header.dump()); async.setResponse(new Error(ERROR_UNKNOWN_REQUEST)); } return async; } public Response sendPendingRequest(Request req, int toEntityId, PendingResponseHandler handler) { if (serviceConnector != null) { return serviceConnector.sendPendingRequest(req, toEntityId, handler); } return clusterClient.getSession().sendPendingRequest(req, toEntityId, (byte) 30, handler); } public Response sendPendingRequest(Request req, PendingResponseHandler handler) { if (serviceConnector != null) { return serviceConnector.sendPendingRequest(req, Core.UNADDRESSED, handler); } return clusterClient.getSession().sendPendingRequest(req, Core.UNADDRESSED, (byte) 30, handler); } public Response sendPendingDirectRequest(Request req, PendingResponseHandler handler) { return clusterClient.getSession().sendPendingRequest(req, Core.DIRECT, (byte) 30, handler); } public Async sendRequest(Request req) { if (serviceConnector != null) { return serviceConnector.sendRequest(req, Core.UNADDRESSED); } return clusterClient.getSession().sendRequest(req, Core.UNADDRESSED, (byte) 30); } public Async sendRequest(Request req, int toEntityId) { if (serviceConnector != null) { return serviceConnector.sendRequest(req, toEntityId); } return clusterClient.getSession().sendRequest(req, toEntityId, (byte) 30); } public Async sendDirectRequest(Request req) { return clusterClient.getSession().sendRequest(req, Core.DIRECT, (byte) 30); } public boolean isServiceExistant(int entityId) { return services.isServiceExistant(entityId); } public void sendMessage(Message msg, int toEntityId) { if (serviceConnector != null && isServiceExistant(toEntityId)) { serviceConnector.sendMessage(msg, toEntityId); } else { clusterClient.getSession().sendMessage(msg, toEntityId); } } public void sendAltBroadcastMessage(Message msg, int altId) { clusterClient.getSession().sendAltBroadcastMessage(msg, altId); } public void sendBroadcastMessage(Message msg, int toEntityId, int topicId) { if (serviceConnector != null) { serviceConnector.sendBroadcastMessage(msg, toEntityId, topicId); } else { clusterClient.getSession().sendTopicBroadcastMessage(msg, toEntityId, topicId); } } public Topic publishTopic() { return publisher.publish(); } /** * Subscribe an entity to the given topic. If once is true, tetrapod won't subscribe them a second time */ public void subscribe(int topicId, int entityId, boolean once) { publisher.subscribe(topicId, entityId, once); } public void subscribe(int topicId, int entityId) { subscribe(topicId, entityId, false); } public void unsubscribe(int topicId, int entityId) { publisher.unsubscribe(topicId, entityId); } public void unpublish(int topicId) { publisher.unpublish(topicId); } // Generic handlers for all request/subscriptions @Override public Response genericRequest(Request r, RequestContext ctx) { logger.error("unhandled request " + r.dump()); return new Error(CoreContract.ERROR_UNKNOWN_REQUEST); } public void setDependencies(int... contractIds) { for (int contractId : contractIds) { dependencies.add(contractId); } } // Session.Help implementation @Override public Dispatcher getDispatcher() { return dispatcher; } public ServiceAPI getServiceHandler(int contractId) { // this method allows us to have delegate objects that directly handle some contracts return this; } @Override public List<SubscriptionAPI> getMessageHandlers(int contractId, int structId) { return messageHandlers.get(contractId, structId); } @Override public int getContractId() { return contract == null ? 0 : contract.getContractId(); } public void addSubscriptionHandler(Contract sub, SubscriptionAPI handler) { messageHandlers.add(sub, handler); } public void addMessageHandler(Message k, SubscriptionAPI handler) { messageHandlers.add(k, handler); } @Override public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) { logger.info("******** {}", m.dump()); clusterMembers.add(new ServerAddress(m.host, m.servicePort)); } @Override public void messageClusterPropertyAdded(ClusterPropertyAddedMessage m, MessageContext ctx) { logger.info("******** {}", m.dump()); System.setProperty(m.property.key, m.property.val); } @Override public void messageClusterPropertyRemoved(ClusterPropertyRemovedMessage m, MessageContext ctx) { logger.info("******** {}", m.dump()); System.clearProperty(m.key); } @Override public void messageClusterSynced(ClusterSyncedMessage m, MessageContext ctx) { Metrics.init(getMetricsPrefix()); checkDependencies(); } // private methods protected void registerServiceInformation() { if (contract != null) { AddServiceInformationRequest asi = new AddServiceInformationRequest(); asi.info = new ContractDescription(); asi.info.contractId = contract.getContractId(); asi.info.version = contract.getContractVersion(); asi.info.routes = contract.getWebRoutes(); asi.info.structs = new ArrayList<>(); for (Structure s : contract.getRequests()) { asi.info.structs.add(s.makeDescription()); } for (Structure s : contract.getResponses()) { asi.info.structs.add(s.makeDescription()); } for (Structure s : contract.getMessages()) { asi.info.structs.add(s.makeDescription()); } for (Structure s : contract.getStructs()) { asi.info.structs.add(s.makeDescription()); } sendDirectRequest(asi).handle(ResponseHandler.LOGGER); } } // Base service implementation @Override public Response requestPause(PauseRequest r, RequestContext ctx) { // TODO: Check admin rights or macaroon updateStatus(getStatus() | Core.STATUS_PAUSED); onPaused(); return Response.SUCCESS; } @Override public Response requestPurge(PurgeRequest r, RequestContext ctx) { onPurged(); return Response.SUCCESS; } @Override public Response requestRebalance(RebalanceRequest r, RequestContext ctx) { onRebalance(); return Response.SUCCESS; } @Override public Response requestReleaseExcess(ReleaseExcessRequest r, RequestContext ctx) { onReleaseExcess(); return Response.SUCCESS; } @Override public Response requestUnpause(UnpauseRequest r, RequestContext ctx) { // TODO: Check admin rights or macaroon updateStatus(getStatus() & ~Core.STATUS_PAUSED); onUnpaused(); return Response.SUCCESS; } @Override public Response requestRestart(RestartRequest r, RequestContext ctx) { // TODO: Check admin rights or macaroon dispatcher.dispatch(() -> shutdown(true)); return Response.SUCCESS; } @Override public Response requestShutdown(ShutdownRequest r, RequestContext ctx) { // TODO: Check admin rights or macaroon dispatcher.dispatch(() -> shutdown(false)); return Response.SUCCESS; } @Override public Response requestServiceDetails(ServiceDetailsRequest r, RequestContext ctx) { return new ServiceDetailsResponse(getServiceIcon(), getServiceMetadata(), getServiceCommands()); } @Override public Response requestServiceStatsSubscribe(ServiceStatsSubscribeRequest r, RequestContext ctx) { stats.subscribe(ctx.header.fromId); return Response.SUCCESS; } @Override public Response requestServiceStatsUnsubscribe(ServiceStatsUnsubscribeRequest r, RequestContext ctx) { stats.unsubscribe(ctx.header.fromId); return Response.SUCCESS; } @Override public Response requestServiceLogs(ServiceLogsRequest r, RequestContext ctx) { if (logBuffer == null) { return new Error(CoreContract.ERROR_NOT_CONFIGURED); } final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>(); long last = logBuffer.getItems(r.logId, logBuffer.convert(r.level), r.maxItems, list); return new ServiceLogsResponse(last, list); } protected String getStartLoggingMessage() { return "*** Start Service ***" + "\n *** Service name: " + Util.getProperty("APPNAME") + "\n *** Options: " + Launcher.getAllOpts() + "\n *** VM Args: " + ManagementFactory.getRuntimeMXBean().getInputArguments().toString(); } @Override public Response requestServiceErrorLogs(ServiceErrorLogsRequest r, RequestContext ctx) { if (logBuffer == null) { return new Error(CoreContract.ERROR_NOT_CONFIGURED); } final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>(); list.addAll(logBuffer.getErrors()); list.addAll(logBuffer.getWarnings()); Collections.sort(list, (e1, e2) -> ((Long) e1.timestamp).compareTo(e2.timestamp)); return new ServiceErrorLogsResponse(list); } @Override public Response requestResetServiceErrorLogs(ResetServiceErrorLogsRequest r, RequestContext ctx) { if (logBuffer == null) { return new Error(CoreContract.ERROR_NOT_CONFIGURED); } logBuffer.resetErrorLogs(); return Response.SUCCESS; } @Override public Response requestSetCommsLogLevel(SetCommsLogLevelRequest r, RequestContext ctx) { ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("comms"); if (logger == null) { return new Error(CoreContract.ERROR_NOT_CONFIGURED); } logger.setLevel(ch.qos.logback.classic.Level.valueOf(r.level)); return Response.SUCCESS; } @Override public Response requestWebAPI(WebAPIRequest r, RequestContext ctx) { return Response.error(CoreContract.ERROR_UNKNOWN_REQUEST); } @Override public Response requestDirectConnection(DirectConnectionRequest r, RequestContext ctx) { if (serviceConnector != null) { return serviceConnector.requestDirectConnection(r, ctx); } return new Error(CoreContract.ERROR_NOT_CONFIGURED); } @Override public Response requestValidateConnection(ValidateConnectionRequest r, RequestContext ctx) { if (serviceConnector != null) { return serviceConnector.requestValidateConnection(r, ctx); } return new Error(CoreContract.ERROR_NOT_CONFIGURED); } @Override public Response requestDummy(DummyRequest r, RequestContext ctx) { return Response.SUCCESS; } @Override public Response requestHostInfo(HostInfoRequest r, RequestContext ctx) { return new HostInfoResponse(Util.getHostName(), (byte) Metrics.getNumCores(), null); } @Override public Response requestHostStats(HostStatsRequest r, RequestContext ctx) { return new HostStatsResponse(Metrics.getLoadAverage(), Metrics.getFreeDiskSpace()); } @Override public Response requestServiceRequestStats(ServiceRequestStatsRequest r, RequestContext ctx) { return stats.getRequestStats(r.domain, r.limit, r.minTime, r.sortBy); } }
package org.javarosa.core.model; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapTagged; import org.javarosa.core.util.externalizable.Externalizable; import org.javarosa.core.util.externalizable.PrototypeFactory; /** * A Submission Profile is a class which is responsible for * holding and processing the details of how a submission * should be handled. * * @author ctsims * */ public class SubmissionProfile implements Externalizable { IDataReference ref; String method; String action; String mediaType; public SubmissionProfile() { } public SubmissionProfile(IDataReference ref, String method, String action, String mediatype) { this.method = method; this.ref = ref; this.action = action; this.mediaType = mediatype; } public IDataReference getRef() { return ref; } public String getMethod() { return method; } public String getAction() { return action; } public String getMediaType() { return mediaType; } public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { ref = (IDataReference)ExtUtil.read(in, new ExtWrapTagged(IDataReference.class)); method = ExtUtil.readString(in); action = ExtUtil.readString(in); mediaType = ExtUtil.nullIfEmpty(ExtUtil.readString(in)); } public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.write(out, new ExtWrapTagged(ref)); ExtUtil.writeString(out, method); ExtUtil.writeString(out, action); ExtUtil.writeString(out, ExtUtil.emptyIfNull(mediaType)); } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.model; import java.io.Serializable; import java.util.Date; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.core.style.ToStringCreator; @Entity @Table(name="events") public class OnmsEvent extends OnmsEntity implements Serializable { private static final long serialVersionUID = -7412025003474162992L; /** identifier field */ private Integer m_eventId; /** persistent field */ private String m_eventUei; /** persistent field */ private Date m_eventTime; /** nullable persistent field */ private String m_eventHost; /** persistent field */ private String m_eventSource; /** nullable persistent field */ private String m_ipAddr; /** persistent field */ private OnmsDistPoller m_distPoller; /** nullable persistent field */ private String m_eventSnmpHost; /** nullable persistent field */ private OnmsServiceType m_serviceType; /** nullable persistent field */ private String m_eventSnmp; /** nullable persistent field */ private String m_eventParms; /** persistent field */ private Date m_eventCreateTime; /** nullable persistent field */ private String m_eventDescr; /** nullable persistent field */ private String m_eventLogGroup; /** nullable persistent field */ private String m_eventLogMsg; /** persistent field */ private Integer m_eventSeverity; /** nullable persistent field */ private String m_eventPathOutage; /** nullable persistent field */ private String m_eventCorrelation; /** nullable persistent field */ private Integer m_eventSuppressedCount; /** nullable persistent field */ private String m_eventOperInstruct; /** nullable persistent field */ private String m_eventAutoAction; /** nullable persistent field */ private String m_eventOperAction; /** nullable persistent field */ private String m_eventOperActionMenuText; /** nullable persistent field */ private String m_eventNotification; /** nullable persistent field */ private String m_eventTTicket; /** nullable persistent field */ private Integer m_eventTTicketState; /** nullable persistent field */ private String m_eventForward; /** nullable persistent field */ private String m_eventMouseOverText; /** persistent field */ private String m_eventLog; /** persistent field */ private String m_eventDisplay; /** nullable persistent field */ private String m_eventAckUser; /** nullable persistent field */ private Date m_eventAckTime; /** nullable persistent field */ private OnmsAlarm m_alarm; /** persistent field */ private org.opennms.netmgt.model.OnmsNode m_node; /** persistent field */ private Set<OnmsNotification> m_notifications; /** persistent field */ private Set<OnmsOutage> m_outagesBySvcRegainedEventId; /** persistent field */ private Set<OnmsOutage> m_outagesBySvclostEventId; /** full constructor */ public OnmsEvent(Integer eventid, String eventuei, Date eventtime, String eventhost, String eventsource, String ipaddr, OnmsDistPoller distPoller, String eventsnmphost, OnmsServiceType service, String eventsnmp, String eventparms, Date eventcreatetime, String eventdescr, String eventloggroup, String eventlogmsg, Integer eventseverity, String eventpathoutage, String eventcorrelation, Integer eventsuppressedcount, String eventoperinstruct, String eventautoaction, String eventoperaction, String eventoperactionmenutext, String eventnotification, String eventtticket, Integer eventtticketstate, String eventforward, String eventmouseovertext, String eventlog, String eventdisplay, String eventackuser, Date eventacktime, OnmsAlarm alarm, org.opennms.netmgt.model.OnmsNode node, Set<OnmsNotification> notifications, Set<OnmsOutage> outagesBySvcregainedeventid, Set<OnmsOutage> outagesBySvclosteventid) { m_eventId = eventid; m_eventUei = eventuei; m_eventTime = eventtime; m_eventHost = eventhost; m_eventSource = eventsource; m_ipAddr = ipaddr; m_distPoller = distPoller; m_eventSnmpHost = eventsnmphost; m_serviceType = service; m_eventSnmp = eventsnmp; m_eventParms = eventparms; m_eventCreateTime = eventcreatetime; m_eventDescr = eventdescr; m_eventLogGroup = eventloggroup; m_eventLogMsg = eventlogmsg; m_eventSeverity = eventseverity; m_eventPathOutage = eventpathoutage; m_eventCorrelation = eventcorrelation; m_eventSuppressedCount = eventsuppressedcount; m_eventOperInstruct = eventoperinstruct; m_eventAutoAction = eventautoaction; m_eventOperAction = eventoperaction; m_eventOperActionMenuText = eventoperactionmenutext; m_eventNotification = eventnotification; m_eventTTicket = eventtticket; m_eventTTicketState = eventtticketstate; m_eventForward = eventforward; m_eventMouseOverText = eventmouseovertext; m_eventLog = eventlog; m_eventDisplay = eventdisplay; m_eventAckUser = eventackuser; m_eventAckTime = eventacktime; m_alarm = alarm; m_node = node; m_notifications = notifications; m_outagesBySvcRegainedEventId = outagesBySvcregainedeventid; m_outagesBySvclostEventId = outagesBySvclosteventid; } /** default constructor */ public OnmsEvent() { } /** minimal constructor */ public OnmsEvent(Integer eventid, String eventuei, Date eventtime, String eventsource, OnmsDistPoller distPoller, Date eventcreatetime, Integer eventseverity, String eventlog, String eventdisplay, org.opennms.netmgt.model.OnmsNode node, Set<OnmsNotification> notifications, Set<OnmsOutage> outagesBySvcregainedeventid, Set<OnmsOutage> outagesBySvclosteventid, Set alarms) { m_eventId = eventid; m_eventUei = eventuei; m_eventTime = eventtime; m_eventSource = eventsource; m_distPoller = distPoller; m_eventCreateTime = eventcreatetime; m_eventSeverity = eventseverity; m_eventLog = eventlog; m_eventDisplay = eventdisplay; m_node = node; m_notifications = notifications; m_outagesBySvcRegainedEventId = outagesBySvcregainedeventid; m_outagesBySvclostEventId = outagesBySvclosteventid; } /** * @hibernate.id generator-class="assigned" type="java.lang.Integer" * column="eventid" * @hibernate.generator-param name="sequence" value="eventsNxtId" */ @Id @SequenceGenerator(name="eventSequence", sequenceName="eventsNxtId") @GeneratedValue(generator="eventSequence") public Integer getId() { return m_eventId; } public void setId(Integer eventid) { m_eventId = eventid; } @Column(name="eventUei", length=256, nullable=false) public String getEventUei() { return m_eventUei; } public void setEventUei(String eventuei) { m_eventUei = eventuei; } @Temporal(TemporalType.TIMESTAMP) @Column(name="eventTime", nullable=false) public Date getEventTime() { return m_eventTime; } public void setEventTime(Date eventtime) { m_eventTime = eventtime; } @Column(name="eventHost", length=256) public String getEventHost() { return m_eventHost; } public void setEventHost(String eventhost) { m_eventHost = eventhost; } @Column(name="eventSource", length=128, nullable=false) public String getEventSource() { return m_eventSource; } public void setEventSource(String eventsource) { m_eventSource = eventsource; } @Column(name="ipAddr", length=16) public String getIpAddr() { return m_ipAddr; } public void setIpAddr(String ipaddr) { m_ipAddr = ipaddr; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="eventDpName", nullable=false) public OnmsDistPoller getDistPoller() { return m_distPoller; } public void setDistPoller(OnmsDistPoller distPoller) { m_distPoller = distPoller; } @Column(name="eventSnmpHost", length=256) public String getEventSnmpHost() { return m_eventSnmpHost; } public void setEventSnmpHost(String eventsnmphost) { m_eventSnmpHost = eventsnmphost; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="serviceId", nullable=true) public OnmsServiceType getServiceType() { return m_serviceType; } public void setServiceType(OnmsServiceType serviceType) { m_serviceType = serviceType; } @Column(name="eventSnmp", length=256) public String getEventSnmp() { return m_eventSnmp; } public void setEventSnmp(String eventsnmp) { m_eventSnmp = eventsnmp; } @Column(name="eventParms", length=1024) public String getEventParms() { return m_eventParms; } public void setEventParms(String eventparms) { m_eventParms = eventparms; } @Temporal(TemporalType.TIMESTAMP) @Column(name="eventCreateTime", nullable=false) public Date getEventCreateTime() { return m_eventCreateTime; } public void setEventCreateTime(Date eventcreatetime) { m_eventCreateTime = eventcreatetime; } @Column(name="eventDescr", length=4000) public String getEventDescr() { return m_eventDescr; } public void setEventDescr(String eventdescr) { m_eventDescr = eventdescr; } @Column(name="eventLogGroup", length=32) public String getEventLogGroup() { return m_eventLogGroup; } public void setEventLogGroup(String eventloggroup) { m_eventLogGroup = eventloggroup; } @Column(name="eventLogMsg", length=256) public String getEventLogMsg() { return m_eventLogMsg; } public void setEventLogMsg(String eventlogmsg) { m_eventLogMsg = eventlogmsg; } @Column(name="eventSeverity", nullable=false) public Integer getEventSeverity() { return m_eventSeverity; } public void setEventSeverity(Integer severity) { m_eventSeverity = severity; } @Column(name="eventPathOutage", length=1024) public String getEventPathOutage() { return m_eventPathOutage; } public void setEventPathOutage(String eventpathoutage) { m_eventPathOutage = eventpathoutage; } @Column(name="eventCorrelation", length=1024) public String getEventCorrelation() { return m_eventCorrelation; } public void setEventCorrelation(String eventcorrelation) { m_eventCorrelation = eventcorrelation; } @Column(name="eventSuppressedCount") public Integer getEventSuppressedCount() { return m_eventSuppressedCount; } public void setEventSuppressedCount(Integer eventsuppressedcount) { m_eventSuppressedCount = eventsuppressedcount; } @Column(name="eventOperInstruct", length=1024) public String getEventOperInstruct() { return m_eventOperInstruct; } public void setEventOperInstruct(String eventoperinstruct) { m_eventOperInstruct = eventoperinstruct; } @Column(name="eventAutoAction", length=256) public String getEventAutoAction() { return m_eventAutoAction; } public void setEventAutoAction(String eventautoaction) { m_eventAutoAction = eventautoaction; } @Column(name="eventOperAction", length=256) public String getEventOperAction() { return m_eventOperAction; } public void setEventOperAction(String eventoperaction) { m_eventOperAction = eventoperaction; } @Column(name="eventOperActionMenuText", length=64) public String getEventOperActionMenuText() { return m_eventOperActionMenuText; } public void setEventOperActionMenuText(String eventOperActionMenuText) { m_eventOperActionMenuText = eventOperActionMenuText; } @Column(name="eventNotification", length=128) public String getEventNotification() { return m_eventNotification; } public void setEventNotification(String eventnotification) { m_eventNotification = eventnotification; } @Column(name="eventTTicket", length=128) public String getEventTTicket() { return m_eventTTicket; } public void setEventTTicket(String eventtticket) { m_eventTTicket = eventtticket; } @Column(name="eventTTicketState") public Integer getEventTTicketState() { return m_eventTTicketState; } public void setEventTTicketState(Integer eventtticketstate) { m_eventTTicketState = eventtticketstate; } @Column(name="eventForward", length=256) public String getEventForward() { return m_eventForward; } public void setEventForward(String eventforward) { m_eventForward = eventforward; } @Column(name="eventMouseOverText", length=64) public String getEventMouseOverText() { return m_eventMouseOverText; } public void setEventMouseOverText(String eventmouseovertext) { m_eventMouseOverText = eventmouseovertext; } /** * TODO: Make this an Enum */ @Column(name="eventLog", length=1, nullable=false) public String getEventLog() { return m_eventLog; } public void setEventLog(String eventlog) { m_eventLog = eventlog; } /** * TODO: make this an Enum * */ @Column(name="eventDisplay", length=1, nullable=false) public String getEventDisplay() { return m_eventDisplay; } public void setEventDisplay(String eventdisplay) { m_eventDisplay = eventdisplay; } @Column(name="eventAckUser", length=256) public String getEventAckUser() { return m_eventAckUser; } public void setEventAckUser(String eventackuser) { m_eventAckUser = eventackuser; } @Temporal(TemporalType.TIMESTAMP) @Column(name="eventAckTime") public Date getEventAckTime() { return m_eventAckTime; } public void setEventAckTime(Date eventacktime) { m_eventAckTime = eventacktime; } @ManyToOne @JoinColumn(name="alarmId") public OnmsAlarm getAlarm() { return m_alarm; } public void setAlarm(OnmsAlarm alarm) { m_alarm = alarm; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="nodeId") public OnmsNode getNode() { return m_node; } public void setNode(OnmsNode node) { m_node = node; } @OneToMany(mappedBy="event", fetch=FetchType.LAZY) public Set<OnmsNotification> getNotifications() { return m_notifications; } public void setNotifications(Set<OnmsNotification> notifications) { m_notifications = notifications; } @OneToMany(mappedBy="eventBySvcRegainedEvent", fetch=FetchType.LAZY) public Set<OnmsOutage> getOutagesBySvcRegainedEventId() { return m_outagesBySvcRegainedEventId; } public void setOutagesBySvcRegainedEventId(Set<OnmsOutage> outagesBySvcregainedeventid) { m_outagesBySvcRegainedEventId = outagesBySvcregainedeventid; } @OneToMany(mappedBy="eventBySvcLostEvent", fetch=FetchType.LAZY) public Set<OnmsOutage> getOutagesBySvclostEventId() { return m_outagesBySvclostEventId; } public void setOutagesBySvclostEventId(Set<OnmsOutage> outagesBySvclosteventid) { m_outagesBySvclostEventId = outagesBySvclosteventid; } public String toString() { return new ToStringCreator(this).append("eventid", getId()) .toString(); } public void visit(EntityVisitor visitor) { throw new RuntimeException("visitor method not implemented"); } }
package com.navercorp.utilset.ui; import android.content.Context; public class DisplayUtils { public static int getDpFromPixel(Context context, int pixel) { float scale = context.getResources().getDisplayMetrics().density; // get display density return (int)(pixel / scale); } public static int getPixelFromDP(Context context, int dp) { // Get the screen's density scale float scale = context.getResources().getDisplayMetrics().density; // Convert the dps to pixels, based on density scale return (int)(dp * scale + 0.5f); } }
package edu.wustl.catissuecore.query; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.tree.DefaultMutableTreeNode; import edu.wustl.catissuecore.bizlogic.BizLogicFactory; import edu.wustl.catissuecore.bizlogic.QueryBizLogic; import edu.wustl.catissuecore.util.SearchUtil; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.util.logger.Logger; /** * @author poornima_govindrao * *This class is for diplaying the tree in query view of Advanced Search * */ public class TreeView { //Variable which holds node ID in the tree. private int nodeId=0; private boolean andOrBool = false; //Recursive function to create the tree public void arrangeTree(DefaultMutableTreeNode node,int parentId,Vector tree,Map advancedConditionNodesMap,int checkedNode,String operation) throws Exception { nodeId++; //Loop for all the children for the current node. for(int i = 0; i < node.getChildCount();i++){ //nodeCount++; DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i); DefaultMutableTreeNode parent = (DefaultMutableTreeNode)child.getParent(); //Condition that allow to start from Participant as a parent node if(!parent.isRoot()) { AdvancedConditionsNode parentAdvConditionNode = (AdvancedConditionsNode)parent.getUserObject(); String temp = parentAdvConditionNode.getOperationWithChildCondition().getOperator(); //Condition to provide Psudo And if(temp.equals(Operator.EXIST)) { andOrBool = true; } else { andOrBool = false; } } AdvancedConditionsNode advConditionNode = (AdvancedConditionsNode)child.getUserObject(); advancedConditionNodesMap.put(new Integer(nodeId),child); if(nodeId == checkedNode) { if(operation.equals(Operator.EXIST)) { //Condition to set value only when selected node has child if(child.getChildCount() > 0) advConditionNode.setOperationWithChildCondition(new Operator(Operator.EXIST)); } else { advConditionNode.setOperationWithChildCondition(new Operator(Operator.OR)); } } Vector vectorOfCondtions = advConditionNode.getObjectConditions(); String tableName = advConditionNode.getObjectName(); String str = ""; Condition con = null; DataElement data = null; for(int k = 0; k < vectorOfCondtions.size(); k++) { con = (Condition)vectorOfCondtions.get(k); data = con.getDataElement(); Operator op = con.getOperator(); String value = con.getValue(); String columnName = data.getField(); String table = data.getTable(); //split column name in case of Specimen event parameters to remove aliasName //StringTokenizer columnNameTokenizer = new StringTokenizer(columnName,"."); QueryBizLogic bizLogic = (QueryBizLogic)BizLogicFactory .getBizLogic(Constants.SIMPLE_QUERY_INTERFACE_ID); // String columnDisplayName = bizLogic.getColumnDisplayNames(table,columnName); int formId = SearchUtil.getFormId(tableName); String columnDisplayName = SearchUtil.getColumnDisplayName(formId,table,columnName); //append table name to the column name in case of event parameters conditions. if(table.indexOf("Parameter")>0) { StringTokenizer tableTokens = new StringTokenizer(table,"."); String superTable = new String(); if(tableTokens.countTokens()==2) { table = tableTokens.nextToken(); superTable = tableTokens.nextToken(); } Map eventParameterDisplayNames = SearchUtil.getEventParametersDisplayNames(bizLogic,SearchUtil.getEventParametersTables(bizLogic)); columnDisplayName = (String)eventParameterDisplayNames.get(table+"."+columnName); Logger.out.debug("column display name for event parameters"+columnDisplayName); } if(columnDisplayName.equals("")) { columnDisplayName=columnName; } Logger.out.debug("Column Display name in tree view:"+columnDisplayName); String column = data.getField(); if(k == 0) { //str = temp + "|" + parentId + "|" +data.getTable()+": "+data.getField()+ " "+op.getOperator() + " "+con.getValue(); str = nodeId + "|" + parentId + "|" +columnDisplayName+ " "+ op.getOperator() + " " + value+ ""; } else //str = str +" "+"AND"+" "+data.getField()+" "+op.getOperator() + " "+con.getValue(); str = str +" "+"<font color='red'>AND</font>"+" "+columnDisplayName+" "+op.getOperator() + " "+value+ ""; // entered by Mandar for validation of single quotes around the values. Logger.out.debug( "STR : } if(data != null) if(andOrBool) { str = str + "|" + tableName + "|true"; } else { str = str + "|" + tableName + "|false"; } if(con == null) { if(andOrBool) { str = nodeId + "|" + parentId + "|" + "ANY" + "|"+advConditionNode.getObjectName() + "|true"; } else { str = nodeId + "|" + parentId + "|" + "ANY" + "|"+advConditionNode.getObjectName() + "|false"; } } Logger.out.debug("STR in TREVIEW--"+str); tree.add(str); andOrBool = false; if(child.isLeaf()) { nodeId++; } else arrangeTree(child,nodeId,tree,advancedConditionNodesMap,checkedNode,operation); } } }
package weave.servlets; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.rmi.RemoteException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Vector; import java.util.zip.DeflaterOutputStream; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.postgresql.util.Base64; import weave.beans.JsonRpcErrorModel; import weave.beans.JsonRpcRequestModel; import weave.beans.JsonRpcResponseModel; import weave.utils.CSVParser; import weave.utils.ListUtils; import weave.utils.MapUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.heatonresearch.httprecipes.html.PeekableInputStream; import com.thoughtworks.paranamer.BytecodeReadingParanamer; import com.thoughtworks.paranamer.Paranamer; import flex.messaging.FlexContext; import flex.messaging.MessageException; import flex.messaging.io.SerializationContext; import flex.messaging.io.TypeMarshallingContext; import flex.messaging.io.amf.ASObject; import flex.messaging.io.amf.Amf3Input; import flex.messaging.io.amf.Amf3Output; import flex.messaging.messages.ErrorMessage; /** * This class provides a servlet interface to a set of functions. * The functions may be invoked using URL parameters via HTTP GET using url parameters * or via HTTP POST using JSON RPC 2.0 or AMF3-serialized objects. * If using URL variables or JSON RPC 2.0, the return value will be provided as a JSON RPC 2.0 response object. * If using AMF3, the return value will be provided as compressed AMF3. * * @author skota * @author adufilie * @author skolman */ public class WeaveServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static long debugThreshold = 1000; /** * The name of the property which contains the remote method name. */ protected final String METHOD = "method"; /** * The name of the property which contains method parameters. */ protected final String PARAMS = "params"; /** * The name of the property which specifies the index in the params Array that corresponds to an InputStream. */ protected final String STREAM_PARAMETER_INDEX = "streamParameterIndex"; private Map<String, ExposedMethod> methodMap = new HashMap<String, ExposedMethod>(); //Key: methodName private Paranamer paranamer = new BytecodeReadingParanamer(); // this gets parameter names from Methods private SerializationContext serializationContext; /** * This class contains a Method with its parameter names and class instance. */ private class ExposedMethod { public ExposedMethod(Object instance, Method method, String[] paramNames) { this.instance = instance; this.method = method; this.paramNames = paramNames; } public Object instance; public Method method; public String[] paramNames; } /** * @param serviceObjects The objects to invoke methods on. */ protected WeaveServlet(Object ...serviceObjects) { super(); try { // explicitly initialize this method initMethod(this, WeaveServlet.class.getMethod(GET_CAPABILITIES)); } catch (NoSuchMethodException e) { e.printStackTrace(); } // automatically initialize methods of this object initAllMethods(this); for (Object serviceObject : serviceObjects) initAllMethods(serviceObject); } public void init(ServletConfig config) throws ServletException { super.init(config); serializationContext = SerializationContext.getSerializationContext(); // set serialization context properties serializationContext.enableSmallMessages = true; serializationContext.instantiateTypes = true; serializationContext.supportRemoteClass = true; serializationContext.legacyCollection = false; serializationContext.legacyMap = false; serializationContext.legacyXMLDocument = false; serializationContext.legacyXMLNamespaces = false; serializationContext.legacyThrowable = false; serializationContext.legacyBigNumbers = false; serializationContext.restoreReferences = false; serializationContext.logPropertyErrors = false; serializationContext.ignorePropertyErrors = true; cleanupThreadLocals(); } private static void cleanupThreadLocals() { // Below is a fix for the following error: // SEVERE: The web application [/WeaveServices] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@10d6a3f]) and a value of type [flex.messaging.io.SerializationContext] (value [flex.messaging.io.SerializationContext@1ba7ccc]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak. // Solution found at http://forum.spring.io/forum/spring-projects/web/flex/80980-shutting-down-flex-message-broker-cleanly?p=551551#post551551 // Clear the thread locals used by the 'main' startup thread. // Otherwise get thread leak messages from Tomcat on application shutdown. FlexContext.clearThreadLocalObjects(); // Clear other thread local objects on the 'main' initialization thread SerializationContext.clearThreadLocalObjects(); TypeMarshallingContext.clearThreadLocalObjects(); } /** * This function will expose all the declared public methods of a class as servlet methods, * except methods that match those declared by WeaveServlet or a superclass of WeaveServlet. * @param serviceObject The object containing public methods to be exposed by the servlet. */ protected void initAllMethods(Object serviceObject) { for (Method method : serviceObject.getClass().getDeclaredMethods()) { try { // if this succeeds, we don't want to initialize the method automatically WeaveServlet.class.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { // no matching method found in WeaveServlet, so initialize the method initMethod(serviceObject, method); } } } /** * @param serviceObject The instance of an object to use in the servlet. * @param method The method to expose on serviceObject. */ synchronized protected void initMethod(Object serviceObject, Method method) { // only expose public methods if (!Modifier.isPublic(method.getModifiers())) return; String methodName = method.getName(); if (methodMap.containsKey(methodName)) { methodMap.put(methodName, null); System.err.println(String.format( "Method %s.%s will not be supported because there are multiple definitions.", this.getClass().getName(), methodName )); } else { String[] paramNames = null; paramNames = paranamer.lookupParameterNames(method, false); // returns null if not found methodMap.put(methodName, new ExposedMethod(serviceObject, method, paramNames)); } } protected static class ServletRequestInfo { public ServletRequestInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { this.request = request; this.response = response; this.inputStream = new PeekableInputStream(request.getInputStream()); } private ServletOutputStream _servletOutputStream = null; /** * It's important to use this function to get the ServletOutputStream instead of response.getOutputStream(), which can only be called once per request. * @return The ServletOutputStream from the HTTPServletResponse object. */ public ServletOutputStream getOutputStream() throws IOException { if (_servletOutputStream == null) _servletOutputStream = response.getOutputStream(); return _servletOutputStream; } public HttpServletRequest request; public HttpServletResponse response; public JsonRpcRequestModel currentJsonRequest; public List<JsonRpcResponseModel> jsonResponses = new Vector<JsonRpcResponseModel>(); public Number streamParameterIndex = null; public PeekableInputStream inputStream; public Boolean isBatchRequest = false; public boolean prettyPrinting = false; } /** * This maps a thread to the corresponding RequestInfo for the doGet() or doPost() call that thread is handling. */ private Map<Thread,ServletRequestInfo> _servletRequestInfo = new HashMap<Thread,ServletRequestInfo>(); /** * This function retrieves the ServletRequestInfo associated with the current thread's doGet() or doPost() call. * From the ServletRequestInfo object you can get the ServletOutputStream. * In a public function with a void return type, you can use the ServletOutputStream for full control over the output. */ protected ServletRequestInfo getServletRequestInfo() { synchronized (_servletRequestInfo) { return _servletRequestInfo.get(Thread.currentThread()); } } private ServletRequestInfo setServletRequestInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { synchronized (_servletRequestInfo) { ServletRequestInfo info = new ServletRequestInfo(request, response); _servletRequestInfo.put(Thread.currentThread(), info); return info; } } private void removeServletRequestInfo() { synchronized (_servletRequestInfo) { _servletRequestInfo.remove(Thread.currentThread()); cleanupThreadLocals(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleServletRequest(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleServletRequest(request, response); } @SuppressWarnings("unchecked") private void handleServletRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { ServletRequestInfo info = setServletRequestInfo(request, response); if (request.getMethod().equals("GET")) { List<String> urlParamNames = Collections.list(request.getParameterNames()); HashMap<String, String> params = new HashMap<String,String>(); for (String paramName : urlParamNames) params.put(paramName, request.getParameter(paramName)); JsonRpcRequestModel json = new JsonRpcRequestModel(); json.jsonrpc = JSONRPC_VERSION; json.id = ""; json.method = params.remove(METHOD); json.params = params; info.currentJsonRequest = json; info.prettyPrinting = true; invokeMethod(json.method, params); } else // post { try { String methodName; Object methodParams; if (info.inputStream.peek() == '[' || info.inputStream.peek() == '{') // json { handleArrayOfJsonRequests(info.inputStream,response); } else // AMF3 { ASObject obj = (ASObject)deserializeAmf3(info.inputStream); methodName = (String) obj.get(METHOD); methodParams = obj.get(PARAMS); info.streamParameterIndex = (Number) obj.get(STREAM_PARAMETER_INDEX); invokeMethod(methodName, methodParams); } } catch (IOException e) { sendError(e, null); } catch (Exception e) { sendError(e, null); } } handleJsonResponses(); } finally { removeServletRequestInfo(); } } public static final String JSONRPC_VERSION = "2.0"; private static final Gson GSON = new GsonBuilder() .registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()) .registerTypeHierarchyAdapter(Double.class, new NaNToNullAdapter()) .disableHtmlEscaping() .create(); private static final Gson GSON_PRETTY = new GsonBuilder() .registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()) .registerTypeHierarchyAdapter(Double.class, new NaNToNullAdapter()) .disableHtmlEscaping() .setPrettyPrinting() .create(); private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> { public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return Base64.decode(json.getAsString()); } public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(Base64.encodeBytes(src, Base64.DONT_BREAK_LINES)); } } private static class NaNToNullAdapter implements JsonSerializer<Double>, JsonDeserializer<Double> { public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return json.isJsonNull() ? Double.NaN : json.getAsDouble(); } public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { return Double.isNaN(src) ? JsonNull.INSTANCE : new JsonPrimitive(src); } } private void handleArrayOfJsonRequests(PeekableInputStream inputStream,HttpServletResponse response) throws IOException { try { JsonRpcRequestModel[] jsonRequests; String streamString = IOUtils.toString(inputStream, "UTF-8"); ServletRequestInfo info = getServletRequestInfo(); /*If first character is { then it is a single request. We add it to the array jsonRequests and continue*/ if (streamString.charAt(0) == '{') { JsonRpcRequestModel req = GSON.fromJson(streamString, JsonRpcRequestModel.class); jsonRequests = new JsonRpcRequestModel[] { req }; info.isBatchRequest = false; } else { jsonRequests = GSON.fromJson(streamString, JsonRpcRequestModel[].class); info.isBatchRequest = true; } /* we loop through each request, get results or check error and add repsonses to an array*/ for (int i = 0; i < jsonRequests.length; i++) { info.currentJsonRequest = jsonRequests[i]; /* Check to see if JSON-RPC protocol is 2.0*/ if (info.currentJsonRequest.jsonrpc == null || !info.currentJsonRequest.jsonrpc.equals(JSONRPC_VERSION)) { sendJsonError(JSON_RPC_PROTOCOL_ERROR_MESSAGE, info.currentJsonRequest.jsonrpc); continue; } /*Check if ID is a number and if so it has not fractional numbers*/ else if (info.currentJsonRequest.id instanceof Number) { Number number = (Number) info.currentJsonRequest.id; if (number.intValue() != number.doubleValue()) { sendJsonError(JSON_RPC_ID_ERROR_MESSAGE, info.currentJsonRequest.id); continue; } info.currentJsonRequest.id = number.intValue(); } /*Check if Method exists*/ if (methodMap.get(info.currentJsonRequest.method) == null) { sendJsonError(JSON_RPC_METHOD_ERROR_MESSAGE, info.currentJsonRequest.method); continue; } invokeMethod(info.currentJsonRequest.method, info.currentJsonRequest.params); } } catch (JsonParseException e) { sendError(e, JSON_RPC_PARSE_ERROR_MESSAGE); } } private void handleJsonResponses() { ServletRequestInfo info = getServletRequestInfo(); if (info.currentJsonRequest == null) return; info.response.setContentType("application/json"); info.response.setCharacterEncoding("UTF-8"); String result; try { // Note: JSON-RPC 2.0 specification says the following: // "If there are no Response objects contained within the Response array as it is to be sent to the client, // the server MUST NOT return an empty Array and should return nothing at all." // However, this means we have to add a special case in our JS code when we send an empty batch request. // It is more convenient if the server returns an empty Array, so we don't follow this part of the specification. Gson gson = info.prettyPrinting ? GSON_PRETTY : GSON; if (info.isBatchRequest) result = gson.toJson(info.jsonResponses); else result = gson.toJson(info.jsonResponses.get(0)); PrintWriter writer = new PrintWriter(info.getOutputStream()); writer.print(result); writer.close(); writer.flush(); } catch (Exception e) { e.printStackTrace(); } } private static String JSON_RPC_PROTOCOL_ERROR_MESSAGE = "JSON-RPC protocol must be 2.0"; private static String JSON_RPC_ID_ERROR_MESSAGE = "ID cannot contain fractional parts"; private static String JSON_RPC_METHOD_ERROR_MESSAGE = "The method does not exist or is not available."; private static String JSON_RPC_PARSE_ERROR_MESSAGE = "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."; private void sendJsonError(String message, Object data) { ServletRequestInfo info = getServletRequestInfo(); Object id = info.currentJsonRequest.id; // If ID is empty then it is a notification and we send nothing back if (id == null) return; JsonRpcResponseModel result = new JsonRpcResponseModel(); result.id = id; result.jsonrpc = "2.0"; result.error = new JsonRpcErrorModel(); result.error.message = message; result.error.data = data; if (message.equals(JSON_RPC_PROTOCOL_ERROR_MESSAGE) || message.equals(JSON_RPC_ID_ERROR_MESSAGE)) { result.error.code = "-32600"; } else if (message.equals(JSON_RPC_METHOD_ERROR_MESSAGE)) { result.error.code = "-32601"; } else if (message.equals(JSON_RPC_PARSE_ERROR_MESSAGE)) { result.error.code = "-32700"; } else { result.error.code = "-32000"; } info.jsonResponses.add(result); } @SuppressWarnings({ "rawtypes", "unchecked" }) private Object[] getParamsFromMap(ExposedMethod exposedMethod, Map params) { String[] argNames = exposedMethod.paramNames; Class[] argTypes = exposedMethod.method.getParameterTypes(); Object[] argValues = new Object[argTypes.length]; Map extraParameters = null; // parameters that weren't mapped directly to method arguments // For each method parameter, get the corresponding url parameter value. if (argNames != null && params != null) { for (Object parameterName : params.keySet()) { Object parameterValue = params.get(parameterName); int index = ListUtils.findString((String)parameterName, argNames); if (index >= 0) { argValues[index] = parameterValue; } else if (!parameterName.equals(METHOD)) { if (extraParameters == null) extraParameters = new HashMap(); extraParameters.put(parameterName, parameterValue); } } } // support for a function having a single Map<String,String> parameter // see if we can find a Map arg. If so, set it to extraParameters if (argTypes != null) { for (int i = 0; i < argTypes.length; i++) { if (argTypes[i] == Map.class && argValues[i] == null) { // avoid passing a null Map to the function if (extraParameters == null) extraParameters = new HashMap<String,String>(); argValues[i] = extraParameters; extraParameters = null; break; } } } if (extraParameters != null) { System.out.println("Received servlet request: " + methodToString(exposedMethod.method.getName(), argValues)); System.out.println("Unused parameters: "+extraParameters.entrySet()); } return argValues; } /** * @param methodName The name of the function to invoke. * @param methodParams A Map, List, or Array of input parameters for the method. Values will be cast to the appropriate types if necessary. */ private void invokeMethod(String methodName, Object methodParams) throws IOException { ServletRequestInfo info = getServletRequestInfo(); // when no method is specified, call getCapabilities() if (methodName == null) { methodName = GET_CAPABILITIES; info.prettyPrinting = true; } ExposedMethod exposedMethod = methodMap.get(methodName); if (exposedMethod == null) { String message = methodName == null ? "No method specified." : String.format("Unknown method: \"%s\"", methodName); sendError(new IllegalArgumentException(message), null); return; } if (methodParams == null) methodParams = new Object[0]; if (methodParams instanceof Map) methodParams = getParamsFromMap(exposedMethod, (Map<?,?>)methodParams); if (methodParams instanceof List<?>) methodParams = ((List<?>)methodParams).toArray(); if (info.streamParameterIndex != null) { int index = info.streamParameterIndex.intValue(); if (index >= 0) ((Object[])methodParams)[index] = info.inputStream; } Object[] params = (Object[])methodParams; // cast input values to appropriate types if necessary Class<?>[] expectedArgTypes = exposedMethod.method.getParameterTypes(); if (expectedArgTypes.length == params.length) { for (int index = 0; index < params.length; index++) { params[index] = cast(params[index], expectedArgTypes[index]); } } // prepare to output the result of the method call long startTime = System.currentTimeMillis(); // Invoke the method on the object with the arguments try { Object result = exposedMethod.method.invoke(exposedMethod.instance, params); if (info.currentJsonRequest == null) // AMF3 { if (exposedMethod.method.getReturnType() != void.class) { ServletOutputStream servletOutputStream = info.getOutputStream(); serializeCompressedAmf3(result, servletOutputStream); } } else // json { Object id = info.currentJsonRequest.id; /* If ID is empty then it is a notification, we send nothing back */ if (id != null) { JsonRpcResponseModel responseObj = new JsonRpcResponseModel(); responseObj.jsonrpc = "2.0"; responseObj.result = result; responseObj.id = id; info.jsonResponses.add(responseObj); } } } catch (InvocationTargetException e) { System.err.println(methodToString(methodName, params)); sendError(e, null); } catch (IllegalArgumentException e) { String moreInfo = "Expected: " + formatFunctionSignature(methodName, expectedArgTypes, exposedMethod.paramNames) + "\n" + "Received: " + formatFunctionSignature(methodName, params, null); sendError(e, moreInfo); } catch (Exception e) { System.err.println(methodToString(methodName, params)); sendError(e, null); } long endTime = System.currentTimeMillis(); // debug if (endTime - startTime >= debugThreshold) System.out.println(String.format("[%sms] %s", endTime - startTime, methodToString(methodName, params))); } /** * Tries to convert value to the given type. * @param value The value to cast to a new type. * @param type The desired type. * @return The value, which may have been cast as the new type. */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object cast(Object value, Type type) throws RemoteException { Class<?> typeClass = null; if (Class.class.isInstance(type)) { typeClass = (Class<?>)type; if (typeClass.isInstance(value)) return value; } else if (ParameterizedType.class.isInstance(type)) typeClass = (Class<?>)((ParameterizedType)type).getRawType(); try { if (value == null) // null -> NaN { if (type == double.class || type == Double.class) value = Double.NaN; else if (type == float.class || type == Float.class) value = Float.NaN; return value; } if (value instanceof Map) // Map -> Java Bean { if (Map.class.isAssignableFrom(typeClass)) { Class<?> keyType = null, valueType = null; try { ParameterizedType pt = null; if (ParameterizedType.class.isAssignableFrom(type.getClass())) pt = (ParameterizedType)type; else pt = (ParameterizedType)typeClass.getGenericSuperclass(); Type[] types = pt.getActualTypeArguments(); keyType = (Class<?>) types[0]; valueType = (Class<?>) types[1]; } catch (Exception e) { // ignore exception if (Map.class.isAssignableFrom(value.getClass())) keyType = valueType = Object.class; } if (keyType != null && valueType != null) { Map newMap = null; try { newMap = (Map<?,?>)typeClass.newInstance(); } catch (Exception e) { newMap = new HashMap(); } for (Entry<?,?> e : ((Map<?,?>)value).entrySet()) newMap.put(cast(e.getKey(), keyType), cast(e.getValue(), valueType)); return newMap; } } if (typeClass.isInstance(value)) return value; Object bean = typeClass.newInstance(); for (Field field : typeClass.getFields()) { Object fieldValue = ((Map<?,?>)value).get(field.getName()); fieldValue = cast(fieldValue, field.getGenericType()); field.set(bean, fieldValue); } return bean; } if (typeClass.isArray()) { if (value instanceof String) // String -> String[] value = CSVParser.defaultParser.parseCSVRow((String)value, true); if (value instanceof List) // List -> Object[] value = ((List<?>)value).toArray(); if (value.getClass().isArray()) // T1[] -> T2[] { int n = Array.getLength(value); Class<?> itemType = typeClass.getComponentType(); Object output = Array.newInstance(itemType, n); while (n Array.set(output, n, cast(Array.get(value, n), itemType)); return output; } } if (Collection.class.isAssignableFrom(typeClass)) // ? -> <? extends Collection> { value = cast(value, Object[].class); // ? -> Object[] if (value.getClass().isArray()) // T1[] -> Vector<T2> { int n = Array.getLength(value); List<Object> output = new Vector<Object>(n); TypeVariable<?>[] itemTypes = typeClass.getTypeParameters(); Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null; while (n { Object item = Array.get(value, n); if (itemType != null) item = cast(item, itemType); // T1 -> T2 output.set(n, item); } return output; } } if (value instanceof String) // String -> ? { String string = (String)value; // String -> primitive if (type == char.class || type == Character.class) return string.charAt(0); if (type == byte.class || type == Byte.class) return Byte.parseByte(string); if (type == long.class || type == Long.class) return Long.parseLong(string); if (type == int.class || type == Integer.class) return Integer.parseInt(string); if (type == short.class || type == Short.class) return Short.parseShort(string); if (type == float.class || type == Float.class) return Float.parseFloat(string); if (type == double.class || type == Double.class) return Double.parseDouble(string); if (type == boolean.class || type == Boolean.class) return string.equalsIgnoreCase("true"); if (type == InputStream.class) // String -> InputStream { try { return new ByteArrayInputStream(string.getBytes("UTF-8")); } catch (Exception e) { return null; } } } if (value instanceof Number) // Number -> primitive { Number number = (Number)value; if (type == byte.class || type == Byte.class) return number.byteValue(); if (type == long.class || type == Long.class) return number.longValue(); if (type == int.class || type == Integer.class) return number.intValue(); if (type == short.class || type == Short.class) return number.shortValue(); if (type == float.class || type == Float.class) return number.floatValue(); if (type == double.class || type == Double.class) return number.doubleValue(); if (type == char.class || type == Character.class) return Character.toChars(number.intValue())[0]; if (type == boolean.class || type == Boolean.class) return !Double.isNaN(number.doubleValue()) && number.intValue() != 0; } } catch (Exception e) { throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(), typeClass.getSimpleName()), e); } // Return original value if not handled above. // Primitives and their Object equivalents will cast automatically. return value; } private static final String GET_CAPABILITIES = "getCapabilities"; /** * Lists available methods. */ public Map<String,Object> getCapabilities() { List<String> methodNames = new Vector<String>(methodMap.keySet()); Collections.sort(methodNames); List<String> methods = new Vector<String>(); List<String> deprecated = new Vector<String>(); for (String methodName : methodNames) { ExposedMethod em = methodMap.get(methodName); String str = String.format( "%s %s", em.method.getReturnType().getSimpleName(), formatFunctionSignature(methodName, em.method.getParameterTypes(), em.paramNames) ); if (em.method.getAnnotation(Deprecated.class) != null) deprecated.add(str); else methods.add(str); } return MapUtils.fromPairs( "class", this.getClass().getCanonicalName(), "methods", methods.toArray(), "deprecated", deprecated.toArray() ); } /** * This function formats a Java function signature as a String. * @param methodName The name of the method. * @param paramValuesOrTypes A list of Class objects or arbitrary Objects to get the class names from. * @param paramNames The names of the parameters, may be null. * @return A readable Java function signature. */ private String formatFunctionSignature(String methodName, Object[] paramValuesOrTypes, String[] paramNames) { // don't use paramNames if the length doesn't match the paramValuesOrTypes length. if (paramNames != null && paramNames.length != paramValuesOrTypes.length) paramNames = null; List<String> names = new Vector<String>(paramValuesOrTypes.length); for (int i = 0; i < paramValuesOrTypes.length; i++) { Object valueOrType = paramValuesOrTypes[i]; String name = "null"; if (valueOrType instanceof Class) name = ((Class<?>)valueOrType).getSimpleName(); else if (valueOrType != null) name = valueOrType.getClass().getSimpleName(); // hide package names if (name.indexOf('.') >= 0) name = name.substring(name.lastIndexOf('.') + 1); if (paramNames != null) name += " " + paramNames[i]; names.add(name); } String result = names.toString(); return String.format("%s(%s)", methodName, result.substring(1, result.length() - 1)); } private void sendError(Throwable exception, String moreInfo) throws IOException { if (exception instanceof InvocationTargetException) exception = exception.getCause(); // log errors exception.printStackTrace(); String message; if (exception instanceof NullPointerException) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); exception.printStackTrace(pw); message = sw.getBuffer().toString(); } else if (exception instanceof RuntimeException) message = exception.toString(); else message = exception.getMessage(); if (message == null) message = "null"; if (moreInfo != null) message += "\n" + moreInfo; System.err.println("Serializing ErrorMessage: "+message); ServletRequestInfo info = getServletRequestInfo(); if (info.currentJsonRequest == null) { ServletOutputStream servletOutputStream = info.getOutputStream(); ErrorMessage errorMessage = new ErrorMessage(new MessageException(message)); errorMessage.faultCode = exception.getClass().getSimpleName(); serializeCompressedAmf3(errorMessage, servletOutputStream); } else { sendJsonError(message, null); } } // Serialize a Java Object to AMF3 ByteArray protected void serializeCompressedAmf3(Object objToSerialize, ServletOutputStream servletOutputStream) { try { DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(servletOutputStream); Amf3Output amf3Output = new Amf3Output(serializationContext); amf3Output.setOutputStream(deflaterOutputStream); // compress amf3Output.writeObject(objToSerialize); amf3Output.flush(); deflaterOutputStream.close(); // this is necessary to finish the compression } catch (Exception e) { e.printStackTrace(); } } // De-serialize a ByteArray/AMF3/Flex object to a Java object protected ASObject deserializeAmf3(InputStream inputStream) throws ClassNotFoundException, IOException { ASObject deSerializedObj = null; Amf3Input amf3Input = new Amf3Input(serializationContext); amf3Input.setInputStream(inputStream); // uncompress deSerializedObj = (ASObject) amf3Input.readObject(); //amf3Input.close(); return deSerializedObj; } protected String methodToString(String name, Object[] params) { String str = name + Arrays.deepToString(params); int max = 1024; if (str.length() > max) str = str.substring(0, max) + "..."; return str; } }
package nl.tud.dcs.fddg.game; import nl.tud.dcs.fddg.game.actions.Action; import nl.tud.dcs.fddg.game.actions.DamageAction; import nl.tud.dcs.fddg.game.actions.DeleteUnitAction; import nl.tud.dcs.fddg.game.entities.Dragon; import nl.tud.dcs.fddg.game.entities.Player; import nl.tud.dcs.fddg.game.entities.Unit; import java.io.File; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class Field implements Serializable { public static final int BOARD_WIDTH = 25, BOARD_HEIGHT = 25; private static final int INITIAL_DRAGONS = 20; private Unit[][] entities; private int[] dx = {0, 1, 0, -1}; private int[] dy = {-1, 0, 1, 0}; private HashSet<Integer> unitIds; private ConcurrentHashMap<Integer, Player> playerMap; private ConcurrentHashMap<Integer, Dragon> dragonMap; private Random random; /** * The constructor of the Field class. * Sets up the field and creates maps to keep track of the players and dragon * in the game. */ public Field(String filename) throws FileNotFoundException { entities = new Unit[BOARD_HEIGHT][BOARD_WIDTH]; unitIds = new HashSet<Integer>(); playerMap = new ConcurrentHashMap<Integer, Player>(); dragonMap = new ConcurrentHashMap<Integer, Dragon>(); random = new Random(System.currentTimeMillis()); // fill the field with dragons // int randX, randY; // for (int i = 0; i < INITIAL_DRAGONS; i++) { // randX = random.nextInt(BOARD_WIDTH); // randY = random.nextInt(BOARD_HEIGHT); // } while (!isFree(randX, randY)); // Dragon d = new Dragon(randX, randY, getUniqueId()); // entities[randY][randX] = d; // dragonMap.put(d.getUnitId(), d); readFromFile(filename); } private void readFromFile(String filename) throws FileNotFoundException { Scanner sc = new Scanner(new File(filename)); for (int y = 0; y < BOARD_HEIGHT; y++) { for (int x = 0; x < BOARD_WIDTH; x++) { String next = sc.next(); if (next.equals("D")) { Dragon dragon = new Dragon(x, y, getUniqueId()); entities[y][x] = dragon; dragonMap.put(dragon.getUnitId(), dragon); } } } } /** * This function checks if a given location is not occupied at the moment. * * @param x The x coordinate of the location. * @param y The y coordinate of the location. * @return Returns a boolean indicating if the location is unoccupied. */ public boolean isFree(int x, int y) { return entities[y][x] == null; } /** * This function generates a new ID to be used. * * @return A unique ID. */ private int getUniqueId() { Random random = new Random(System.currentTimeMillis()); int uniqueId = random.nextInt(Integer.MAX_VALUE); while (unitIds.contains(uniqueId)) { uniqueId = random.nextInt(Integer.MAX_VALUE); } unitIds.add(uniqueId); return uniqueId; } /** * This function places a Player randomly on the field. * * @param playerId The (unique) ID of the player to be placed on the field. */ public void addPlayer(int playerId) { int randX, randY; do { randX = random.nextInt(BOARD_WIDTH); randY = random.nextInt(BOARD_HEIGHT); } while (!isFree(randX, randY)); Player p = new Player(randX, randY, playerId); playerMap.put(playerId, p); entities[randY][randX] = p; } /** * This function places a Player on the field at a specific location. * * @param playerId The (unique) ID of the player to be placed on the field. * @param x The x-coordinate of the player. * @param y The y-coordinate of the player. */ public void addPlayer(int playerId, int x, int y) { Player p = new Player(x, y, playerId); playerMap.put(playerId, p); entities[y][x] = p; } /** * This function checks if a player ID belongs indeed to a player on the field. * * @param playerId The ID of the player to be checked. * @return A boolean indicating if the ID is valid and present on the field. */ public boolean isValidPlayerId(int playerId) { return playerMap.containsKey(playerId); } /** * This function checks if a move action to a new location can be done. * * @param newX The x coordinate of the new location. * @param newY The y coordinate of the new location. * @return A boolean indicating if the move can be done. */ public boolean canMove(int newX, int newY) { return isInBoard(newX, newY) && isFree(newX, newY); } /** * This function moves a player to a new location. * * @param playerId The (unique) ID of the player to be moved. * @param x The x coordinate of the location the player wants to move to. * @param y The y coordinate of the location the player wants to move to. * @return A boolean indicating if a player can move to the location provided. */ public boolean movePlayer(int playerId, int x, int y) { Player p = playerMap.get(playerId); // TODO we forgot something... apparently the player can move anywhere it likes. No distance = 1 check?! if (!canMove(x, y)) { return false; } // move the player entities[p.getyPos()][p.getxPos()] = null; entities[y][x] = p; p.setxPos(x); p.setyPos(y); return true; } /** * Simple getter function that returns the unit (might be null) on a position in the field. * Null means the location is not occupied by a unit. * * @param x The x position on the field. * @param y The y position on the field. * @return A unit (might be null) that occupies this location on the field. */ public Unit getUnit(int x, int y) { return entities[y][x]; } public int manhattanDistance(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } public boolean isInRange(int thisPlayerId, int thatUnitId, int range) { Player thisPlayer = playerMap.get(thisPlayerId); Unit thatUnit; if (playerMap.containsKey(thatUnitId)) { thatUnit = playerMap.get(thatUnitId); } else if (dragonMap.containsKey(thatUnitId)) { thatUnit = dragonMap.get(thatUnitId); } else { return false; } int distance = manhattanDistance(thisPlayer.getxPos(), thisPlayer.getyPos(), thatUnit.getxPos(), thatUnit.getyPos()); return (distance <= range); } /** * This method returns a random player from a set of players that are eligible to heal. * We return a random player from this set to avoid overhealing of one player. * * @param playerId The ID of the player to heal. * @return The player that is in range to heal (can be null). */ public Player isInRangeToHeal(int playerId) { ArrayList<Player> eligible = new ArrayList<Player>(); Iterator<Integer> it = playerMap.keySet().iterator(); while (it.hasNext()) { Integer id = it.next(); Player thatPlayer = playerMap.get(id); if (isInRange(playerId, id, 5) && thatPlayer.getHitPointsPercentage() < 0.5 && thatPlayer.getCurHitPoints() > 0) { eligible.add(thatPlayer); } } if (eligible.size() == 0) { return null; } return eligible.get(new Random().nextInt(eligible.size())); } /** * This method returns a random dragon from a set of dragons that can be attacked. * Null indicates no dragon is in range. * * @param playerId The (unique) ID of the player that wishes to attack a dragon. * @return A dragon that the player can attack (might be null). */ public Dragon dragonIsInRangeToAttack(int playerId) { ArrayList<Dragon> eligible = new ArrayList<Dragon>(); Iterator<Integer> it = dragonMap.keySet().iterator(); while (it.hasNext()) { Integer id = it.next(); Dragon d = dragonMap.get(id); if (isInRange(playerId, id, 1)) { eligible.add(d); } } if (eligible.size() == 0) { return null; } return eligible.get(new Random().nextInt(eligible.size())); } /** * This function returns a player object on the field based on its ID. * * @param playerId The (unique) ID of the player object. * @return The player object that belongs to the ID. */ // TODO Check if map contains? public Player getPlayer(int playerId) { return playerMap.get(playerId); } /** * This function returns a dragon object on the field based on its ID. * * @param dragonId The (unique) ID of the dragon object. * @return The dragon object that belongs to the ID. */ // TODO Check if map contains? public Dragon getDragon(int dragonId) { return dragonMap.get(dragonId); } /** * This function removes a dragon from the field. * Called when it's dead. * * @param dragonId The (unique) ID of the dragon to be deleted. */ public void removeDragon(int dragonId) { Dragon d = dragonMap.get(dragonId); entities[d.getyPos()][d.getxPos()] = null; dragonMap.remove(dragonId); } /** * This function computes the location to go to when heading for the next nearest * dragon on the field based on a start position (the current place of the player). * * @param startX The x coordinate of the start position. * @param startY The y coordinate of the start position. * @return An integer in which the x and y location of the next location are encoded. * The encode is as follows: the x coordinate of the new position + (Math.max(BOARD_HEIGHT, BOARD_WIDTH) + 5) * the y coordinate. * -1 if no next step is possible. */ public int getDirectionToNearestDragon(int startX, int startY) { HashMap<Integer, Integer> stepMap = new HashMap<Integer, Integer>(); final int MAX_WIDTH_HEIGHT = Math.max(BOARD_HEIGHT, BOARD_WIDTH) + 5; int curPos = startX + startY * MAX_WIDTH_HEIGHT; State s = new State(curPos, new ArrayList<Integer>(), 0); Queue<State> queue = new LinkedList<State>(); queue.add(s); stepMap.put(curPos, 0); while (!queue.isEmpty()) { State curState = queue.poll(); ArrayList<Integer> path = curState.passed; int position = curState.curPos; int curX = position % MAX_WIDTH_HEIGHT; int curY = position / MAX_WIDTH_HEIGHT; int curSteps = curState.steps; for (int i = 0; i < dx.length; i++) { int newX = curX + dx[i]; int newY = curY + dy[i]; if (isInBoard(newX, newY) && (entities[newY][newX] instanceof Dragon)) { return path.get(0); } if (canMove(newX, newY)) { int newPos = newX + newY * MAX_WIDTH_HEIGHT; if (!stepMap.containsKey(newPos) || (curSteps + 1) < stepMap.get(newPos)) { // Make a copy (hard copy, no reference) ArrayList<Integer> updatedPath = new ArrayList<Integer>(path); updatedPath.add(newPos); stepMap.put(newPos, curSteps + 1); queue.add(new State(newPos, updatedPath, curSteps + 1)); } } } } // No path possible, return -1 return -1; } /** * Checks whether (x,y) is a valid location in the board * * @param x * @param y * @return */ private boolean isInBoard(int x, int y) { return x >= 0 && x < BOARD_WIDTH && y >= 0 && y < BOARD_HEIGHT; } /** * This function lets all dragon alive on the field attack nearby players (that are connected to this server). */ public Set<Action> dragonRage(Set<Integer> connectedPlayers) { Set<Action> actionSet = new HashSet<Action>(); for (int dragonId : dragonMap.keySet()) { Dragon d = dragonMap.get(dragonId); for (int playerId : playerMap.keySet()) { Player p = playerMap.get(playerId); if(isInRange(playerId, dragonId, 2)) { p.setCurHitPoints(p.getCurHitPoints() - d.getAttackPower()); if (p.getCurHitPoints() <= 0) { DeleteUnitAction dua = new DeleteUnitAction(p.getUnitId()); actionSet.add(dua); removePlayer(p.getUnitId()); } DamageAction da = new DamageAction(p.getUnitId(), d.getAttackPower()); actionSet.add(da); } } } return actionSet; } public void removePlayer(int playerId) { Player p = getPlayer(playerId); entities[p.getyPos()][p.getxPos()] = null; } /** * This function checks if the game has been finished yet. * * @return A boolean indicating if the game has finished. */ public boolean gameHasFinished() { if (dragonMap.size() == 0) { return true; } for (int playerId : playerMap.keySet()) { if (playerMap.get(playerId).getCurHitPoints() > 0) { return false; } } return true; } } /** * An inner class representing a state in the Breadth-first Search algorithm to determine the next location to go to in the {@link Field#getDirectionToNearestDragon(int, int)} function. */ class State { int curPos, steps; ArrayList<Integer> passed; public State(int i, ArrayList<Integer> set, int steps) { this.curPos = i; this.passed = set; this.steps = steps; } }
package org.oscm.app.aws.controller; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import org.oscm.app.aws.data.FlowState; import org.oscm.app.aws.data.Operation; import org.oscm.app.aws.i18n.Messages; import org.oscm.app.common.controller.LogAndExceptionConverter; import org.oscm.app.common.data.Context; import org.oscm.app.v1_0.data.ControllerSettings; import org.oscm.app.v1_0.data.InstanceDescription; import org.oscm.app.v1_0.data.InstanceStatus; import org.oscm.app.v1_0.data.InstanceStatusUsers; import org.oscm.app.v1_0.data.LocalizedText; import org.oscm.app.v1_0.data.OperationParameter; import org.oscm.app.v1_0.data.ProvisioningSettings; import org.oscm.app.v1_0.data.ServiceUser; import org.oscm.app.v1_0.exceptions.APPlatformException; import org.oscm.app.v1_0.intf.APPlatformController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AWS implementation of a service controller based on the Asynchronous * Provisioning Platform (APP). */ @Stateless(mappedName = "bss/app/controller/" + AWSController.ID) @Remote(APPlatformController.class) public class AWSController implements APPlatformController { public static final String ID = "ess.aws"; private static final Logger LOGGER = LoggerFactory .getLogger(AWSController.class); /** * Starts the creation of an application instance and returns the instance * ID. * <p> * The internal status <code>CREATION_REQUESTED</code> is stored as a * controller configuration setting. It is evaluated and handled by the * status dispatcher, which is invoked at regular intervals by APP through * the <code>getInstanceStatus</code> method. * * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @return an <code>InstanceDescription</code> instance describing the * application instance * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceDescription createInstance(ProvisioningSettings settings) throws APPlatformException { try { PropertyHandler ph = PropertyHandler.withSettings(settings); validateParameters(ph); ph.setOperation(Operation.EC2_CREATION); ph.setState(FlowState.CREATION_REQUESTED); // Return generated instance information InstanceDescription id = new InstanceDescription(); id.setInstanceId("aws-" + UUID.randomUUID().toString()); id.setChangedParameters(settings.getParameters()); LOGGER.info("createInstance({})", LogAndExceptionConverter .getLogText(id.getInstanceId(), settings)); return id; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.CREATION); } } /** * Starts the deletion of an application instance. * <p> * The internal status <code>DELETION_REQUESTED</code> is stored as a * controller configuration setting. It is evaluated and handled by the * status dispatcher, which is invoked at regular intervals by APP through * the <code>getInstanceStatus</code> method. * * @param instanceId * the ID of the application instance to be deleted * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @return an <code>InstanceStatus</code> instance with the overall status * of the application instance * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus deleteInstance(String instanceId, ProvisioningSettings settings) throws APPlatformException { LOGGER.info("deleteInstance({})", LogAndExceptionConverter.getLogText(instanceId, settings)); try { PropertyHandler ph = PropertyHandler.withSettings(settings); ph.setOperation(Operation.EC2_DELETION); ph.setState(FlowState.DELETION_REQUESTED); InstanceStatus result = new InstanceStatus(); result.setChangedParameters(settings.getParameters()); return result; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.DELETION); } } /** * Starts the modification of an application instance. * <p> * The internal status <code>MODIFICATION_REQUESTED</code> is stored as a * controller configuration setting. It is evaluated and handled by the * status dispatcher, which is invoked at regular intervals by APP through * the <code>getInstanceStatus</code> method. * * @param instanceId * the ID of the application instance to be modified * @param currentSettings * a <code>ProvisioningSettings</code> object specifying the * current service parameters and configuration settings * @param newSettings * a <code>ProvisioningSettings</code> object specifying the * modified service parameters and configuration settings * @return an <code>InstanceStatus</code> instance with the overall status * of the application instance * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus modifyInstance(String instanceId, ProvisioningSettings currentSettings, ProvisioningSettings newSettings) throws APPlatformException { LOGGER.info("modifyInstance({})", LogAndExceptionConverter .getLogText(instanceId, currentSettings)); try { PropertyHandler ph = PropertyHandler.withSettings(newSettings); ph.setOperation(Operation.EC2_MODIFICATION); ph.setState(FlowState.MODIFICATION_REQUESTED); InstanceStatus result = new InstanceStatus(); result.setChangedParameters(newSettings.getParameters()); return result; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.MODIFICATION); } } /** * Returns the current overall status of the application instance. * <p> * For retrieving the status, the method calls the status dispatcher with * the currently stored controller configuration settings. These settings * include the internal status set by the controller or the dispatcher * itself. The overall status of the instance depends on this internal * status. * * @param instanceId * the ID of the application instance to be checked * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @return an <code>InstanceStatus</code> instance with the overall status * of the application instance * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus getInstanceStatus(String instanceId, ProvisioningSettings settings) throws APPlatformException { LOGGER.debug("getInstanceStatus({})", LogAndExceptionConverter.getLogText(instanceId, settings)); try { PropertyHandler ph = PropertyHandler.withSettings(settings); EC2Processor ec2processor = new EC2Processor(ph, instanceId); InstanceStatus status = ec2processor.process(); return status; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.STATUS); } } /** * Does not carry out specific actions in this implementation and always * returns <code>null</code>. * * @param instanceId * the ID of the application instance * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @param properties * the events as properties consisting of a key and a value each * @return <code>null</code> * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus notifyInstance(String instanceId, ProvisioningSettings settings, Properties properties) throws APPlatformException { LOGGER.info("notifyInstance({})", LogAndExceptionConverter.getLogText(instanceId, settings)); InstanceStatus status = null; if (instanceId == null || settings == null || properties == null) { return status; } PropertyHandler propertyHandler = new PropertyHandler(settings); if ("finish".equals(properties.get("command"))) { if (FlowState.MANUAL.equals(propertyHandler.getState())) { propertyHandler.setState(FlowState.FINISHED); status = setNotificationStatus(settings, propertyHandler); LOGGER.debug( "Got finish event => changing instance status to finished"); } else { APPlatformException pe = new APPlatformException( "Got finish event but instance is in state " + propertyHandler.getState() + " => nothing changed"); LOGGER.debug(pe.getMessage()); throw pe; } } return status; } /** * Starts the activation of an application instance. * <p> * The internal status <code>ACTIVATION_REQUESTED</code> is stored as a * controller configuration setting. It is evaluated and handled by the * status dispatcher, which is invoked at regular intervals by APP through * the <code>getInstanceStatus</code> method. * * @param instanceId * the ID of the application instance to be activated * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @return an <code>InstanceStatus</code> instance with the overall status * of the application instance * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus activateInstance(String instanceId, ProvisioningSettings settings) throws APPlatformException { LOGGER.info("activateInstance({})", LogAndExceptionConverter.getLogText(instanceId, settings)); try { // Set status to store for application instance PropertyHandler ph = PropertyHandler.withSettings(settings); ph.setOperation(Operation.EC2_ACTIVATION); ph.setState(FlowState.ACTIVATION_REQUESTED); InstanceStatus result = new InstanceStatus(); result.setChangedParameters(settings.getParameters()); return result; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.ACTIVATION); } } /** * Starts the deactivation of an application instance. * <p> * The internal status <code>DEACTIVATION_REQUESTED</code> is stored as a * controller configuration setting. It is evaluated and handled by the * status dispatcher, which is invoked at regular intervals by APP through * the <code>getInstanceStatus</code> method. * * @param instanceId * the ID of the application instance to be activated * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @return an <code>InstanceStatus</code> instance with the overall status * of the application instance * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus deactivateInstance(String instanceId, ProvisioningSettings settings) throws APPlatformException { LOGGER.info("deactivateInstance({})", LogAndExceptionConverter.getLogText(instanceId, settings)); try { // Set status to store for application instance PropertyHandler ph = PropertyHandler.withSettings(settings); ph.setOperation(Operation.EC2_ACTIVATION); ph.setState(FlowState.DEACTIVATION_REQUESTED); InstanceStatus result = new InstanceStatus(); result.setChangedParameters(settings.getParameters()); return result; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.DEACTIVATION); } } /** * Does not carry out specific actions in this implementation and always * returns <code>null</code>. * * @param instanceId * the ID of the application instance * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @param users * a list of users * @return <code>null</code> * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatusUsers createUsers(String instanceId, ProvisioningSettings settings, List<ServiceUser> users) throws APPlatformException { return null; } /** * Does not carry out specific actions in this implementation and always * returns <code>null</code>. * * @param instanceId * the ID of the application instance * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @param users * a list of users * @return <code>null</code> * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus deleteUsers(String instanceId, ProvisioningSettings settings, List<ServiceUser> users) throws APPlatformException { return null; } /** * Does not carry out specific actions in this implementation and always * returns <code>null</code>. * * @param instanceId * the ID of the application instance * @param settings * a <code>ProvisioningSettings</code> object specifying the * service parameters and configuration settings * @param users * a list of users * @return <code>null</code> * @throws APPlatformException */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus updateUsers(String instanceId, ProvisioningSettings settings, List<ServiceUser> users) throws APPlatformException { return null; } @Override public InstanceStatus executeServiceOperation(String userId, String instanceId, String transactionId, String operationId, List<OperationParameter> parameters, ProvisioningSettings settings) throws APPlatformException { LOGGER.info("executeServiceOperation(" + LogAndExceptionConverter.getLogText(instanceId, settings) + " | OperationIdID: {})", operationId); InstanceStatus status = null; if (instanceId == null || operationId == null || settings == null) { return status; } try { PropertyHandler ph = PropertyHandler.withSettings(settings); boolean operationAccepted = false; if ("START_VIRTUAL_SYSTEM".equals(operationId)) { ph.setState(FlowState.START_REQUESTED); ph.setOperation(Operation.EC2_OPERATION); operationAccepted = true; } else if ("STOP_VIRTUAL_SYSTEM".equals(operationId)) { ph.setState(FlowState.STOP_REQUESTED); ph.setOperation(Operation.EC2_OPERATION); operationAccepted = true; } if (operationAccepted) { // when a valid operation has been requested, let the timer // handle the instance afterwards status = new InstanceStatus(); status.setRunWithTimer(true); status.setIsReady(false); status.setChangedParameters(settings.getParameters()); } return status; } catch (Throwable t) { throw LogAndExceptionConverter.createAndLogPlatformException(t, Context.OPERATION); } } @Override public List<LocalizedText> getControllerStatus(ControllerSettings settings) throws APPlatformException { return null; // not yet implemented } @Override public List<OperationParameter> getOperationParameters(String userId, String instanceId, String operationId, ProvisioningSettings settings) throws APPlatformException { return null; // not applicable } @Override public void setControllerSettings(ControllerSettings settings) { // not applicable } private void validateParameters(PropertyHandler ph) throws APPlatformException { String instanceName = ph.getInstanceName(); if (isNullOrEmpty(instanceName)) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_name")); throw new APPlatformException( Messages.getAll("error_missing_name")); } String regex = ph.getInstanceNamePattern(); if (!isNullOrEmpty(regex)) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(instanceName); if (!m.matches()) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_name", new Object[] { instanceName })); throw new APPlatformException(Messages.getAll( "error_invalid_name", new Object[] { instanceName })); } } if (isNullOrEmpty(ph.getKeyPairName())) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_keypair")); throw new APPlatformException( Messages.getAll("error_missing_keypair")); } if (isNullOrEmpty(ph.getImageName())) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_imagename")); throw new APPlatformException( Messages.getAll("error_missing_imagename")); } if (isNullOrEmpty(ph.getInstanceType())) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_instancetype")); throw new APPlatformException( Messages.getAll("error_missing_instancetype")); } if (isNullOrEmpty(ph.getDiskSize())) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_instance_disk_size")); throw new APPlatformException( Messages.getAll("error_missing_instance_disk_size")); } if (isNullOrEmpty(ph.getSubnet())) { LOGGER.error(Messages.get(Messages.DEFAULT_LOCALE, "error_missing_instance_subnet")); throw new APPlatformException( Messages.getAll("error_missing_instance_subnet")); } } private boolean isNullOrEmpty(String value) { return value == null || value.trim().length() == 0; } private InstanceStatus setNotificationStatus(ProvisioningSettings settings, PropertyHandler propertyHandler) { InstanceStatus status; status = new InstanceStatus(); status.setIsReady(true); status.setRunWithTimer(true); status.setDescription(getProvisioningStatusText(propertyHandler)); status.setChangedParameters(settings.getParameters()); return status; } /** * Returns a small status text for the current provisioning step. * * @param paramHandler * property handler containing the current status * @return short status text describing the current status */ private List<LocalizedText> getProvisioningStatusText( PropertyHandler paramHandler) { List<LocalizedText> messages = Messages .getAll("status_" + paramHandler.getState()); for (LocalizedText message : messages) { if (message.getText() == null || (message.getText().startsWith("!") && message.getText().endsWith("!"))) { message.setText(Messages.get(message.getLocale(), "status_INSTANCE_OVERALL")); } } return messages; } }
package com.gurkensalat.osm.entity; import org.springframework.data.jpa.domain.AbstractPersistable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Table; import javax.persistence.Version; @Entity @Table(name = "OSM_PLACES") public class Place extends AbstractPersistable<Long> { @Version @Column(name = "VERSION") private Integer version; @Column(name = "TYPE", length = 20) @Enumerated(EnumType.STRING) private PlaceType type; @Column(name = "LAT") private double lat; @Column(name = "LON") private double lon; @Column(name = "NAME", length = 80) private String name; private Address address; protected Place() { } public Place(String name, PlaceType type) { this.name = name; this.type = type; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public PlaceType getType() { return type; } public void setType(PlaceType type) { this.type = type; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } }
package servlets; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; public class LastPage { static FrameClass frame1; static int Height; static int Width; static highScore HIscore; static BufferedImage background; int score; public class Action { } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { LastPage.frame1.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public LastPage() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame1 = new FrameClass(); Height = frame1.getHeight(); Width = frame1.getWidth(); frame1.getContentPane().setForeground(new Color(0, 0, 205)); frame1.getContentPane().setFont(new Font("Lucida Grande", Font.BOLD, 50)); frame1.getContentPane().setBackground(Color.CYAN); // frame.setBackground(Color.CYAN); frame1.getContentPane().setLayout(null); try { background = ImageIO.read(new File("InjuredBird.png")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // High Score String HIscore = ""; try { HIscore = highScore.updateHiScore(0).toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } JLabel txtHighScore = new JLabel(); txtHighScore.setText("High Score: " + HIscore); txtHighScore.setForeground(Color.MAGENTA); txtHighScore.setFont(new Font("Comic Sans MS", Font.BOLD, 36)); txtHighScore.setBounds(Width / 2 - 150, Height / 2 - 200, 380, 50); frame1.getContentPane().add(txtHighScore); score = Activity.getFinalScore(); JLabel txtYourScore = new JLabel(); txtYourScore.setFont(new Font("Comic Sans MS", Font.BOLD, 36)); txtYourScore.setText("Your Score: " +score); txtYourScore.setForeground(Color.YELLOW); txtYourScore.setForeground(new Color(0, 0, 128)); txtYourScore.setBounds(Width / 2 - 150, Height / 2 - 100, 380, 50); frame1.getContentPane().add(txtYourScore); // txtYourScore.setColumns(10); JButton btnNewButton = new JButton("REPLAY"); btnNewButton.setForeground(Color.BLUE); btnNewButton.setFont(new Font("Comic Sans MS", Font.BOLD, 24)); btnNewButton.setBounds(Width / 2 - 60, Height / 2 - 60, 120, 50); frame1.getContentPane().add(btnNewButton); btnNewButton.addActionListener(new CustomActionListener()); JButton btnNewButton_1 = new JButton("EXIT"); btnNewButton_1.setForeground(Color.BLUE); btnNewButton_1.setFont(new Font("Comic Sans MS", Font.BOLD, 24)); btnNewButton_1.setBounds(Width / 2 - 60, Height / 2 + 130, 120, 50); frame1.getContentPane().add(btnNewButton_1); // frame1.setResizable(false); btnNewButton_1.addActionListener(new EndButtonAction()); JLabel imagelabel = new JLabel(new ImageIcon(background)); imagelabel.setBounds(Width / 2 - 250, Height / 2 - 250, 500, 500); frame1.getContentPane().add(imagelabel); } class CustomActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO Start here frame1.setVisible(false); // System.out.println("hello"); // new Activity(); Activity a = new Activity(); a.ConnectActivity(); } } class EndButtonAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO exit here System.exit(0); } } public void ConnectLastpage() { LastPage.frame1.setVisible(true); } }
package org.postgresql.util; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.CharArrayReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.nio.charset.MalformedInputException; import java.util.Arrays; public class ReaderInputStreamTest { // 132878 = U+2070E - chosen because it is the first supplementary character // in the International Ideographic Core (IICore) // Character.highSurrogate(132878) = 0xd841 static final private char LEADING_SURROGATE = 0xd841; // Character.lowSurrogate(132878) = 0xdf0e static final private char TRAILING_SURROGATE = 0xdf0e; @Test(expected = IllegalArgumentException.class) public void NullReaderTest() { new ReaderInputStream(null); } @Test(expected = IllegalArgumentException.class) public void cbufTooSmallReaderTest() { new ReaderInputStream(new StringReader("abc"), 1); } static private void read(InputStream is, int... expected) throws IOException { byte[] actual = new byte[4]; Arrays.fill(actual, (byte) 0x00); int nActual = is.read(actual); int[] actualInts = new int[4]; for (int i = 0; i < actual.length; i++) { actualInts[i] = actual[i] & 0xff; } if (expected.length > 0) { // Ensure "expected" has 4 bytes expected = Arrays.copyOf(expected, 4); assertEquals(Arrays.toString(expected), Arrays.toString(actualInts)); } else { assertEquals("should be end-of-stream", -1, nActual); is.close(); } } @Test public void SimpleTest() throws IOException { char[] chars = new char[]{'a', 'b', 'c'}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader); read(is, 0x61, 0x62, 0x63); read(is); } @Test public void inputSmallerThanCbufsizeTest() throws IOException { char[] chars = new char[]{'a'}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader, 2); read(is, 0x61); read(is); } @Test public void tooManyReadsTest() throws IOException { char[] chars = new char[]{'a'}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader, 2); read(is, 0x61); assertEquals("should be end-of-stream", -1, is.read()); assertEquals("should be end-of-stream", -1, is.read()); assertEquals("should be end-of-stream", -1, is.read()); is.close(); } @Test public void surrogatePairSpansCharBufBoundaryTest() throws IOException { char[] chars = new char[]{'a', LEADING_SURROGATE, TRAILING_SURROGATE}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader, 2); read(is, 0x61, 0xF0, 0xA0, 0x9C); read(is, 0x8E); read(is); } @Test(expected = MalformedInputException.class) public void invalidInputTest() throws IOException { char[] chars = new char[]{'a', LEADING_SURROGATE, LEADING_SURROGATE}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader, 2); read(is); } @Test(expected = MalformedInputException.class) public void unmatchedLeadingSurrogateInputTest() throws IOException { char[] chars = new char[]{LEADING_SURROGATE}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader, 2); read(is, 0x00); } @Test(expected = MalformedInputException.class) public void unmatchedTrailingSurrogateInputTest() throws IOException { char[] chars = new char[]{TRAILING_SURROGATE}; Reader reader = new CharArrayReader(chars); InputStream is = new ReaderInputStream(reader, 2); read(is); } @Test(expected = NullPointerException.class) public void nullArrayReadTest() throws IOException { Reader reader = new StringReader("abc"); InputStream is = new ReaderInputStream(reader); is.read(null, 0, 4); } @Test(expected = IndexOutOfBoundsException.class) public void invalidOffsetArrayReadTest() throws IOException { Reader reader = new StringReader("abc"); InputStream is = new ReaderInputStream(reader); byte[] bytes = new byte[4]; is.read(bytes, 5, 4); } @Test(expected = IndexOutOfBoundsException.class) public void negativeOffsetArrayReadTest() throws IOException { Reader reader = new StringReader("abc"); InputStream is = new ReaderInputStream(reader); byte[] bytes = new byte[4]; is.read(bytes, -1, 4); } @Test(expected = IndexOutOfBoundsException.class) public void invalidLengthArrayReadTest() throws IOException { Reader reader = new StringReader("abc"); InputStream is = new ReaderInputStream(reader); byte[] bytes = new byte[4]; is.read(bytes, 1, 4); } @Test(expected = IndexOutOfBoundsException.class) public void negativeLengthArrayReadTest() throws IOException { Reader reader = new StringReader("abc"); InputStream is = new ReaderInputStream(reader); byte[] bytes = new byte[4]; is.read(bytes, 1, -2); } @Test public void zeroLengthArrayReadTest() throws IOException { Reader reader = new StringReader("abc"); InputStream is = new ReaderInputStream(reader); byte[] bytes = new byte[4]; assertEquals("requested 0 byte read", 0, is.read(bytes, 1, 0)); } @Test public void singleCharArrayReadTest() throws IOException { Reader reader = new SingleCharPerReadReader(LEADING_SURROGATE, TRAILING_SURROGATE); InputStream is = new ReaderInputStream(reader); read(is, 0xF0, 0xA0, 0x9C, 0x8E); read(is); } @Test(expected = MalformedInputException.class) public void malformedSingleCharArrayReadTest() throws IOException { Reader reader = new SingleCharPerReadReader(LEADING_SURROGATE, LEADING_SURROGATE); InputStream is = new ReaderInputStream(reader); read(is, 0xF0, 0xA0, 0x9C, 0x8E); } @Test public void readsSmallerThanBlockSizeTest() throws Exception { final int BLOCK = 8 * 1024; final int DATASIZE = BLOCK * 5 + 57; final byte[] data = new byte[DATASIZE]; final byte[] buffer = new byte[BLOCK]; InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(data)); ReaderInputStream r = new ReaderInputStream(isr); int read; int total = 0; while ((read = r.read(buffer, 0, BLOCK)) > -1) { total += read; } assertEquals("Data not read completely: missing " + (DATASIZE - total) + " bytes", total, DATASIZE); } private static class SingleCharPerReadReader extends Reader { private final char[] data; private int i; private SingleCharPerReadReader(char... data) { this.data = data; } @Override public int read(char[] cbuf, int off, int len) throws IOException { if (i < data.length) { cbuf[off] = data[i++]; return 1; } return -1; } @Override public void close() throws IOException { } } }
package com.rhomobile.rhodes; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.Calendar; import java.util.Enumeration; import java.util.Locale; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.Vector; import com.rhomobile.rhodes.alert.Alert; import com.rhomobile.rhodes.event.EventStore; import com.rhomobile.rhodes.file.RhoFileApi; import com.rhomobile.rhodes.geolocation.GeoLocation; import com.rhomobile.rhodes.mainview.MainView; import com.rhomobile.rhodes.ui.AboutDialog; import com.rhomobile.rhodes.ui.LogOptionsDialog; import com.rhomobile.rhodes.ui.LogViewDialog; import com.rhomobile.rhodes.uri.ExternalHttpHandler; import com.rhomobile.rhodes.uri.MailUriHandler; import com.rhomobile.rhodes.uri.SmsUriHandler; import com.rhomobile.rhodes.uri.TelUriHandler; import com.rhomobile.rhodes.uri.UriHandler; import com.rhomobile.rhodes.uri.VideoUriHandler; import com.rhomobile.rhodes.util.PerformOnUiThread; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.WindowManager; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.RemoteViews; public class RhodesService extends Service { private static final String TAG = RhodesService.class.getSimpleName(); private static final boolean DEBUG = false; public static final String INTENT_EXTRA_PREFIX = "com.rhomobile.rhodes."; public static final String INTENT_SOURCE = INTENT_EXTRA_PREFIX + ".intent.source"; public static int WINDOW_FLAGS = WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; public static int WINDOW_MASK = WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; private static final int DOWNLOAD_PACKAGE_ID = 1; private static final String ACTION_ASK_CANCEL_DOWNLOAD = "com.rhomobile.rhodes.DownloadManager.ACTION_ASK_CANCEL_DOWNLOAD"; private static final String ACTION_CANCEL_DOWNLOAD = "com.rhomobile.rhodes.DownloadManager.ACTION_CANCEL_DOWNLOAD"; private static RhodesService sInstance; private final IBinder mBinder = new LocalBinder(); @SuppressWarnings("rawtypes") private static final Class[] mStartForegroundSignature = new Class[] {int.class, Notification.class}; @SuppressWarnings("rawtypes") private static final Class[] mStopForegroundSignature = new Class[] {boolean.class}; @SuppressWarnings("rawtypes") private static final Class[] mSetForegroundSignature = new Class[] {boolean.class}; private Method mStartForeground; private Method mStopForeground; private Method mSetForeground; private NotificationManager mNM; //private MainView mMainView; private static int mScreenWidth; private static int mScreenHeight; private static int mScreenOrientation; private static float mScreenPpiX; private static float mScreenPpiY; private static boolean mCameraAvailable; private static int sActivitiesActive; private static int mGeoLocationInactivityTimeout; public static int getGeoLocationInactivityTimeout() { return mGeoLocationInactivityTimeout; } private RhoLogConf m_rhoLogConf = new RhoLogConf(); public RhoLogConf getLogConf() { return m_rhoLogConf; } private boolean mNeedGeoLocationRestart = false; static PowerManager.WakeLock wakeLockObject = null; static boolean wakeLockEnabled = false; private Vector<UriHandler> mUriHandlers = new Vector<UriHandler>(); public boolean handleUrlLoading(String url) { Enumeration<UriHandler> e = mUriHandlers.elements(); while (e.hasMoreElements()) { UriHandler handler = e.nextElement(); try { if (handler.handle(url)) return true; } catch (Exception ex) { Logger.E(TAG, ex.getMessage()); continue; } } return false; } private native void initClassLoader(ClassLoader c); private native void createRhodesApp(); private native void startRhodesApp(); public native void doSyncAllSources(boolean v); public native void doSyncSource(String source); public native String normalizeUrl(String url); public native void doRequest(String url); public static native void loadUrl(String url); public static native void navigateBack(); private String mRootPath; private native void nativeInitPath(String rootPath, String sqliteJournalsPath, String apkPath); public static native void onScreenOrientationChanged(int width, int height, int angle); public native void callUiCreatedCallback(); public native void callUiDestroyedCallback(); public native void callActivationCallback(boolean active); public static native String getBuildConfig(String key); public static native boolean isOnStartPage(); public static native boolean canStartApp(String strCmdLine, String strSeparators); public static RhodesService getInstance() { return sInstance; } private void initRootPath() { ApplicationInfo appInfo = getAppInfo(); String dataDir = appInfo.dataDir; mRootPath = dataDir + "/rhodata/"; Log.d(TAG, "Root path: " + mRootPath); String sqliteJournalsPath = dataDir + "/sqlite_stmt_journals/"; Log.d(TAG, "Sqlite journals path: " + sqliteJournalsPath); File f = new File(mRootPath); f.mkdirs(); f = new File(f, "db/db-files"); f.mkdirs(); f = new File(sqliteJournalsPath); f.mkdirs(); String apkPath = appInfo.sourceDir; nativeInitPath(mRootPath, sqliteJournalsPath, apkPath); } public String getRootPath() { return mRootPath; } private ApplicationInfo getAppInfo() { Context context = this; String pkgName = context.getPackageName(); try { ApplicationInfo info = context.getPackageManager().getApplicationInfo(pkgName, 0); return info; } catch (NameNotFoundException e) { throw new RuntimeException("Internal error: package " + pkgName + " not found: " + e.getMessage()); } } public class LocalBinder extends Binder { RhodesService getService() { return RhodesService.this; } }; @Override public IBinder onBind(Intent intent) { if (DEBUG) Log.d(TAG, "+++ onBind"); return mBinder; } @Override public void onCreate() { if (DEBUG) Log.d(TAG, "+++ onCreate"); sInstance = this; Context context = this; mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); initClassLoader(context.getClassLoader()); try { initRootPath(); RhoFileApi.init(); } catch (IOException e) { Log.e(TAG, e.getMessage()); exit(); return; } if (Utils.isAppHashChanged()) { try { Log.i(TAG, "Application hash was changed, so remove files"); Utils.deleteChildrenIgnoreFirstLevel(new File(getRootPath(), "apps"), "rhoconfig.txt"); Utils.deleteRecursively(new File(getRootPath(), "lib")); /* String[] folders = {"apps", "lib"}; for (String folder : folders) { File f = new File(getRootPath(), folder); if (!f.exists()) continue; Utils.deleteRecursively(f); }*/ initRootPath(); RhoFileApi.init(); RhoFileApi.copy("hash"); } catch (IOException e) { Log.e(TAG, e.getMessage()); exit(); return; } } createRhodesApp(); RhodesActivity ra = RhodesActivity.getInstance(); SplashScreen splashScreen = ra.getSplashScreen(); splashScreen.start(); initForegroundServiceApi(); setFullscreenParameters(); Logger.I("Rhodes", "Loading..."); // Increase WebView rendering priority WebView w = new WebView(context); WebSettings webSettings = w.getSettings(); webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); // Get screen width/height WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); Display d = wm.getDefaultDisplay(); mScreenHeight = d.getHeight(); mScreenWidth = d.getWidth(); mScreenOrientation = d.getOrientation(); DisplayMetrics metrics = new DisplayMetrics(); d.getMetrics(metrics); mScreenPpiX = metrics.xdpi; mScreenPpiY = metrics.ydpi; // TODO: detect camera availability mCameraAvailable = true; mGeoLocationInactivityTimeout = RhoConf.getInt("geo_location_inactivity_timeout"); if (mGeoLocationInactivityTimeout == 0) mGeoLocationInactivityTimeout = 25*1000; // 25s // Register custom uri handlers here mUriHandlers.addElement(new ExternalHttpHandler(context)); mUriHandlers.addElement(new MailUriHandler(context)); mUriHandlers.addElement(new TelUriHandler(context)); mUriHandlers.addElement(new SmsUriHandler(context)); mUriHandlers.addElement(new VideoUriHandler(context)); getRhodesApplication().addOnExitHandler(new Runnable() { public void run() { PerformOnUiThread.exec( new Runnable() { public void run() { if (wakeLockObject != null) { wakeLockObject.release(); wakeLockObject = null; wakeLockEnabled = false; } } }, false); } }); try { if (Capabilities.PUSH_ENABLED) { PushService.register(); getRhodesApplication().addOnExitHandler(new Runnable() { public void run() { try { PushService.unregister(); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage()); } } }); } } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage()); exit(); return; } startRhodesApp(); if (sActivitiesActive > 0) handleAppActivation(); } private void setFullscreenParameters() { boolean fullScreen = true; if (RhoConf.isExist("full_screen")) fullScreen = RhoConf.getBool("full_screen"); if (fullScreen) { WINDOW_FLAGS = WindowManager.LayoutParams.FLAG_FULLSCREEN; WINDOW_MASK = WindowManager.LayoutParams.FLAG_FULLSCREEN; RhodesActivity.setFullscreen(1); } else { WINDOW_FLAGS = WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; WINDOW_MASK = WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN; RhodesActivity.setFullscreen(0); } //Utils.platformLog(TAG, "rhoconfig full_screen = "+String.valueOf(fullScreen)+" "); } private void initForegroundServiceApi() { try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); mSetForeground = getClass().getMethod("setForeground", mSetForegroundSignature); } catch (NoSuchMethodException e) { mStartForeground = null; mStopForeground = null; mSetForeground = null; } } @Override public void onDestroy() { if (DEBUG) Log.d(TAG, "+++ onDestroy"); sInstance = null; getRhodesApplication().exit(); } @Override public void onStart(Intent intent, int startId) { if (DEBUG) Log.d(TAG, "+++ onStart"); try { handleCommand(intent); } catch (Exception e) { Logger.E(TAG, "Can't handle service command: " + e.getMessage()); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (DEBUG) Log.d(TAG, "+++ onStartCommand"); try { handleCommand(intent); } catch (Exception e) { Logger.E(TAG, "Can't handle service command: " + e.getMessage()); } return Service.START_STICKY; } private void handleCommand(Intent intent) { String source = intent.getStringExtra(INTENT_SOURCE); if (source == null) throw new IllegalArgumentException("Service command received from empty source"); Logger.D(TAG, "Service command received from " + source); if (source.equals(PushReceiver.INTENT_SOURCE)) { int type = intent.getIntExtra(PushReceiver.INTENT_TYPE, PushReceiver.INTENT_TYPE_UNKNOWN); switch (type) { case PushReceiver.INTENT_TYPE_REGISTRATION_ID: String id = intent.getStringExtra(PushReceiver.INTENT_REGISTRATION_ID); if (id == null) throw new IllegalArgumentException("Empty registration id received in service command"); setPushRegistrationId(id); break; case PushReceiver.INTENT_TYPE_MESSAGE: Bundle extras = intent.getBundleExtra(PushReceiver.INTENT_EXTRAS); handlePushMessage(extras); break; default: Logger.W(TAG, "Unknown command type received from " + source + ": " + type); } } } public void startServiceForeground(int id, Notification notification) { if (mStartForeground != null) { try { mStartForeground.invoke(this, new Object[] {Integer.valueOf(id), notification}); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to invoke startForeground", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to invoke startForeground", e); } return; } if (mSetForeground != null) { try { mSetForeground.invoke(this, new Object[] {Boolean.valueOf(true)}); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to invoke setForeground", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to invoke setForeground", e); } } mNM.notify(id, notification); } public void stopServiceForeground(int id) { if (mStopForeground != null) { try { mStopForeground.invoke(this, new Object[] {Integer.valueOf(id)}); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to invoke stopForeground", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to invoke stopForeground", e); } return; } mNM.cancel(id); if (mSetForeground != null) { try { mSetForeground.invoke(this, new Object[] {Boolean.valueOf(false)}); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to invoke setForeground", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to invoke setForeground", e); } } } public void setMainView(MainView v) { RhodesActivity ra = RhodesActivity.getInstance(); ra.setMainView(v); } public MainView getMainView() { RhodesActivity ra = RhodesActivity.getInstance(); if (ra == null) return null; return ra.getMainView(); } public RhodesApplication getRhodesApplication() { return (RhodesApplication)getApplication(); } public static void exit() { getInstance().getRhodesApplication().exit(); } public void rereadScreenProperties() { // check for orientarion changed // Get screen width/height WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE); Display d = wm.getDefaultDisplay(); mScreenHeight = d.getHeight(); mScreenWidth = d.getWidth(); int newScreenOrientation = d.getOrientation(); if (newScreenOrientation != mScreenOrientation) { onScreenOrientationChanged(mScreenWidth, mScreenHeight, 90); mScreenOrientation = newScreenOrientation; } } public static void showAboutDialog() { PerformOnUiThread.exec(new Runnable() { public void run() { final AboutDialog aboutDialog = new AboutDialog(RhodesActivity.getInstance()); aboutDialog.setTitle("About"); aboutDialog.setCanceledOnTouchOutside(true); aboutDialog.setCancelable(true); aboutDialog.show(); } }, false); } public static void showLogView() { PerformOnUiThread.exec(new Runnable() { public void run() { final LogViewDialog logViewDialog = new LogViewDialog(RhodesActivity.getInstance()); logViewDialog.setTitle("Log View"); logViewDialog.setCancelable(true); logViewDialog.show(); } }, false); } public static void showLogOptions() { PerformOnUiThread.exec(new Runnable() { public void run() { final LogOptionsDialog logOptionsDialog = new LogOptionsDialog(RhodesActivity.getInstance()); logOptionsDialog.setTitle("Logging Options"); logOptionsDialog.setCancelable(true); logOptionsDialog.show(); } }, false); } // Called from native code public static void deleteFilesInFolder(String folder) { try { String[] children = new File(folder).list(); for (int i = 0; i != children.length; ++i) Utils.deleteRecursively(new File(folder, children[i])); } catch (Exception e) { Logger.E(TAG, e); } } public static boolean pingHost(String host) { HttpURLConnection conn = null; boolean hostExists = false; try { URL url = new URL(host); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setAllowUserInteraction( false ); conn.setDoInput( true ); conn.setDoOutput( true ); conn.setUseCaches( false ); hostExists = (conn.getContentLength() > 0); if(hostExists) Logger.I(TAG, "PING network SUCCEEDED."); else Logger.E(TAG, "PING network FAILED."); } catch (Exception e) { Logger.E(TAG, e); } finally { if (conn != null) { try { conn.disconnect(); } catch(Exception e) { Logger.E(TAG, e); } } } return hostExists; } private static boolean hasNetwork() { if (!Capabilities.NETWORK_STATE_ENABLED) { Logger.E(TAG, "HAS_NETWORK: Capability NETWORK_STATE disabled"); return false; } Context ctx = RhodesService.getContext(); ConnectivityManager conn = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE); if (conn == null) { Logger.E(TAG, "HAS_NETWORK: cannot create ConnectivityManager"); return false; } NetworkInfo[] info = conn.getAllNetworkInfo(); if (info == null) { Logger.E(TAG, "HAS_NETWORK: cannot issue getAllNetworkInfo"); return false; } for (int i = 0, lim = info.length; i < lim; ++i) { //Logger.I(TAG, "HAS_NETWORK: " + info[i].toString() ); if (info[i].getState() == NetworkInfo.State.CONNECTED) return true; } Logger.I(TAG, "HAS_NETWORK: all networks are disconnected"); return false; } private static String getCurrentLocale() { String locale = Locale.getDefault().getLanguage(); if (locale.length() == 0) locale = "en"; return locale; } private static String getCurrentCountry() { String cl = Locale.getDefault().getCountry(); return cl; } public static int getScreenWidth() { return mScreenWidth; } public static int getScreenHeight() { return mScreenHeight; } public static Object getProperty(String name) { try { if (name.equalsIgnoreCase("platform")) return "ANDROID"; else if (name.equalsIgnoreCase("locale")) return getCurrentLocale(); else if (name.equalsIgnoreCase("country")) return getCurrentCountry(); else if (name.equalsIgnoreCase("screen_width")) return new Integer(getScreenWidth()); else if (name.equalsIgnoreCase("screen_height")) return new Integer(getScreenHeight()); else if (name.equalsIgnoreCase("has_camera")) return new Boolean(mCameraAvailable); else if (name.equalsIgnoreCase("has_network")) return hasNetwork(); else if (name.equalsIgnoreCase("ppi_x")) return new Float(mScreenPpiX); else if (name.equalsIgnoreCase("ppi_y")) return new Float(mScreenPpiY); else if (name.equalsIgnoreCase("phone_number")) { Context context = RhodesService.getContext(); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String number = manager.getLine1Number(); return number; } else if (name.equalsIgnoreCase("device_name")) { return Build.DEVICE; } else if (name.equalsIgnoreCase("is_emulator")) { String strDevice = Build.DEVICE; return new Boolean(strDevice != null && strDevice.equalsIgnoreCase("generic")); } else if (name.equalsIgnoreCase("os_version")) { return Build.VERSION.RELEASE; } else if (name.equalsIgnoreCase("has_calendar")) { return new Boolean(EventStore.hasCalendar()); } } catch (Exception e) { Logger.E(TAG, "Can't get property \"" + name + "\": " + e); } return null; } public static String getTimezoneStr() { Calendar cal = Calendar.getInstance(); TimeZone tz = cal.getTimeZone(); return tz.getDisplayName(); } public static void runApplication(String appName, Object params) { try { Context ctx = RhodesService.getContext(); PackageManager mgr = ctx.getPackageManager(); PackageInfo info = mgr.getPackageInfo(appName, PackageManager.GET_ACTIVITIES); if (info.activities.length == 0) { Logger.E(TAG, "No activities found for application " + appName); return; } ActivityInfo ainfo = info.activities[0]; String className = ainfo.name; if (className.startsWith(".")) className = ainfo.packageName + className; Intent intent = new Intent(); intent.setClassName(appName, className); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (params != null) { Bundle startParams = new Bundle(); if (params instanceof String) { startParams.putString(RhodesActivity.RHO_START_PARAMS_KEY, (String)params); } /* else if (params instanceof List<?>) { for (Object obj : (List<?>)params) { startParams.putInt(obj.toString(), 1); } } else if (params instanceof Map<?,?>) { Map<?,?> mp = (Map<?,?>)params; for (Iterator<?> it = mp.keySet().iterator(); it.hasNext();) { Object key = it.next(); Object value = mp.get(key); startParams.putString(key.toString(), value == null ? null : value.toString()); } } */ else throw new IllegalArgumentException("Unknown type of incoming parameter"); intent.putExtras(startParams); } ctx.startActivity(intent); } catch (Exception e) { Logger.E(TAG, "Can't run application " + appName + ": " + e.getMessage()); } } public static boolean isAppInstalled(String appName) { try { RhodesService.getContext().getPackageManager().getPackageInfo(appName, 0); return true; } catch (NameNotFoundException ne) { return false; } catch (Exception e) { Logger.E(TAG, "Can't check is app " + appName + " installed: " + e.getMessage()); return false; } } private void updateDownloadNotification(String url, int totalBytes, int currentBytes) { Context context = RhodesActivity.getContext(); Notification n = new Notification(); n.icon = android.R.drawable.stat_sys_download; n.flags |= Notification.FLAG_ONGOING_EVENT; RemoteViews expandedView = new RemoteViews(context.getPackageName(), AndroidR.layout.status_bar_ongoing_event_progress_bar); StringBuilder newUrl = new StringBuilder(); if (url.length() < 17) newUrl.append(url); else { newUrl.append(url.substring(0, 7)); newUrl.append("..."); newUrl.append(url.substring(url.length() - 7, url.length())); } expandedView.setTextViewText(AndroidR.id.title, newUrl.toString()); StringBuffer downloadingText = new StringBuffer(); if (totalBytes > 0) { long progress = currentBytes*100/totalBytes; downloadingText.append(progress); downloadingText.append('%'); } expandedView.setTextViewText(AndroidR.id.progress_text, downloadingText.toString()); expandedView.setProgressBar(AndroidR.id.progress_bar, totalBytes < 0 ? 100 : totalBytes, currentBytes, totalBytes < 0); n.contentView = expandedView; Intent intent = new Intent(ACTION_ASK_CANCEL_DOWNLOAD); n.contentIntent = PendingIntent.getBroadcast(context, 0, intent, 0); intent = new Intent(ACTION_CANCEL_DOWNLOAD); n.deleteIntent = PendingIntent.getBroadcast(context, 0, intent, 0); mNM.notify(DOWNLOAD_PACKAGE_ID, n); } private File downloadPackage(String url) throws IOException { final Context ctx = RhodesActivity.getContext(); final Thread thisThread = Thread.currentThread(); final Runnable cancelAction = new Runnable() { public void run() { thisThread.interrupt(); } }; BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage("Cancel download?"); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelAction.run(); } }); dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Nothing } }); dialog.show(); } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) { cancelAction.run(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD); filter.addAction(ACTION_CANCEL_DOWNLOAD); ctx.registerReceiver(downloadReceiver, filter); File tmpFile = null; InputStream is = null; OutputStream os = null; try { updateDownloadNotification(url, -1, 0); /* List<File> folders = new ArrayList<File>(); folders.add(Environment.getDownloadCacheDirectory()); folders.add(Environment.getDataDirectory()); folders.add(ctx.getCacheDir()); folders.add(ctx.getFilesDir()); try { folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir)); } catch (NameNotFoundException e1) { // Ignore } folders.add(Environment.getExternalStorageDirectory()); for (File folder : folders) { File tmpRootFolder = new File(folder, "rhodownload"); File tmpFolder = new File(tmpRootFolder, ctx.getPackageName()); if (tmpFolder.exists()) deleteFilesInFolder(tmpFolder.getAbsolutePath()); else tmpFolder.mkdirs(); File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk"); Logger.D(TAG, "Check path " + of.getAbsolutePath() + "..."); try { os = new FileOutputStream(of); } catch (FileNotFoundException e) { Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path"); continue; } Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app"); tmpFile = of; break; } */ tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk"); os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE); Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "..."); URL u = new URL(url); URLConnection conn = u.openConnection(); int totalBytes = -1; if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection)conn; totalBytes = httpConn.getContentLength(); } is = conn.getInputStream(); int downloaded = 0; updateDownloadNotification(url, totalBytes, downloaded); long prevProgress = 0; byte[] buf = new byte[65536]; for (;;) { if (thisThread.isInterrupted()) { tmpFile.delete(); Logger.D(TAG, "Download of " + url + " was canceled"); return null; } int nread = is.read(buf); if (nread == -1) break; //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes..."); os.write(buf, 0, nread); downloaded += nread; if (totalBytes > 0) { // Update progress view only if current progress is greater than // previous by more than 10%. Otherwise, if update it very frequently, // user will no have chance to click on notification view and cancel if need long progress = downloaded*10/totalBytes; if (progress > prevProgress) { updateDownloadNotification(url, totalBytes, downloaded); prevProgress = progress; } } } Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath()); return tmpFile; } catch (IOException e) { if (tmpFile != null) tmpFile.delete(); throw e; } finally { try { if (is != null) is.close(); } catch (IOException e) {} try { if (os != null) os.close(); } catch (IOException e) {} mNM.cancel(DOWNLOAD_PACKAGE_ID); ctx.unregisterReceiver(downloadReceiver); } } public static void installApplication(final String url) { Thread bgThread = new Thread(new Runnable() { public void run() { try { final RhodesService r = RhodesService.getInstance(); final File tmpFile = r.downloadPackage(url); if (tmpFile != null) { PerformOnUiThread.exec(new Runnable() { public void run() { try { Logger.D(TAG, "Install package " + tmpFile.getAbsolutePath()); Uri uri = Uri.fromFile(tmpFile); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, "application/vnd.android.package-archive"); r.startActivity(intent); } catch (Exception e) { Log.e(TAG, "Can't install file from " + tmpFile.getAbsolutePath(), e); Logger.E(TAG, "Can't install file from " + tmpFile.getAbsolutePath() + ": " + e.getMessage()); } } }, false); } } catch (IOException e) { Log.e(TAG, "Can't download package from " + url, e); Logger.E(TAG, "Can't download package from " + url + ": " + e.getMessage()); } } }); bgThread.setPriority(Thread.MIN_PRIORITY); bgThread.start(); } public static void uninstallApplication(String appName) { try { Uri packageUri = Uri.parse("package:" + appName); Intent intent = new Intent(Intent.ACTION_DELETE, packageUri); RhodesService.getContext().startActivity(intent); } catch (Exception e) { Logger.E(TAG, "Can't uninstall application " + appName + ": " + e.getMessage()); } } public static void openExternalUrl(String url) { try { Context ctx = RhodesService.getContext(); Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); ctx.startActivity(Intent.createChooser(intent, "Open in...")); } catch (Exception e) { Logger.E(TAG, "Can't open url :" + url + ": " + e.getMessage()); } } private native void setPushRegistrationId(String id); private native boolean callPushCallback(String data); private void handlePushMessage(Bundle extras) { Logger.D(TAG, "Receive PUSH message"); if (extras == null) { Logger.W(TAG, "Empty PUSH message received"); return; } StringBuilder builder = new StringBuilder(); Set<String> keys = extras.keySet(); // Remove system related keys keys.remove("collapse_key"); keys.remove("from"); for (String key : keys) { Logger.D(TAG, "PUSH item: " + key); Object value = extras.get(key); if (builder.length() > 0) builder.append("&"); builder.append(key); builder.append("="); if (value != null) builder.append(value.toString()); } String data = builder.toString(); Logger.D(TAG, "Received PUSH message: " + data); if (callPushCallback(data)) return; String alert = extras.getString("alert"); if (alert != null) { Logger.D(TAG, "PUSH: Alert: " + alert); Alert.showPopup(alert); } String sound = extras.getString("sound"); if (sound != null) { Logger.D(TAG, "PUSH: Sound file name: " + sound); Alert.playFile("/public/alerts/" + sound, null); } String vibrate = extras.getString("vibrate"); if (vibrate != null) { Logger.D(TAG, "PUSH: Vibrate: " + vibrate); int duration; try { duration = Integer.parseInt(vibrate); } catch (NumberFormatException e) { duration = 5; } Logger.D(TAG, "Vibrate " + duration + " seconds"); Alert.vibrate(duration); } String syncSources = extras.getString("do_sync"); if (syncSources != null) { Logger.D(TAG, "PUSH: Sync:"); boolean syncAll = false; for (String source : syncSources.split(",")) { Logger.D(TAG, "url = " + source); if (source.equalsIgnoreCase("all")) syncAll = true; else { doSyncSource(source.trim()); } } if (syncAll) doSyncAllSources(true); } } private void restartGeoLocationIfNeeded() { if (mNeedGeoLocationRestart) { GeoLocation.isKnownPosition(); mNeedGeoLocationRestart = false; } } private void stopGeoLocation() { mNeedGeoLocationRestart = GeoLocation.isAvailable(); GeoLocation.stop(); } private void restoreWakeLockIfNeeded() { PerformOnUiThread.exec( new Runnable() { public void run() { if (wakeLockEnabled) { if (wakeLockObject == null) { PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); if (pm != null) { Logger.I(TAG, "activityStarted() restore wakeLock object"); wakeLockObject = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG); wakeLockObject.acquire(); } else { Logger.E(TAG, "activityStarted() - Can not get PowerManager !!!"); } } } } }, false); } private void stopWakeLock() { PerformOnUiThread.exec( new Runnable() { public void run() { if (wakeLockObject != null) { Logger.I(TAG, "activityStopped() temporary destroy wakeLock object"); wakeLockObject.release(); wakeLockObject = null; } } }, false); } public static int rho_sys_set_sleeping(int enable) { Logger.I(TAG, "rho_sys_set_sleeping("+enable+")"); int wasEnabled = 1; if (wakeLockObject != null) { wasEnabled = 0; } if (enable != 0) { // disable lock device PerformOnUiThread.exec( new Runnable() { public void run() { if (wakeLockObject != null) { wakeLockObject.release(); wakeLockObject = null; wakeLockEnabled = false; } } }, false); } else { // lock device from sleep PerformOnUiThread.exec( new Runnable() { public void run() { if (wakeLockObject == null) { PowerManager pm = (PowerManager)getInstance().getContext().getSystemService(Context.POWER_SERVICE); if (pm != null) { wakeLockObject = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG); wakeLockObject.acquire(); wakeLockEnabled = true; } else { Logger.E(TAG, "rho_sys_set_sleeping() - Can not get PowerManager !!!"); } } } }, false); } return wasEnabled; } private void handleAppActivation() { if (DEBUG) Log.d(TAG, "handle app activation"); restartGeoLocationIfNeeded(); restoreWakeLockIfNeeded(); callActivationCallback(true); } private void handleAppDeactivation() { if (DEBUG) Log.d(TAG, "handle app deactivation"); stopWakeLock(); stopGeoLocation(); callActivationCallback(false); } public static void activityStarted() { if (DEBUG) Log.d(TAG, "activityStarted (1): sActivitiesActive=" + sActivitiesActive); if (sActivitiesActive == 0) { RhodesService r = RhodesService.getInstance(); if (DEBUG) Log.d(TAG, "first activity started; r=" + r); if (r != null) r.handleAppActivation(); } ++sActivitiesActive; if (DEBUG) Log.d(TAG, "activityStarted (2): sActivitiesActive=" + sActivitiesActive); } public static void activityStopped() { if (DEBUG) Log.d(TAG, "activityStopped (1): sActivitiesActive=" + sActivitiesActive); --sActivitiesActive; if (sActivitiesActive == 0) { RhodesService r = RhodesService.getInstance(); if (DEBUG) Log.d(TAG, "last activity stopped; r=" + r); if (r != null) r.handleAppDeactivation(); } if (DEBUG) Log.d(TAG, "activityStopped (2): sActivitiesActive=" + sActivitiesActive); } @Override public void startActivity(Intent intent) { RhodesActivity ra = RhodesActivity.getInstance(); if (ra == null) throw new IllegalStateException("Trying to start activity, but main activity is empty (we are in background, no UI active)"); ra.startActivity(intent); } public static Context getContext() { RhodesService r = RhodesService.getInstance(); if (r == null) throw new IllegalStateException("No rhodes service instance at this moment"); return r; } }
package com.intellij.dvcs.push.ui; import com.intellij.dvcs.DvcsUtil; import com.intellij.dvcs.push.*; import com.intellij.dvcs.repo.Repository; import com.intellij.dvcs.repo.VcsRepositoryManager; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.OptionAction; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.ui.JBDimension; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.components.BorderLayoutPanel; import net.miginfocom.swing.MigLayout; import one.util.streamex.StreamEx; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import static com.intellij.util.containers.ContainerUtil.getFirstItem; public class VcsPushDialog extends DialogWrapper implements VcsPushUi, DataProvider { private static final String DIMENSION_KEY = "Vcs.Push.Dialog.v2"; private static final String HELP_ID = "Vcs.Push.Dialog"; private static final int CENTER_PANEL_HEIGHT = 450; private static final int CENTER_PANEL_WIDTH = 800; protected final Project myProject; private final PushLog myListPanel; protected final PushController myController; private final Map<PushSupport, VcsPushOptionsPanel> myAdditionalPanels; private Action myPushAction; @NotNull private final List<ActionWrapper> myAdditionalActions; public VcsPushDialog(@NotNull Project project, @NotNull List<? extends Repository> selectedRepositories, @Nullable Repository currentRepo) { this(project, VcsRepositoryManager.getInstance(project).getRepositories(), selectedRepositories, currentRepo, null); } public VcsPushDialog(@NotNull Project project, Collection<? extends Repository> allRepos, @NotNull List<? extends Repository> selectedRepositories, @Nullable Repository currentRepo, @Nullable PushSource pushSource) { super(project, true, (Registry.is("ide.perProjectModality")) ? IdeModalityType.PROJECT : IdeModalityType.IDE); myProject = project; myController = new PushController(project, this, allRepos, selectedRepositories, currentRepo, pushSource); myAdditionalPanels = myController.createAdditionalPanels(); myListPanel = myController.getPushPanelLog(); ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("Vcs.Push.Actions"); myAdditionalActions = StreamEx. of(group.getChildren(null)). select(PushActionBase.class). map(action -> new ActionWrapper(myProject, this, action)).toList(); init(); updateOkActions(); setOKButtonText("Push"); setOKButtonMnemonic('P'); setTitle("Push Commits " + (allRepos.size() == 1 ? "to " + DvcsUtil.getShortRepositoryName(getFirstItem(allRepos)) : "")); } @Nullable @Override protected Border createContentPaneBorder() { return null; } @Nullable @Override protected JPanel createSouthAdditionalPanel() { return createSouthOptionsPanel(); } @Override protected JComponent createSouthPanel() { JComponent southPanel = super.createSouthPanel(); southPanel.setBorder(JBUI.Borders.empty(8, 12)); return southPanel; } @Override protected JComponent createCenterPanel() { JPanel panel = JBUI.Panels.simplePanel(0, 2) .addToCenter(myListPanel) .addToBottom(createOptionsPanel()); myListPanel.setPreferredSize(new JBDimension(CENTER_PANEL_WIDTH, CENTER_PANEL_HEIGHT)); return panel; } @NotNull protected JPanel createOptionsPanel() { JPanel optionsPanel = new JPanel(new MigLayout("ins 0 0, flowy")) { @Override public Component add(Component comp) { JPanel wrapperPanel = new BorderLayoutPanel().addToCenter(comp); wrapperPanel.setBorder(JBUI.Borders.empty(5, 15, 0, 0)); return super.add(wrapperPanel); } }; for (VcsPushOptionsPanel panel : myAdditionalPanels.values()) { if (panel.getPosition() == VcsPushOptionsPanel.OptionsPanelPosition.DEFAULT) { optionsPanel.add(panel); } } return optionsPanel; } @NotNull private JPanel createSouthOptionsPanel() { JPanel optionsPanel = new JPanel(new MigLayout(String.format("ins 0 %spx 0 0, flowx, gapx %spx", JBUI.scale(20), JBUI.scale(16)))); for (VcsPushOptionsPanel panel : myAdditionalPanels.values()) { if (panel.getPosition() == VcsPushOptionsPanel.OptionsPanelPosition.SOUTH) { optionsPanel.add(panel); } } return optionsPanel; } @Override protected String getDimensionServiceKey() { return DIMENSION_KEY; } @Nullable @Override protected ValidationInfo doValidate() { updateOkActions(); return null; } @Override protected boolean postponeValidation() { return false; } @Override protected void doOKAction() { push(false); } @Override protected Action @NotNull [] createActions() { final List<Action> actions = new ArrayList<>(); myPushAction = new ComplexPushAction(myAdditionalActions); myPushAction.putValue(DEFAULT_ACTION, Boolean.TRUE); actions.add(myPushAction); actions.add(getCancelAction()); actions.add(getHelpAction()); return actions.toArray(new Action[0]); } @Override public boolean canPush() { return myController.isPushAllowed(); } @Override @NotNull public Map<PushSupport, Collection<PushInfo>> getSelectedPushSpecs() { return myController.getSelectedPushSpecs(); } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myListPanel.getPreferredFocusedComponent(); } @NotNull @Override protected Action getOKAction() { return myPushAction; } @Override protected String getHelpId() { return HELP_ID; } @Override @CalledInAwt public void push(boolean forcePush) { executeAfterRunningPrePushHandlers(new Task.Backgroundable(myProject, "Pushing...", true) { @Override public void run(@NotNull ProgressIndicator indicator) { myController.push(forcePush); } }); } @Override @CalledInAwt public void executeAfterRunningPrePushHandlers(@NotNull Task.Backgroundable activity) { PrePushHandler.Result result = runPrePushHandlersInModalTask(); if (result == PrePushHandler.Result.OK) { activity.queue(); close(OK_EXIT_CODE); } else if (result == PrePushHandler.Result.ABORT_AND_CLOSE) { doCancelAction(); } else if (result == PrePushHandler.Result.ABORT) { // cancel push and leave the push dialog open } } @CalledInAwt public PrePushHandler.Result runPrePushHandlersInModalTask() { FileDocumentManager.getInstance().saveAllDocuments(); AtomicReference<PrePushHandler.Result> result = new AtomicReference<>(PrePushHandler.Result.OK); new Task.Modal(myController.getProject(), "Checking Commits...", true) { @Override public void run(@NotNull ProgressIndicator indicator) { result.set(myController.executeHandlers(indicator)); } @Override public void onThrowable(@NotNull Throwable error) { if (error instanceof PushController.HandlerException) { PushController.HandlerException handlerException = (PushController.HandlerException)error; Throwable cause = handlerException.getCause(); String failedHandler = handlerException.getFailedHandlerName(); List<String> skippedHandlers = handlerException.getSkippedHandlers(); String suggestionMessage; if (cause instanceof ProcessCanceledException) { suggestionMessage = failedHandler + " has been cancelled.\n"; } else { super.onThrowable(cause); suggestionMessage = failedHandler + " has failed. See log for more details.\n"; } if (skippedHandlers.isEmpty()) { suggestionMessage += "Would you like to push anyway or cancel the push completely?"; } else { suggestionMessage += "Would you like to skip all remaining pre-push steps and push, or cancel the push completely?"; } suggestToSkipOrPush(suggestionMessage); } else { super.onThrowable(error); } } @Override public void onCancel() { super.onCancel(); suggestToSkipOrPush("Would you like to skip all pre-push steps and push, or cancel the push completely?"); } private void suggestToSkipOrPush(@NotNull String message) { if (Messages.showOkCancelDialog(myProject, message, "Push", "&Push Anyway", "&Cancel", UIUtil.getWarningIcon()) == Messages.OK) { result.set(PrePushHandler.Result.OK); } else { result.set(PrePushHandler.Result.ABORT); } } }.queue(); return result.get(); } public void updateOkActions() { myPushAction.setEnabled(canPush()); for (ActionWrapper wrapper : myAdditionalActions) { wrapper.update(); } } public void enableOkActions(boolean value) { myPushAction.setEnabled(value); } @Override @Nullable public VcsPushOptionValue getAdditionalOptionValue(@NotNull PushSupport support) { VcsPushOptionsPanel panel = myAdditionalPanels.get(support); return panel == null ? null : panel.getValue(); } @Nullable @Override public Object getData(@NotNull String dataId) { if (VcsPushUi.VCS_PUSH_DIALOG.is(dataId)) { return this; } return null; } private class ComplexPushAction extends AbstractAction implements OptionAction { private final List<? extends ActionWrapper> myOptions; private ComplexPushAction(@NotNull List<? extends ActionWrapper> additionalActions) { super("&Push"); myOptions = additionalActions; } @Override public void actionPerformed(ActionEvent e) { push(false); } @Override public void setEnabled(boolean isEnabled) { super.setEnabled(isEnabled); for (Action optionAction : myOptions) { optionAction.setEnabled(isEnabled); } } @Override public Action @NotNull [] getOptions() { return myAdditionalActions.toArray(new ActionWrapper[0]); } } private static class ActionWrapper extends AbstractAction { @NotNull private final Project myProject; @NotNull private final VcsPushUi myDialog; @NotNull private final PushActionBase myRealAction; ActionWrapper(@NotNull Project project, @NotNull VcsPushUi dialog, @NotNull PushActionBase realAction) { super(realAction.getTemplatePresentation().getTextWithMnemonic()); myProject = project; myDialog = dialog; myRealAction = realAction; putValue(OptionAction.AN_ACTION, realAction); } @Override public void actionPerformed(ActionEvent e) { myRealAction.actionPerformed(myProject, myDialog); } public void update() { boolean enabled = myRealAction.isEnabled(myDialog); setEnabled(enabled); putValue(Action.SHORT_DESCRIPTION, myRealAction.getDescription(myDialog, enabled)); } } }
package com.intellij.build; import com.intellij.build.events.*; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.ide.actions.EditSourceAction; import com.intellij.ide.ui.UISettings; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.treeView.NodeRenderer; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ThreeComponentsSplitter; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.ui.*; import com.intellij.ui.tree.AsyncTreeModel; import com.intellij.ui.tree.StructureTreeModel; import com.intellij.ui.tree.TreeVisitor; import com.intellij.ui.tree.ui.DefaultTreeUI; import com.intellij.ui.treeStructure.SimpleNode; import com.intellij.ui.treeStructure.SimpleTreeStructure; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.EditSourceOnDoubleClickHandler; import com.intellij.util.EditSourceOnEnterKeyHandler; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.DateFormatUtil; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.border.CompoundBorder; import javax.swing.plaf.TreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Predicate; import java.util.function.Supplier; import static com.intellij.build.BuildView.CONSOLE_VIEW_NAME; import static com.intellij.ui.AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED; import static com.intellij.ui.SimpleTextAttributes.GRAYED_ATTRIBUTES; import static com.intellij.util.ui.UIUtil.getTreeSelectionForeground; /** * @author Vladislav.Soroka */ public class BuildTreeConsoleView implements ConsoleView, DataProvider, BuildConsoleView, Filterable<ExecutionNode> { private static final Logger LOG = Logger.getInstance(BuildTreeConsoleView.class); @NonNls private static final String TREE = "tree"; @NonNls private static final String SPLITTER_PROPERTY = "BuildView.Splitter.Proportion"; private final JPanel myPanel = new JPanel(); private final Map<Object, ExecutionNode> nodesMap = ContainerUtil.newConcurrentMap(); private final Project myProject; private final ConsoleViewHandler myConsoleViewHandler; private final String myWorkingDir; private final AtomicBoolean myDisposed = new AtomicBoolean(); private final AtomicBoolean myShownFirstError = new AtomicBoolean(); private final StructureTreeModel<SimpleTreeStructure> myTreeModel; private final Tree myTree; private final ExecutionNode myRootNode; private final ExecutionNode myBuildProgressRootNode; @Nullable private volatile Predicate<ExecutionNode> myExecutionTreeFilter; public BuildTreeConsoleView(Project project, BuildDescriptor buildDescriptor, @Nullable ExecutionConsole executionConsole, @NotNull BuildViewSettingsProvider buildViewSettingsProvider) { myProject = project; myWorkingDir = FileUtil.toSystemIndependentName(buildDescriptor.getWorkingDir()); myRootNode = new ExecutionNode(myProject, null); myRootNode.setAutoExpandNode(true); myBuildProgressRootNode = new ExecutionNode(myProject, myRootNode); myBuildProgressRootNode.setAutoExpandNode(true); myRootNode.add(myBuildProgressRootNode); SimpleTreeStructure treeStructure = new SimpleTreeStructure.Impl(myRootNode); myTreeModel = new StructureTreeModel<>(treeStructure); myTree = initTree(new AsyncTreeModel(myTreeModel, this)); JPanel myContentPanel = new JPanel(); myContentPanel.setLayout(new CardLayout()); myContentPanel.add(ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT), TREE); myPanel.setLayout(new BorderLayout()); OnePixelSplitter myThreeComponentsSplitter = new OnePixelSplitter(SPLITTER_PROPERTY, 0.33f); myThreeComponentsSplitter.setFirstComponent(myContentPanel); myConsoleViewHandler = new ConsoleViewHandler(myProject, myTree, myBuildProgressRootNode, this, executionConsole, buildViewSettingsProvider); myThreeComponentsSplitter.setSecondComponent(myConsoleViewHandler.getComponent()); myPanel.add(myThreeComponentsSplitter, BorderLayout.CENTER); } private void installContextMenu(@NotNull StartBuildEvent startBuildEvent) { UIUtil.invokeLaterIfNeeded(() -> { final DefaultActionGroup group = new DefaultActionGroup(); final DefaultActionGroup rerunActionGroup = new DefaultActionGroup(); AnAction[] restartActions = startBuildEvent.getRestartActions(); for (AnAction anAction : restartActions) { rerunActionGroup.add(anAction); } if (restartActions.length > 0) { group.addAll(rerunActionGroup); group.addSeparator(); } EditSourceAction edit = new EditSourceAction(); ActionUtil.copyFrom(edit, "EditSource"); group.add(edit); group.addSeparator(); group.add(new ShowExecutionErrorsOnlyAction(this)); PopupHandler.installPopupHandler(myTree, group, "BuildView"); }); } @Override public void clear() { getRootElement().removeChildren(); nodesMap.clear(); myConsoleViewHandler.clear(); myTreeModel.invalidate(); } @Override public boolean isFilteringEnabled() { return true; } @Override @Nullable public Predicate<ExecutionNode> getFilter() { return myExecutionTreeFilter; } @Override public void setFilter(@Nullable Predicate<ExecutionNode> executionTreeFilter) { myExecutionTreeFilter = executionTreeFilter; ExecutionNode buildProgressRootNode = getBuildProgressRootNode(); ExecutionNode rootElement = getRootElement(); Predicate<ExecutionNode> predicate = executionTreeFilter == null ? null : node -> node == buildProgressRootNode || executionTreeFilter.test(node); rootElement.setFilter(predicate); scheduleUpdate(rootElement); } private ExecutionNode getRootElement() { return myRootNode; } public ExecutionNode getBuildProgressRootNode() { return myBuildProgressRootNode; } @Override public void print(@NotNull String text, @NotNull ConsoleViewContentType contentType) { } @Nullable private ExecutionNode getOrMaybeCreateParentNode(@NotNull BuildEvent event) { ExecutionNode parentNode = event.getParentId() == null ? null : nodesMap.get(event.getParentId()); if (event instanceof MessageEvent) { if (parentNode == getBuildProgressRootNode()) { parentNode = getRootElement(); } parentNode = createMessageParentNodes((MessageEvent)event, parentNode); } return parentNode; } public void onEventInternal(@NotNull BuildEvent event) { final ExecutionNode parentNode = getOrMaybeCreateParentNode(event); final Object eventId = event.getId(); ExecutionNode currentNode = nodesMap.get(eventId); ExecutionNode buildProgressRootNode = getBuildProgressRootNode(); if (event instanceof StartEvent || event instanceof MessageEvent) { if (currentNode == null) { if (event instanceof StartBuildEvent) { currentNode = buildProgressRootNode; installContextMenu((StartBuildEvent)event); String buildTitle = ((StartBuildEvent)event).getBuildTitle(); currentNode.setTitle(buildTitle); currentNode.setAutoExpandNode(true); } else { currentNode = new ExecutionNode(myProject, parentNode); if (event instanceof MessageEvent) { MessageEvent messageEvent = (MessageEvent)event; currentNode.setStartTime(messageEvent.getEventTime()); currentNode.setEndTime(messageEvent.getEventTime()); Navigatable messageEventNavigatable = messageEvent.getNavigatable(myProject); currentNode.setNavigatable(messageEventNavigatable); final MessageEventResult messageEventResult = messageEvent.getResult(); currentNode.setResult(messageEventResult); if (messageEvent.getKind() == MessageEvent.Kind.ERROR) { if (messageEventNavigatable != null && myShownFirstError.compareAndSet(false, true)) { GuiUtils.invokeLaterIfNeeded(() -> messageEventNavigatable.navigate(false), ModalityState.defaultModalityState(), myProject.getDisposed()); } } } currentNode.setAutoExpandNode(currentNode == buildProgressRootNode || parentNode == buildProgressRootNode); } nodesMap.put(eventId, currentNode); } else { LOG.warn("start event id collision found:" + eventId + ", was also in node: " + currentNode.getTitle()); return; } if (parentNode != null) { parentNode.add(currentNode); } } else { currentNode = nodesMap.get(eventId); if (currentNode == null && event instanceof ProgressBuildEvent) { currentNode = new ExecutionNode(myProject, parentNode); nodesMap.put(eventId, currentNode); if (parentNode != null) { parentNode.add(currentNode); } } } if (currentNode == null) { // TODO log error return; } currentNode.setName(event.getMessage()); currentNode.setHint(event.getHint()); if (currentNode.getStartTime() == 0) { currentNode.setStartTime(event.getEventTime()); } if (event instanceof FinishEvent) { currentNode.setEndTime(event.getEventTime()); currentNode.setResult(((FinishEvent)event).getResult()); } if (event instanceof FinishBuildEvent) { String aHint = event.getHint(); String time = DateFormatUtil.formatDateTime(event.getEventTime()); aHint = aHint == null ? "at " + time : aHint + " at " + time; currentNode.setHint(aHint); if (myConsoleViewHandler.myExecutionNode == null) { ExecutionNode element = buildProgressRootNode; ApplicationManager.getApplication().invokeLater(() -> myConsoleViewHandler.setNode(element)); } } scheduleUpdate(currentNode); } protected void expand(Tree tree) { TreeUtil.expand(tree, path -> { ExecutionNode node = TreeUtil.getLastUserObject(ExecutionNode.class, path); if (node != null && node.isAutoExpandNode() && node.getChildCount() > 0) { return TreeVisitor.Action.CONTINUE; } else { return TreeVisitor.Action.SKIP_CHILDREN; } }, path -> { }); } @Override public void scrollTo(int offset) { } @Override public void attachToProcess(ProcessHandler processHandler) { } @Override public boolean isOutputPaused() { return false; } @Override public void setOutputPaused(boolean value) { } @Override public boolean hasDeferredOutput() { return false; } @Override public void performWhenNoDeferredOutput(@NotNull Runnable runnable) { } @Override public void setHelpId(@NotNull String helpId) { } @Override public void addMessageFilter(@NotNull Filter filter) { } @Override public void printHyperlink(@NotNull String hyperlinkText, @Nullable HyperlinkInfo info) { } @Override public int getContentSize() { return 0; } @Override public boolean canPause() { return false; } @NotNull @Override public AnAction[] createConsoleActions() { return AnAction.EMPTY_ARRAY; } @Override public void allowHeavyFilters() { } @Override public JComponent getComponent() { return myPanel; } @Override public JComponent getPreferredFocusableComponent() { return myTree; } @Override public void dispose() { myDisposed.set(true); } public boolean isDisposed() { return myDisposed.get(); } @Override public void onEvent(@NotNull BuildEvent event) { myTreeModel.getInvoker().runOrInvokeLater(() -> onEventInternal(event)); } void scheduleUpdate(ExecutionNode executionNode) { SimpleNode node = executionNode.getParent() == null ? executionNode : executionNode.getParent(); myTreeModel.invalidate(node, true).onProcessed(p -> expand(myTree)); } private ExecutionNode createMessageParentNodes(MessageEvent messageEvent, ExecutionNode parentNode) { Object messageEventParentId = messageEvent.getParentId(); if (messageEventParentId == null) return null; String group = messageEvent.getGroup(); String groupNodeId = group.hashCode() + messageEventParentId.toString(); ExecutionNode messagesGroupNode = getOrCreateMessagesNode(messageEvent, groupNodeId, parentNode, null, group, true, null, null, nodesMap, myProject); EventResult groupNodeResult = messagesGroupNode.getResult(); final MessageEvent.Kind eventKind = messageEvent.getKind(); if (!(groupNodeResult instanceof MessageEventResult) || ((MessageEventResult)groupNodeResult).getKind().compareTo(eventKind) > 0) { messagesGroupNode.setResult((MessageEventResult)() -> eventKind); } if (messageEvent instanceof FileMessageEvent) { ExecutionNode fileParentNode = messagesGroupNode; FilePosition filePosition = ((FileMessageEvent)messageEvent).getFilePosition(); String filePath = FileUtil.toSystemIndependentName(filePosition.getFile().getPath()); String parentsPath = ""; String relativePath = FileUtil.getRelativePath(myWorkingDir, filePath, '/'); if (relativePath != null) { parentsPath = myWorkingDir; } VirtualFile ioFile = VfsUtil.findFileByIoFile(new File(filePath), false); String fileNodeId = groupNodeId + filePath; relativePath = StringUtil.isEmpty(parentsPath) ? filePath : FileUtil.getRelativePath(parentsPath, filePath, '/'); parentNode = getOrCreateMessagesNode(messageEvent, fileNodeId, fileParentNode, relativePath, null, true, () -> { VirtualFile file = VfsUtil.findFileByIoFile(filePosition.getFile(), false); if (file != null) { return file.getFileType().getIcon(); } return null; }, messageEvent.getNavigatable(myProject), nodesMap, myProject); } else { parentNode = messagesGroupNode; } if (eventKind == MessageEvent.Kind.ERROR || eventKind == MessageEvent.Kind.WARNING) { SimpleNode p = parentNode; do { ((ExecutionNode)p).reportChildMessageKind(eventKind); } while ((p = p.getParent()) instanceof ExecutionNode); scheduleUpdate(getRootElement()); } return parentNode; } public void hideRootNode() { UIUtil.invokeLaterIfNeeded(() -> { if (myTree != null) { myTree.setRootVisible(false); myTree.setShowsRootHandles(true); } }); } @Nullable @Override public Object getData(@NotNull String dataId) { if (PlatformDataKeys.HELP_ID.is(dataId)) return "reference.build.tool.window"; if (CommonDataKeys.PROJECT.is(dataId)) return myProject; if (CommonDataKeys.NAVIGATABLE_ARRAY.is(dataId)) return extractNavigatables(); return null; } private Object extractNavigatables() { final List<Navigatable> navigatables = new ArrayList<>(); for (ExecutionNode each : getSelectedNodes()) { List<Navigatable> navigatable = each.getNavigatables(); navigatables.addAll(navigatable); } return navigatables.isEmpty() ? null : navigatables.toArray(new Navigatable[0]); } private ExecutionNode[] getSelectedNodes() { final ExecutionNode[] result = new ExecutionNode[0]; if (myTree != null) { final List<ExecutionNode> nodes = TreeUtil.collectSelectedObjects(myTree, path -> TreeUtil.getLastUserObject(ExecutionNode.class, path)); return nodes.toArray(result); } return result; } @TestOnly JTree getTree() { return myTree; } private static Tree initTree(@NotNull AsyncTreeModel model) { Tree tree = new MyTree(model); UIUtil.putClientProperty(tree, ANIMATION_IN_RENDERER_ALLOWED, true); tree.setRootVisible(false); EditSourceOnDoubleClickHandler.install(tree); EditSourceOnEnterKeyHandler.install(tree, null); new TreeSpeedSearch(tree).setComparator(new SpeedSearchComparator(false)); TreeUtil.installActions(tree); tree.setCellRenderer(new MyNodeRenderer()); return tree; } private static void updateSplitter(@NotNull ThreeComponentsSplitter myThreeComponentsSplitter) { int firstSize = myThreeComponentsSplitter.getFirstSize(); int splitterWidth = myThreeComponentsSplitter.getWidth(); if (firstSize == 0) { float proportion = PropertiesComponent.getInstance().getFloat(SPLITTER_PROPERTY, 0.3f); int width = Math.round(splitterWidth * proportion); if (width > 0) { myThreeComponentsSplitter.setFirstSize(width); } } } @NotNull private static ExecutionNode getOrCreateMessagesNode(MessageEvent messageEvent, String nodeId, ExecutionNode parentNode, String nodeName, String nodeTitle, boolean autoExpandNode, @Nullable Supplier<? extends Icon> iconProvider, @Nullable Navigatable navigatable, Map<Object, ExecutionNode> nodesMap, Project project) { ExecutionNode node = nodesMap.get(nodeId); if (node == null) { node = new ExecutionNode(project, parentNode); node.setName(nodeName); node.setTitle(nodeTitle); if (autoExpandNode) { node.setAutoExpandNode(true); } node.setStartTime(messageEvent.getEventTime()); node.setEndTime(messageEvent.getEventTime()); if (iconProvider != null) { node.setIconProvider(iconProvider); } if (navigatable != null) { node.setNavigatable(navigatable); } parentNode.add(node); nodesMap.put(nodeId, node); } return node; } private static class ConsoleViewHandler { private static final String TASK_OUTPUT_VIEW_NAME = "taskOutputView"; private final JPanel myPanel; private final CompositeView<ExecutionConsole> myView; @NotNull private final BuildViewSettingsProvider myViewSettingsProvider; @NotNull private final ExecutionNode myBuildProgressRootNode; @Nullable private ExecutionNode myExecutionNode; ConsoleViewHandler(Project project, @NotNull Tree tree, @NotNull ExecutionNode buildProgressRootNode, @NotNull Disposable parentDisposable, @Nullable ExecutionConsole executionConsole, @NotNull BuildViewSettingsProvider buildViewSettingsProvider) { myBuildProgressRootNode = buildProgressRootNode; myPanel = new JPanel(new BorderLayout()); ConsoleView myNodeConsole = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole(); myViewSettingsProvider = buildViewSettingsProvider; myView = new CompositeView<>(null); if (executionConsole != null && buildViewSettingsProvider.isSideBySideView()) { myView.addView(executionConsole, CONSOLE_VIEW_NAME, true); } myView.addView(myNodeConsole, TASK_OUTPUT_VIEW_NAME, false); if (buildViewSettingsProvider.isSideBySideView()) { myView.enableView(CONSOLE_VIEW_NAME, false); myPanel.setVisible(true); } else { myPanel.setVisible(false); } JComponent consoleComponent = myNodeConsole.getComponent(); AnAction[] consoleActions = myNodeConsole.createConsoleActions(); consoleComponent.setFocusable(true); final Color editorBackground = EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground(); consoleComponent.setBorder(new CompoundBorder(IdeBorderFactory.createBorder(SideBorder.RIGHT), new SideBorder(editorBackground, SideBorder.LEFT))); myPanel.add(myView.getComponent(), BorderLayout.CENTER); final ActionToolbar toolbar = ActionManager.getInstance() .createActionToolbar("BuildResults", new DefaultActionGroup(consoleActions), false); myPanel.add(toolbar.getComponent(), BorderLayout.EAST); tree.addTreeSelectionListener(e -> { TreePath path = e.getPath(); if (path == null || !e.isAddedPath()) { return; } TreePath selectionPath = tree.getSelectionPath(); setNode(selectionPath != null ? (DefaultMutableTreeNode)selectionPath.getLastPathComponent() : null); }); Disposer.register(parentDisposable, myView); Disposer.register(parentDisposable, myNodeConsole); } private ConsoleView getTaskOutputView() { return (ConsoleView)myView.getView(TASK_OUTPUT_VIEW_NAME); } public boolean setNode(@NotNull ExecutionNode node) { if (node == myBuildProgressRootNode) return false; EventResult eventResult = node.getResult(); boolean hasChanged = false; ConsoleView taskOutputView = getTaskOutputView(); if (eventResult instanceof FailureResult) { taskOutputView.clear(); List<? extends Failure> failures = ((FailureResult)eventResult).getFailures(); if (failures.isEmpty()) return false; for (Iterator<? extends Failure> iterator = failures.iterator(); iterator.hasNext(); ) { Failure failure = iterator.next(); String text = ObjectUtils.chooseNotNull(failure.getDescription(), failure.getMessage()); if (text == null && failure.getError() != null) { text = failure.getError().getMessage(); } if (text == null) continue; printDetails(failure, text); hasChanged = true; if (iterator.hasNext()) { taskOutputView.print("\n\n", ConsoleViewContentType.NORMAL_OUTPUT); } } } else if (eventResult instanceof MessageEventResult) { String details = ((MessageEventResult)eventResult).getDetails(); if (details == null) { return false; } if (details.isEmpty()) { return false; } taskOutputView.clear(); printDetails(null, details); hasChanged = true; } if (!hasChanged) return false; taskOutputView.scrollTo(0); myView.enableView(TASK_OUTPUT_VIEW_NAME, !myViewSettingsProvider.isSideBySideView()); myPanel.setVisible(true); return true; } private void printDetails(Failure failure, @Nullable String details) { BuildConsoleUtils.printDetails(getTaskOutputView(), failure, details); } public void setNode(@Nullable DefaultMutableTreeNode node) { if (node == null || node.getUserObject() == myExecutionNode) return; if (node.getUserObject() instanceof ExecutionNode) { myExecutionNode = (ExecutionNode)node.getUserObject(); if (setNode((ExecutionNode)node.getUserObject())) { return; } } myExecutionNode = null; if (myView.getView(CONSOLE_VIEW_NAME) != null && myViewSettingsProvider.isSideBySideView()) { myView.enableView(CONSOLE_VIEW_NAME, false); myPanel.setVisible(true); } else { myPanel.setVisible(false); } } public JComponent getComponent() { return myPanel; } public void clear() { myPanel.setVisible(false); getTaskOutputView().clear(); } } private static class MyTree extends Tree { private MyTree(TreeModel treemodel) { super(treemodel); } @Override public void setUI(final TreeUI ui) { super.setUI(ui instanceof DefaultTreeUI ? ui : new DefaultTreeUI()); setLargeModel(true); } } private static class MyNodeRenderer extends NodeRenderer { private String myDurationText; private Color myDurationColor; private int myDurationWidth; private int myDurationOffset; @Override public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus); myDurationText = null; myDurationColor = null; myDurationWidth = 0; myDurationOffset = 0; final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; final Object userObj = node.getUserObject(); if (userObj instanceof ExecutionNode) { myDurationText = ((ExecutionNode)userObj).getDuration(); if (myDurationText != null) { FontMetrics metrics = getFontMetrics(RelativeFont.SMALL.derive(getFont())); myDurationWidth = metrics.stringWidth(myDurationText); myDurationOffset = metrics.getHeight() / 2; // an empty area before and after the text myDurationColor = selected ? getTreeSelectionForeground(hasFocus) : GRAYED_ATTRIBUTES.getFgColor(); } } } @Override protected void paintComponent(Graphics g) { UISettings.setupAntialiasing(g); Shape clip = null; int width = getWidth(); int height = getHeight(); if (isOpaque()) { // paint background for expanded row g.setColor(getBackground()); g.fillRect(0, 0, width, height); } if (myDurationWidth > 0) { width -= myDurationWidth + myDurationOffset; if (width > 0 && height > 0) { g.setColor(myDurationColor); g.setFont(RelativeFont.SMALL.derive(getFont())); g.drawString(myDurationText, width + myDurationOffset / 2, getTextBaseLine(g.getFontMetrics(), height)); clip = g.getClip(); g.clipRect(0, 0, width, height); } } super.paintComponent(g); // restore clip area if needed if (clip != null) g.setClip(clip); } } }
package com.intellij.ui.tabs.impl; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.rd.RdIdeaKt; import com.intellij.openapi.ui.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.openapi.wm.IdeGlassPaneUtil; import com.intellij.ui.ScreenUtil; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.switcher.QuickActionProvider; import com.intellij.ui.tabs.*; import com.intellij.ui.tabs.impl.singleRow.ScrollableSingleRowLayout; import com.intellij.ui.tabs.impl.singleRow.SingleRowLayout; import com.intellij.ui.tabs.impl.singleRow.SingleRowPassInfo; import com.intellij.ui.tabs.impl.table.TableLayout; import com.intellij.util.Alarm; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.ui.*; import com.intellij.util.ui.update.LazyUiDisposable; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.*; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.*; import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance; public class JBTabsImpl extends JComponent implements JBTabsEx, PropertyChangeListener, TimerListener, DataProvider, PopupMenuListener, Disposable, JBTabsPresentation, Queryable, UISettingsListener, QuickActionProvider, Accessible { @NonNls public static final Key<Integer> SIDE_TABS_SIZE_LIMIT_KEY = Key.create("SIDE_TABS_SIZE_LIMIT_KEY"); static final int MIN_TAB_WIDTH = JBUIScale.scale(75); static final int DEFAULT_MAX_TAB_WIDTH = JBUIScale.scale(300); private static final Comparator<TabInfo> ABC_COMPARATOR = (o1, o2) -> StringUtil.naturalCompare(o1.getText(), o2.getText()); private static final Logger LOG = Logger.getInstance(JBTabsImpl.class); @NotNull final ActionManager myActionManager; private final List<TabInfo> myVisibleInfos = new ArrayList<>(); private final Map<TabInfo, AccessibleTabPage> myInfo2Page = new HashMap<>(); private final Map<TabInfo, Integer> myHiddenInfos = new HashMap<>(); private TabInfo mySelectedInfo; public final Map<TabInfo, TabLabel> myInfo2Label = new HashMap<>(); public final Map<TabInfo, Toolbar> myInfo2Toolbar = new HashMap<>(); public Dimension myHeaderFitSize; private Insets myInnerInsets = JBUI.emptyInsets(); private final List<EventListener> myTabMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private final List<TabsListener> myTabListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private boolean myFocused; private Getter<? extends ActionGroup> myPopupGroup; private String myPopupPlace; TabInfo myPopupInfo; final DefaultActionGroup myNavigationActions; final PopupMenuListener myPopupListener; JPopupMenu myActivePopup; public boolean myHorizontalSide = true; private boolean mySideComponentOnTabs = true; private boolean mySideComponentBefore = true; private final int mySeparatorWidth = JBUI.scale(1); private DataProvider myDataProvider; private final WeakHashMap<Component, Component> myDeferredToRemove = new WeakHashMap<>(); private SingleRowLayout mySingleRowLayout; private final TableLayout myTableLayout = new TableLayout(this); private final TabsSideSplitter mySplitter = new TabsSideSplitter(this); private TabLayout myLayout; private LayoutPassInfo myLastLayoutPass; public boolean myForcedRelayout; private UiDecorator myUiDecorator; static final UiDecorator ourDefaultDecorator = new DefaultDecorator(); private boolean myPaintFocus; private boolean myHideTabs; @Nullable private Project myProject; private boolean myRequestFocusOnLastFocusedComponent; private boolean myListenerAdded; final Set<TabInfo> myAttractions = new HashSet<>(); private final Animator myAnimator; private List<TabInfo> myAllTabs; private IdeFocusManager myFocusManager; private static final boolean myAdjustBorders = true; private Set<JBTabsImpl> myNestedTabs = new HashSet<>(); private JBTabsImpl myParentTabs = null; boolean myAddNavigationGroup = true; private boolean myDisposed; private Color myActiveTabFillIn; private boolean myTabLabelActionsAutoHide; private final TabActionsAutoHideListener myTabActionsAutoHideListener = new TabActionsAutoHideListener(); private Disposable myTabActionsAutoHideListenerDisposable = Disposer.newDisposable(); private IdeGlassPane myGlassPane; @NonNls private static final String LAYOUT_DONE = "Layout.done"; @NonNls public static final String STRETCHED_BY_WIDTH = "Layout.stretchedByWidth"; private TimedDeadzone.Length myTabActionsMouseDeadzone = TimedDeadzone.DEFAULT; private long myRemoveDeferredRequest; private JBTabsPosition myPosition = JBTabsPosition.top; private final JBTabsBorder myBorder = createTabBorder(); private final BaseNavigationAction myNextAction; private final BaseNavigationAction myPrevAction; private boolean myTabDraggingEnabled; private DragHelper myDragHelper; private boolean myNavigationActionsEnabled = true; protected TabInfo myDropInfo; private int myDropInfoIndex; protected boolean myShowDropLocation = true; private TabInfo myOldSelection; private SelectionChangeHandler mySelectionChangeHandler; private Runnable myDeferredFocusRequest; private int myFirstTabOffset; private final TabPainterAdapter myTabPainterAdapter = createTabPainterAdapter(); protected final JBTabPainter myTabPainter = myTabPainterAdapter.getTabPainter(); private boolean myAlphabeticalMode; private boolean mySupportsCompression; private String myEmptyText; private boolean myMouseInsideTabsArea; private boolean myRemoveNotifyInProgress; protected JBTabsBorder createTabBorder() { return new JBDefaultTabsBorder(this); } public JBTabPainter getTabPainter() { return myTabPainter; } TabPainterAdapter getTabPainterAdapter() { return myTabPainterAdapter; } protected TabPainterAdapter createTabPainterAdapter() { return new DefaultTabPainterAdapter(JBTabPainter.getDEFAULT()); } private TabLabel tabLabelAtMouse; public JBTabsImpl(@NotNull Project project) { this(project, project); } private JBTabsImpl(@NotNull Project project, @NotNull Disposable parent) { this(project, ActionManager.getInstance(), IdeFocusManager.getInstance(project), parent); } public JBTabsImpl(@Nullable Project project, IdeFocusManager focusManager, @NotNull Disposable parent) { this(project, ActionManager.getInstance(), focusManager, parent); } public JBTabsImpl(@Nullable Project project, @NotNull ActionManager actionManager, IdeFocusManager focusManager, @NotNull Disposable parent) { myProject = project; myActionManager = actionManager; myFocusManager = focusManager != null ? focusManager : getGlobalInstance(); setOpaque(true); setBackground(myTabPainter.getBackgroundColor()); setBorder(myBorder); Disposer.register(parent, this); myNavigationActions = new DefaultActionGroup(); myNextAction = new SelectNextAction(this, myActionManager); myPrevAction = new SelectPreviousAction(this, myActionManager); myNavigationActions.add(myNextAction); myNavigationActions.add(myPrevAction); setUiDecorator(null); mySingleRowLayout = createSingleRowLayout(); myLayout = mySingleRowLayout; mySplitter.getDivider().setOpaque(false); myPopupListener = new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { disposePopupListener(); } @Override public void popupMenuCanceled(final PopupMenuEvent e) { disposePopupListener(); } }; addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (mySingleRowLayout.myLastSingRowLayout != null && mySingleRowLayout.myLastSingRowLayout.moreRect != null && mySingleRowLayout.myLastSingRowLayout.moreRect.contains(e.getPoint())) { showMorePopup(e); } } }); addMouseWheelListener(event -> { int units = event.getUnitsToScroll(); if (units == 0) return; if (mySingleRowLayout.myLastSingRowLayout != null) { mySingleRowLayout.scroll((int)(event.getPreciseWheelRotation() * mySingleRowLayout.getScrollUnitIncrement())); revalidateAndRepaint(false); } }); AWTEventListener listener = new AWTEventListener() { final Alarm afterScroll = new Alarm(JBTabsImpl.this); @Override public void eventDispatched(AWTEvent event) { if (mySingleRowLayout.myLastSingRowLayout == null) return; MouseEvent me = (MouseEvent)event; Point point = me.getPoint(); SwingUtilities.convertPointToScreen(point, me.getComponent()); Rectangle rect = getVisibleRect(); rect = rect.intersection(mySingleRowLayout.myLastSingRowLayout.tabRectangle); Point p = rect.getLocation(); SwingUtilities.convertPointToScreen(p, JBTabsImpl.this); rect.setLocation(p); boolean inside = rect.contains(point); if (inside != myMouseInsideTabsArea) { myMouseInsideTabsArea = inside; afterScroll.cancelAllRequests(); if (!inside) { afterScroll.addRequest(() -> { // here is no any "isEDT"-checks <== this task should be called in EDT <== // <== Alarm instance executes tasks in EDT <== used constructor of Alarm uses EDT for tasks by default if (!myMouseInsideTabsArea) { relayout(false, false); } }, 500); } } } }; Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_MOTION_EVENT_MASK); Disposer.register(this, () -> { Toolkit toolkit = Toolkit.getDefaultToolkit(); if (toolkit != null) { toolkit.removeAWTEventListener(listener); } }); myAnimator = new Animator("JBTabs Attractions", 2, 500, true) { @Override public void paintNow(final int frame, final int totalFrames, final int cycle) { repaintAttractions(); } }; setFocusTraversalPolicyProvider(true); setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() { @Override public Component getDefaultComponent(final Container aContainer) { return getToFocus(); } }); new LazyUiDisposable<JBTabsImpl>(parent, this, this) { @Override protected void initialize(@NotNull Disposable parent, @NotNull JBTabsImpl child, @Nullable Project project) { if (myProject == null && project != null) { myProject = project; } Disposer.register(child, myAnimator); Disposer.register(child, () -> removeTimerUpdate()); IdeGlassPane gp = IdeGlassPaneUtil.find(child); myTabActionsAutoHideListenerDisposable = Disposer.newDisposable("myTabActionsAutoHideListener"); Disposer.register(child, myTabActionsAutoHideListenerDisposable); gp.addMouseMotionPreprocessor(myTabActionsAutoHideListener, myTabActionsAutoHideListenerDisposable); myGlassPane = gp; UIUtil.addAwtListener(__ -> { if (mySingleRowLayout.myMorePopup != null) return; processFocusChange(); }, AWTEvent.FOCUS_EVENT_MASK, child); myDragHelper = new DragHelper(child); myDragHelper.start(); if (myProject != null && myFocusManager == getGlobalInstance()) { myFocusManager = IdeFocusManager.getInstance(myProject); } } }; UIUtil.putClientProperty( this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, (Iterable<JComponent>)() -> JBIterable.from(getVisibleInfos()).filter(Conditions.not(Conditions.is(mySelectedInfo))).transform( info -> info.getComponent()).iterator()); } public boolean isMouseInsideTabsArea() { return myMouseInsideTabsArea; } @Override public void uiSettingsChanged(UISettings uiSettings) { for (Map.Entry<TabInfo, TabLabel> entry : myInfo2Label.entrySet()) { entry.getKey().revalidate(); entry.getValue().updateActionLabelPosition(); } boolean oldHideTabsIfNeeded = mySingleRowLayout instanceof ScrollableSingleRowLayout; boolean newHideTabsIfNeeded = UISettings.getInstance().getHideTabsIfNeeded(); if (oldHideTabsIfNeeded != newHideTabsIfNeeded) { updateRowLayout(); } } private void updateRowLayout() { boolean wasSingleRow = isSingleRow(); mySingleRowLayout = createSingleRowLayout(); if (wasSingleRow) { myLayout = mySingleRowLayout; } relayout(true, true); } protected SingleRowLayout createSingleRowLayout() { return new ScrollableSingleRowLayout(this); } @Override public JBTabs setNavigationActionBinding(String prevActionId, String nextActionId) { if (myNextAction != null) { myNextAction.reconnect(nextActionId); } if (myPrevAction != null) { myPrevAction.reconnect(prevActionId); } return this; } public void setHovered(TabLabel label) { TabLabel old = tabLabelAtMouse; tabLabelAtMouse = label; if(old != null) { old.repaint(); } if(tabLabelAtMouse != null) { tabLabelAtMouse.repaint(); } } void unHover(TabLabel label) { if(tabLabelAtMouse == label) { tabLabelAtMouse = null; label.repaint(); } } protected boolean isHoveredTab(TabLabel label) { return label != null && label == tabLabelAtMouse; } protected boolean isActiveTabs(TabInfo info) { return UIUtil.isFocusAncestor(this); } @Override public boolean isEditorTabs() { return false; } public boolean supportsCompression() { return mySupportsCompression; } @Override public JBTabs setNavigationActionsEnabled(boolean enabled) { myNavigationActionsEnabled = enabled; return this; } @Override public final boolean isDisposed() { return myDisposed; } public void addNestedTabs(JBTabsImpl tabs) { myNestedTabs.add(tabs); tabs.myParentTabs = this; } public void removeNestedTabs(JBTabsImpl tabs) { myNestedTabs.remove(tabs); tabs.myParentTabs = null; } public static Image getComponentImage(TabInfo info) { JComponent cmp = info.getComponent(); BufferedImage img; if (cmp.isShowing()) { final int width = cmp.getWidth(); final int height = cmp.getHeight(); img = UIUtil.createImage(info.getComponent(), width > 0 ? width : 500, height > 0 ? height : 500, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); cmp.paint(g); } else { img = UIUtil.createImage(info.getComponent(), 500, 500, BufferedImage.TYPE_INT_ARGB); } return img; } @Override public void dispose() { myDisposed = true; mySelectedInfo = null; myDeferredFocusRequest = null; resetTabsCache(); myAttractions.clear(); myVisibleInfos.clear(); myUiDecorator = null; myActivePopup = null; myInfo2Label.clear(); myInfo2Page.clear(); myInfo2Toolbar.clear(); myTabListeners.clear(); myLastLayoutPass = null; if (myParentTabs != null) myParentTabs.removeNestedTabs(this); } void resetTabsCache() { ApplicationManager.getApplication().assertIsDispatchThread(); myAllTabs = null; } private void processFocusChange() { Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) { setFocused(false); return; } if (owner == this || SwingUtilities.isDescendingFrom(owner, this)) { setFocused(true); } else { setFocused(false); } } private void repaintAttractions() { boolean needsUpdate = false; for (TabInfo each : myVisibleInfos) { TabLabel eachLabel = myInfo2Label.get(each); needsUpdate |= eachLabel.repaintAttraction(); } if (needsUpdate) { relayout(true, false); } } @Override public void addNotify() { super.addNotify(); addTimerUpdate(); if (myDeferredFocusRequest != null) { final Runnable request = myDeferredFocusRequest; myDeferredFocusRequest = null; request.run(); } } @Override public void remove(int index) { if (myRemoveNotifyInProgress) { LOG.warn(new IllegalStateException("removeNotify in progress")); } super.remove(index); } @Override public void removeAll() { if (myRemoveNotifyInProgress) { LOG.warn(new IllegalStateException("removeNotify in progress")); } super.removeAll(); } @Override public void removeNotify() { try { myRemoveNotifyInProgress = true; super.removeNotify(); } finally { myRemoveNotifyInProgress = false; } setFocused(false); removeTimerUpdate(); if (ScreenUtil.isStandardAddRemoveNotify(this) && myGlassPane != null) { Disposer.dispose(myTabActionsAutoHideListenerDisposable); myTabActionsAutoHideListenerDisposable = Disposer.newDisposable(); myGlassPane = null; } } @Override public void processMouseEvent(MouseEvent e) { super.processMouseEvent(e); } private void addTimerUpdate() { if (!myListenerAdded) { myActionManager.addTimerListener(500, this); myListenerAdded = true; } } private void removeTimerUpdate() { if (myListenerAdded) { myActionManager.removeTimerListener(this); myListenerAdded = false; } } public void layoutComp(SingleRowPassInfo data, int deltaX, int deltaY, int deltaWidth, int deltaHeight) { JComponent hToolbar = data.hToolbar.get(); JComponent vToolbar = data.vToolbar.get(); if (hToolbar != null) { final int toolbarHeight = hToolbar.getPreferredSize().height; final int hSeparatorHeight = toolbarHeight > 0 ? 1 : 0; final Rectangle compRect = layoutComp(deltaX, toolbarHeight + hSeparatorHeight + deltaY, data.comp.get(), deltaWidth, deltaHeight); layout(hToolbar, compRect.x, compRect.y - toolbarHeight - hSeparatorHeight, compRect.width, toolbarHeight); } else if (vToolbar != null) { final int toolbarWidth = vToolbar.getPreferredSize().width; final int vSeparatorWidth = toolbarWidth > 0 ? 1 : 0; if (mySideComponentBefore) { final Rectangle compRect = layoutComp(toolbarWidth + vSeparatorWidth + deltaX, deltaY, data.comp.get(), deltaWidth, deltaHeight); layout(vToolbar, compRect.x - toolbarWidth - vSeparatorWidth, compRect.y, toolbarWidth, compRect.height); } else { final Rectangle compRect = layoutComp(new Rectangle(deltaX, deltaY, getWidth() - toolbarWidth - vSeparatorWidth, getHeight()), data.comp.get(), deltaWidth, deltaHeight); layout(vToolbar, compRect.x + compRect.width + vSeparatorWidth, compRect.y, toolbarWidth, compRect.height); } } else { layoutComp(deltaX, deltaY, data.comp.get(), deltaWidth, deltaHeight); } } public boolean isDropTarget(TabInfo info) { return myDropInfo != null && myDropInfo == info; } private void setDropInfoIndex(int dropInfoIndex) { myDropInfoIndex = dropInfoIndex; } public int getFirstTabOffset() { return myFirstTabOffset; } @Override public void setFirstTabOffset(int firstTabOffset) { myFirstTabOffset = firstTabOffset; } @Override public JBTabsPresentation setEmptyText(@Nullable String text) { myEmptyText = text; return this; } public int tabMSize() { return 20; } /** * TODO use {@link RdIdeaKt#childAtMouse(IdeGlassPane, Container)} */ @Deprecated class TabActionsAutoHideListener extends MouseMotionAdapter implements Weighted { private TabLabel myCurrentOverLabel; private Point myLastOverPoint; @Override public double getWeight() { return 1; } @Override public void mouseMoved(final MouseEvent e) { if (!myTabLabelActionsAutoHide) return; myLastOverPoint = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), JBTabsImpl.this); processMouseOver(); } void processMouseOver() { if (!myTabLabelActionsAutoHide) return; if (myLastOverPoint == null) return; if (myLastOverPoint.x >= 0 && myLastOverPoint.x < getWidth() && myLastOverPoint.y > 0 && myLastOverPoint.y < getHeight()) { final TabLabel label = myInfo2Label.get(_findInfo(myLastOverPoint, true)); if (label != null) { if (myCurrentOverLabel != null) { myCurrentOverLabel.toggleShowActions(false); } label.toggleShowActions(true); myCurrentOverLabel = label; return; } } if (myCurrentOverLabel != null) { myCurrentOverLabel.toggleShowActions(false); myCurrentOverLabel = null; } } } @Override public ModalityState getModalityState() { return ModalityState.stateForComponent(this); } @Override public void run() { updateTabActions(false); } @Override public void updateTabActions(final boolean validateNow) { final Ref<Boolean> changed = new Ref<>(Boolean.FALSE); for (final TabInfo eachInfo : myInfo2Label.keySet()) { final boolean changes = myInfo2Label.get(eachInfo).updateTabActions(); changed.set(changed.get().booleanValue() || changes); } if (changed.get()) { revalidateAndRepaint(); } } @Override public boolean canShowMorePopup() { final SingleRowPassInfo lastLayout = mySingleRowLayout.myLastSingRowLayout; return lastLayout != null && lastLayout.moreRect != null; } @Override public void showMorePopup(@Nullable final MouseEvent e) { final SingleRowPassInfo lastLayout = mySingleRowLayout.myLastSingRowLayout; if (lastLayout == null) { return; } mySingleRowLayout.myMorePopup = new JBPopupMenu(); for (final TabInfo each : getVisibleInfos()) { if (!mySingleRowLayout.isTabHidden(each)) continue; final JBMenuItem item = new JBMenuItem(each.getText(), each.getIcon()); item.setForeground(each.getDefaultForeground()); item.setBackground(each.getTabColor()); mySingleRowLayout.myMorePopup.add(item); item.addActionListener(__ -> select(each, true)); } mySingleRowLayout.myMorePopup.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { mySingleRowLayout.myMorePopup = null; } @Override public void popupMenuCanceled(final PopupMenuEvent e) { mySingleRowLayout.myMorePopup = null; } }); if (e != null) { mySingleRowLayout.myMorePopup.show(this, e.getX(), e.getY()); } else { final Rectangle rect = lastLayout.moreRect; if (rect != null) { mySingleRowLayout.myMorePopup.show(this, rect.x, rect.y + rect.height); } } } @Nullable private JComponent getToFocus() { final TabInfo info = getSelectedInfo(); if (info == null) return null; JComponent toFocus = null; if (isRequestFocusOnLastFocusedComponent() && info.getLastFocusOwner() != null && !isMyChildIsFocusedNow()) { toFocus = info.getLastFocusOwner(); } if (toFocus == null) { toFocus = info.getPreferredFocusableComponent(); if (toFocus == null) { return null; } final JComponent policyToFocus = myFocusManager.getFocusTargetFor(toFocus); if (policyToFocus != null) { toFocus = policyToFocus; } } return toFocus; } @Override public void requestFocus() { final JComponent toFocus = getToFocus(); if (toFocus != null) { getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(toFocus, true)); } else { getGlobalInstance().doWhenFocusSettlesDown(() -> super.requestFocus()); } } @Override public boolean requestFocusInWindow() { final JComponent toFocus = getToFocus(); return toFocus != null ? toFocus.requestFocusInWindow() : super.requestFocusInWindow(); } @Override @NotNull public TabInfo addTab(TabInfo info, int index) { return addTab(info, index, false, true); } @Override public TabInfo addTabSilently(TabInfo info, int index) { return addTab(info, index, false, false); } private TabInfo addTab(TabInfo info, int index, boolean isDropTarget, boolean fireEvents) { if (!isDropTarget && getTabs().contains(info)) { return getTabs().get(getTabs().indexOf(info)); } info.getChangeSupport().addPropertyChangeListener(this); final TabLabel label = createTabLabel(info); Disposer.register(this, label); myInfo2Label.put(info, label); myInfo2Page.put(info, new AccessibleTabPage(info)); if (!isDropTarget) { if (index < 0 || index > myVisibleInfos.size() - 1) { myVisibleInfos.add(info); } else { myVisibleInfos.add(index, info); } } resetTabsCache(); updateText(info); updateIcon(info); updateSideComponent(info); updateTabActions(info); add(label); adjust(info); updateAll(false); if (info.isHidden()) { updateHiding(); } if (!isDropTarget && fireEvents) { if (getTabCount() == 1) { fireBeforeSelectionChanged(null, info); fireSelectionChanged(null, info); } } revalidateAndRepaint(false); return info; } protected TabLabel createTabLabel(TabInfo info) { return new TabLabel(this, info); } @Override @NotNull public TabInfo addTab(TabInfo info) { return addTab(info, -1); } @Override public TabLabel getTabLabel(TabInfo info) { return myInfo2Label.get(info); } @Nullable public ActionGroup getPopupGroup() { return myPopupGroup != null ? myPopupGroup.get() : null; } String getPopupPlace() { return myPopupPlace; } @Override @NotNull public JBTabs setPopupGroup(@NotNull final ActionGroup popupGroup, @NotNull String place, final boolean addNavigationGroup) { return setPopupGroup(() -> popupGroup, place, addNavigationGroup); } @Override @NotNull public JBTabs setPopupGroup(@NotNull final Getter<? extends ActionGroup> popupGroup, @NotNull final String place, final boolean addNavigationGroup) { myPopupGroup = popupGroup; myPopupPlace = place; myAddNavigationGroup = addNavigationGroup; return this; } private void updateAll(final boolean forcedRelayout) { mySelectedInfo = getSelectedInfo(); updateContainer(forcedRelayout, false); removeDeferred(); updateListeners(); updateTabActions(false); updateEnabling(); } private boolean isMyChildIsFocusedNow() { final Component owner = getFocusOwner(); if (owner == null) return false; if (mySelectedInfo != null) { if (!SwingUtilities.isDescendingFrom(owner, mySelectedInfo.getComponent())) return false; } return SwingUtilities.isDescendingFrom(owner, this); } @Nullable private static JComponent getFocusOwner() { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); return (JComponent)(owner instanceof JComponent ? owner : null); } @Override @NotNull public ActionCallback select(@NotNull TabInfo info, boolean requestFocus) { return _setSelected(info, requestFocus); } @NotNull private ActionCallback _setSelected(final TabInfo info, final boolean requestFocus) { if (!isEnabled()) { return ActionCallback.REJECTED; } if (mySelectionChangeHandler != null) { return mySelectionChangeHandler.execute(info, requestFocus, new ActiveRunnable() { @NotNull @Override public ActionCallback run() { return executeSelectionChange(info, requestFocus); } }); } return executeSelectionChange(info, requestFocus); } @NotNull private ActionCallback executeSelectionChange(TabInfo info, boolean requestFocus) { if (mySelectedInfo != null && mySelectedInfo.equals(info)) { if (!requestFocus) { return ActionCallback.DONE; } else { Component owner = myFocusManager.getFocusOwner(); JComponent c = info.getComponent(); if (c != null && owner != null) { if (c == owner || SwingUtilities.isDescendingFrom(owner, c)) { return ActionCallback.DONE; } } return requestFocus(getToFocus()); } } if (myRequestFocusOnLastFocusedComponent && mySelectedInfo != null) { if (isMyChildIsFocusedNow()) { mySelectedInfo.setLastFocusOwner(getFocusOwner()); } } TabInfo oldInfo = mySelectedInfo; mySelectedInfo = info; final TabInfo newInfo = getSelectedInfo(); if (myRequestFocusOnLastFocusedComponent && newInfo != null) { newInfo.setLastFocusOwner(null); } TabLabel label = myInfo2Label.get(info); if(label != null) { setComponentZOrder(label, 0); } fireBeforeSelectionChanged(oldInfo, newInfo); boolean oldValue = myMouseInsideTabsArea; try { updateContainer(false, true); } finally { myMouseInsideTabsArea = oldValue; } fireSelectionChanged(oldInfo, newInfo); if (requestFocus) { final JComponent toFocus = getToFocus(); if (myProject != null && toFocus != null) { final ActionCallback result = new ActionCallback(); requestFocus(toFocus).doWhenProcessed(() -> { if (myDisposed) { result.setRejected(); } else { removeDeferred().notifyWhenDone(result); } }); return result; } else { requestFocus(); return removeDeferred(); } } else { return removeDeferred(); } } private void fireBeforeSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) { if (oldInfo != newInfo) { myOldSelection = oldInfo; try { for (TabsListener eachListener : myTabListeners) { eachListener.beforeSelectionChanged(oldInfo, newInfo); } } finally { myOldSelection = null; } } } private void fireSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) { if (oldInfo != newInfo) { for (TabsListener eachListener : myTabListeners) { if (eachListener != null) { eachListener.selectionChanged(oldInfo, newInfo); } } } } void fireTabsMoved() { for (TabsListener eachListener : myTabListeners) { if (eachListener != null) { eachListener.tabsMoved(); } } } private void fireTabRemoved(@NotNull TabInfo info) { for (TabsListener eachListener : myTabListeners) { if (eachListener != null) { eachListener.tabRemoved(info); } } } @NotNull private ActionCallback requestFocus(final JComponent toFocus) { if (toFocus == null) return ActionCallback.DONE; if (isShowing()) { return myFocusManager.requestFocusInProject(toFocus, myProject); } return ActionCallback.REJECTED; } @NotNull private ActionCallback removeDeferred() { if (myDeferredToRemove.isEmpty()) { return ActionCallback.DONE; } final ActionCallback callback = new ActionCallback(); final long executionRequest = ++myRemoveDeferredRequest; final Runnable onDone = () -> { if (myRemoveDeferredRequest == executionRequest) { removeDeferredNow(); } callback.setDone(); }; myFocusManager.doWhenFocusSettlesDown(onDone); return callback; } private void queueForRemove(Component c) { if (c instanceof JComponent) { addToDeferredRemove(c); } else { remove(c); } } private void unqueueFromRemove(Component c) { myDeferredToRemove.remove(c); } private void removeDeferredNow() { for (Component each : myDeferredToRemove.keySet()) { if (each != null && each.getParent() == this) { remove(each); } } myDeferredToRemove.clear(); } @Override public void propertyChange(final PropertyChangeEvent evt) { final TabInfo tabInfo = (TabInfo)evt.getSource(); if (TabInfo.ACTION_GROUP.equals(evt.getPropertyName())) { updateSideComponent(tabInfo); relayout(false, false); } else if (TabInfo.COMPONENT.equals(evt.getPropertyName())) { relayout(true, false); } else if (TabInfo.TEXT.equals(evt.getPropertyName())) { updateText(tabInfo); } else if (TabInfo.ICON.equals(evt.getPropertyName())) { updateIcon(tabInfo); } else if (TabInfo.TAB_COLOR.equals(evt.getPropertyName())) { revalidateAndRepaint(); } else if (TabInfo.ALERT_STATUS.equals(evt.getPropertyName())) { boolean start = ((Boolean)evt.getNewValue()).booleanValue(); updateAttraction(tabInfo, start); } else if (TabInfo.TAB_ACTION_GROUP.equals(evt.getPropertyName())) { updateTabActions(tabInfo); relayout(false, false); } else if (TabInfo.HIDDEN.equals(evt.getPropertyName())) { updateHiding(); relayout(false, false); } else if (TabInfo.ENABLED.equals(evt.getPropertyName())) { updateEnabling(); } } private void updateEnabling() { final List<TabInfo> all = getTabs(); for (TabInfo each : all) { final TabLabel eachLabel = myInfo2Label.get(each); eachLabel.setTabEnabled(each.isEnabled()); } final TabInfo selected = getSelectedInfo(); if (selected != null && !selected.isEnabled()) { final TabInfo toSelect = getToSelectOnRemoveOf(selected); if (toSelect != null) { select(toSelect, myFocusManager.getFocusedDescendantFor(this) != null); } } } private void updateHiding() { boolean update = false; Iterator<TabInfo> visible = myVisibleInfos.iterator(); while (visible.hasNext()) { TabInfo each = visible.next(); if (each.isHidden() && !myHiddenInfos.containsKey(each)) { myHiddenInfos.put(each, myVisibleInfos.indexOf(each)); visible.remove(); update = true; } } Iterator<TabInfo> hidden = myHiddenInfos.keySet().iterator(); while (hidden.hasNext()) { TabInfo each = hidden.next(); if (!each.isHidden() && myHiddenInfos.containsKey(each)) { myVisibleInfos.add(getIndexInVisibleArray(each), each); hidden.remove(); update = true; } } if (update) { resetTabsCache(); if (mySelectedInfo != null && myHiddenInfos.containsKey(mySelectedInfo)) { mySelectedInfo = getToSelectOnRemoveOf(mySelectedInfo); } updateAll(true); } } private int getIndexInVisibleArray(TabInfo each) { Integer info = myHiddenInfos.get(each); int index = info == null ? myVisibleInfos.size() : info.intValue(); if (index > myVisibleInfos.size()) { index = myVisibleInfos.size(); } if (index < 0) { index = 0; } return index; } private void updateIcon(final TabInfo tabInfo) { myInfo2Label.get(tabInfo).setIcon(tabInfo.getIcon()); revalidateAndRepaint(); } public void revalidateAndRepaint() { revalidateAndRepaint(true); } protected void revalidateAndRepaint(final boolean layoutNow) { if (myVisibleInfos.isEmpty()) { setOpaque(false); Component nonOpaque = UIUtil.findUltimateParent(this); if (getParent() != null) { final Rectangle toRepaint = SwingUtilities.convertRectangle(getParent(), getBounds(), nonOpaque); nonOpaque.repaint(toRepaint.x, toRepaint.y, toRepaint.width, toRepaint.height); } } else { setOpaque(true); } if (layoutNow) { validate(); } else { revalidate(); } repaint(); } private void updateAttraction(final TabInfo tabInfo, boolean start) { if (start) { myAttractions.add(tabInfo); } else { myAttractions.remove(tabInfo); tabInfo.setBlinkCount(0); } if (start && !myAnimator.isRunning()) { myAnimator.resume(); } else if (!start && myAttractions.isEmpty()) { myAnimator.suspend(); repaintAttractions(); } } private void updateText(final TabInfo tabInfo) { final TabLabel label = myInfo2Label.get(tabInfo); label.setText(tabInfo.getColoredText()); label.setToolTipText(tabInfo.getTooltipText()); revalidateAndRepaint(); } private void updateSideComponent(final TabInfo tabInfo) { final Toolbar old = myInfo2Toolbar.get(tabInfo); if (old != null) { remove(old); } final Toolbar toolbar = createToolbarComponent(tabInfo); myInfo2Toolbar.put(tabInfo, toolbar); add(toolbar); } private void updateTabActions(final TabInfo info) { myInfo2Label.get(info).setTabActions(info.getTabLabelActions()); } @Override @Nullable public TabInfo getSelectedInfo() { if (myOldSelection != null) return myOldSelection; if (!myVisibleInfos.contains(mySelectedInfo)) { mySelectedInfo = null; } return mySelectedInfo != null ? mySelectedInfo : !myVisibleInfos.isEmpty() ? myVisibleInfos.get(0) : null; } @Override @Nullable public TabInfo getToSelectOnRemoveOf(TabInfo info) { if (!myVisibleInfos.contains(info)) return null; if (mySelectedInfo != info) return null; if (myVisibleInfos.size() == 1) return null; int index = getVisibleInfos().indexOf(info); TabInfo result = null; if (index > 0) { result = findEnabledBackward(index, false); } if (result == null) { result = findEnabledForward(index, false); } return result; } @Nullable TabInfo findEnabledForward(int from, boolean cycle) { if (from < 0) return null; int index = from; List<TabInfo> infos = getVisibleInfos(); while (true) { index++; if (index == infos.size()) { if (!cycle) break; index = 0; } if (index == from) break; final TabInfo each = infos.get(index); if (each.isEnabled()) return each; } return null; } public boolean isAlphabeticalMode() { return myAlphabeticalMode; } @Nullable TabInfo findEnabledBackward(int from, boolean cycle) { if (from < 0) return null; int index = from; List<TabInfo> infos = getVisibleInfos(); while (true) { index if (index == -1) { if (!cycle) break; index = infos.size() - 1; } if (index == from) break; final TabInfo each = infos.get(index); if (each.isEnabled()) return each; } return null; } private Toolbar createToolbarComponent(final TabInfo tabInfo) { return new Toolbar(this, tabInfo); } @Override @NotNull public TabInfo getTabAt(final int tabIndex) { return getTabs().get(tabIndex); } @Override @NotNull public List<TabInfo> getTabs() { ApplicationManager.getApplication().assertIsDispatchThread(); if (myAllTabs != null) return myAllTabs; ArrayList<TabInfo> result = new ArrayList<>(myVisibleInfos); for (TabInfo each : myHiddenInfos.keySet()) { result.add(getIndexInVisibleArray(each), each); } if (isAlphabeticalMode()) { Collections.sort(result, ABC_COMPARATOR); } myAllTabs = result; return result; } @Override public TabInfo getTargetInfo() { return myPopupInfo != null ? myPopupInfo : getSelectedInfo(); } @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { resetPopup(); } @Override public void popupMenuCanceled(final PopupMenuEvent e) { resetPopup(); } private void resetPopup() { //todo [kirillk] dirty hack, should rely on ActionManager to understand that menu item was either chosen on or cancelled SwingUtilities.invokeLater(() -> { // No need to reset popup info if a new popup has been already opened and myPopupInfo refers to the corresponding info. if (myActivePopup == null) { myPopupInfo = null; } }); } @Override public void setPaintBlocked(boolean blocked, final boolean takeSnapshot) { } private void addToDeferredRemove(final Component c) { if (!myDeferredToRemove.containsKey(c)) { myDeferredToRemove.put(c, c); } } @Override @NotNull public JBTabsPresentation setToDrawBorderIfTabsHidden(final boolean toDrawBorderIfTabsHidden) { return this; } @Override @NotNull public JBTabs getJBTabs() { return this; } public static class Toolbar extends JPanel { public Toolbar(JBTabsImpl tabs, TabInfo info) { setLayout(new BorderLayout()); final ActionGroup group = info.getGroup(); final JComponent side = info.getSideComponent(); if (group != null) { final String place = info.getPlace(); ActionToolbar toolbar = tabs.myActionManager.createActionToolbar(place != null ? place : "JBTabs", group, tabs.myHorizontalSide); toolbar.setTargetComponent(info.getActionsContextComponent()); final JComponent actionToolbar = toolbar.getComponent(); add(actionToolbar, BorderLayout.CENTER); } if (side != null) { if (group != null) { add(side, BorderLayout.EAST); } else { add(side, BorderLayout.CENTER); } } UIUtil.uiTraverser(this).forEach(c -> c.setFocusable(false)); } public boolean isEmpty() { return getComponentCount() == 0; } } @Override public void doLayout() { try { myHeaderFitSize = computeHeaderFitSize(); final Collection<TabLabel> labels = myInfo2Label.values(); for (TabLabel each : labels) { each.setTabActionsAutoHide(myTabLabelActionsAutoHide); } List<TabInfo> visible = new ArrayList<>(getVisibleInfos()); if (myDropInfo != null && !visible.contains(myDropInfo) && myShowDropLocation) { if (getDropInfoIndex() >= 0 && getDropInfoIndex() < visible.size()) { visible.add(getDropInfoIndex(), myDropInfo); } else { visible.add(myDropInfo); } } if (isSingleRow()) { mySingleRowLayout.scrollSelectionInView(); myLastLayoutPass = mySingleRowLayout.layoutSingleRow(visible); myTableLayout.myLastTableLayout = null; OnePixelDivider divider = mySplitter.getDivider(); if (divider.getParent() == this) { int location = getTabsPosition() == JBTabsPosition.left ? mySingleRowLayout.myLastSingRowLayout.tabRectangle.width : getWidth() - mySingleRowLayout.myLastSingRowLayout.tabRectangle.width; divider.setBounds(location, 0, 1, getHeight()); } } else { myLastLayoutPass = myTableLayout.layoutTable(visible); mySingleRowLayout.myLastSingRowLayout = null; } moveDraggedTabLabel(); myTabActionsAutoHideListener.processMouseOver(); } finally { myForcedRelayout = false; } applyResetComponents(); } void moveDraggedTabLabel() { if (myDragHelper != null && myDragHelper.myDragRec != null) { final TabLabel selectedLabel = myInfo2Label.get(getSelectedInfo()); if (selectedLabel != null) { final Rectangle bounds = selectedLabel.getBounds(); if (isHorizontalTabs()) { selectedLabel.setBounds(myDragHelper.myDragRec.x, bounds.y, bounds.width, bounds.height); } else { selectedLabel.setBounds(bounds.x, myDragHelper.myDragRec.y, bounds.width, bounds.height); } } } } private Dimension computeHeaderFitSize() { final Max max = computeMaxSize(); if (myPosition == JBTabsPosition.top || myPosition == JBTabsPosition.bottom) { return new Dimension(getSize().width, myHorizontalSide ? Math.max(max.myLabel.height, max.myToolbar.height) : max.myLabel.height); } return new Dimension(max.myLabel.width + (myHorizontalSide ? 0 : max.myToolbar.width), getSize().height); } public Rectangle layoutComp(int componentX, int componentY, final JComponent comp, int deltaWidth, int deltaHeight) { return layoutComp(new Rectangle(componentX, componentY, getWidth(), getHeight()), comp, deltaWidth, deltaHeight); } public Rectangle layoutComp(final Rectangle bounds, final JComponent comp, int deltaWidth, int deltaHeight) { final Insets insets = getLayoutInsets(); final Insets inner = getInnerInsets(); int x = insets.left + bounds.x + inner.left; int y = insets.top + bounds.y + inner.top; int width = bounds.width - insets.left - insets.right - bounds.x - inner.left - inner.right; int height = bounds.height - insets.top - insets.bottom - bounds.y - inner.top - inner.bottom; if (!isHideTabs()) { width += deltaWidth; height += deltaHeight; } return layout(comp, x, y, width, height); } @Override public JBTabsPresentation setInnerInsets(final Insets innerInsets) { myInnerInsets = innerInsets; return this; } private Insets getInnerInsets() { return myInnerInsets; } public Insets getLayoutInsets() { return myBorder.getEffectiveBorder(); } public int getToolbarInset() { return getArcSize() + 1; } public void resetLayout(boolean resetLabels) { for (TabInfo each : myVisibleInfos) { reset(each, resetLabels); } if (myDropInfo != null) { reset(myDropInfo, resetLabels); } for (TabInfo each : myHiddenInfos.keySet()) { reset(each, resetLabels); } for (Component eachDeferred : myDeferredToRemove.keySet()) { resetLayout((JComponent)eachDeferred); } } private void reset(final TabInfo each, final boolean resetLabels) { final JComponent c = each.getComponent(); if (c != null) { resetLayout(c); } resetLayout(myInfo2Toolbar.get(each)); if (resetLabels) { resetLayout(myInfo2Label.get(each)); } } private static int getArcSize() { return 4; } protected JBTabsPosition getPosition() { return myPosition; } /** * @deprecated You should implement {@link JBTabsBorder} interface */ @Deprecated protected void doPaintBackground(Graphics2D g2d, Rectangle clip) { } @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); if (myVisibleInfos.isEmpty()) { if (myEmptyText != null) { UISettings.setupAntialiasing(g); UIUtil.drawCenteredString((Graphics2D)g, getBounds(), myEmptyText); } return; } myTabPainter.fillBackground((Graphics2D)g, new Rectangle(0, 0, getWidth(), getHeight())); drawBorder(g); drawToolbarSeparator(g); } private void drawToolbarSeparator(Graphics g) { Toolbar toolbar = myInfo2Toolbar.get(getSelectedInfo()); if (toolbar != null && toolbar.getParent() == this && !mySideComponentOnTabs && !myHorizontalSide && isHideTabs()) { Rectangle bounds = toolbar.getBounds(); if (bounds.width > 0) { if (mySideComponentBefore) { getTabPainter().paintBorderLine((Graphics2D)g, mySeparatorWidth, new Point(bounds.x + bounds.width, bounds.y), new Point(bounds.x + bounds.width, bounds.y + bounds.height)); } else { getTabPainter().paintBorderLine((Graphics2D)g, mySeparatorWidth, new Point(bounds.x - mySeparatorWidth, bounds.y), new Point(bounds.x - mySeparatorWidth, bounds.y + bounds.height)); } } } } protected TabLabel getSelectedLabel() { return myInfo2Label.get(getSelectedInfo()); } protected List<TabInfo> getVisibleInfos() { if (!isAlphabeticalMode()) { return myVisibleInfos; } else { List<TabInfo> sortedCopy = new ArrayList<>(myVisibleInfos); Collections.sort(sortedCopy, ABC_COMPARATOR); return sortedCopy; } } protected LayoutPassInfo getLastLayoutPass() { return myLastLayoutPass; } public static int getSelectionTabVShift() { return 2; } private boolean isNavigationVisible() { return myVisibleInfos.size() > 1; } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @Override protected void paintChildren(final Graphics g) { super.paintChildren(g); mySingleRowLayout.myMoreIcon.paintIcon(this, g); } protected void drawBorder(Graphics g) { if (!isHideTabs()) { myBorder.paintBorder(this, g, 0, 0, getWidth(), getHeight()); } } private Max computeMaxSize() { Max max = new Max(); for (TabInfo eachInfo : myVisibleInfos) { final TabLabel label = myInfo2Label.get(eachInfo); max.myLabel.height = Math.max(max.myLabel.height, label.getPreferredSize().height); max.myLabel.width = Math.max(max.myLabel.width, label.getPreferredSize().width); final Toolbar toolbar = myInfo2Toolbar.get(eachInfo); if (myLayout.isSideComponentOnTabs() && toolbar != null && !toolbar.isEmpty()) { max.myToolbar.height = Math.max(max.myToolbar.height, toolbar.getPreferredSize().height); max.myToolbar.width = Math.max(max.myToolbar.width, toolbar.getPreferredSize().width); } } if (getTabsPosition().isSide()) { if (mySplitter.getSideTabsLimit() > 0) { max.myLabel.width = Math.min(max.myLabel.width, mySplitter.getSideTabsLimit()); } } max.myToolbar.height++; return max; } @Override public Dimension getMinimumSize() { return computeSize(component -> component.getMinimumSize(), 1); } @Override public Dimension getPreferredSize() { return computeSize(component -> component.getPreferredSize(), 3); } private Dimension computeSize(Function<? super JComponent, ? extends Dimension> transform, int tabCount) { Dimension size = new Dimension(); for (TabInfo each : myVisibleInfos) { final JComponent c = each.getComponent(); if (c != null) { final Dimension eachSize = transform.fun(c); size.width = Math.max(eachSize.width, size.width); size.height = Math.max(eachSize.height, size.height); } } addHeaderSize(size, tabCount); return size; } private void addHeaderSize(Dimension size, final int tabsCount) { Dimension header = computeHeaderPreferredSize(tabsCount); final boolean horizontal = getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom; if (horizontal) { size.height += header.height; size.width = Math.max(size.width, header.width); } else { size.height += Math.max(size.height, header.height); size.width += header.width; } final Insets insets = getLayoutInsets(); size.width += insets.left + insets.right + 1; size.height += insets.top + insets.bottom + 1; } private Dimension computeHeaderPreferredSize(int tabsCount) { final Iterator<TabInfo> infos = myInfo2Label.keySet().iterator(); Dimension size = new Dimension(); int currentTab = 0; final boolean horizontal = getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom; while (infos.hasNext()) { final boolean canGrow = currentTab < tabsCount; TabInfo eachInfo = infos.next(); final TabLabel eachLabel = myInfo2Label.get(eachInfo); final Dimension eachPrefSize = eachLabel.getPreferredSize(); if (horizontal) { if (canGrow) { size.width += eachPrefSize.width; } size.height = Math.max(size.height, eachPrefSize.height); } else { size.width = Math.max(size.width, eachPrefSize.width); if (canGrow) { size.height += eachPrefSize.height; } } currentTab++; } if (horizontal) { size.height += myBorder.getThickness(); } else { size.width += myBorder.getThickness(); } return size; } @Override public int getTabCount() { return getTabs().size(); } @Override @NotNull public JBTabsPresentation getPresentation() { return this; } @Override @NotNull public ActionCallback removeTab(final TabInfo info) { return removeTab(info, null, true); } @Override @NotNull public ActionCallback removeTab(final TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus) { return removeTab(info, forcedSelectionTransfer, transferFocus, false); } @NotNull private ActionCallback removeTab(TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus, boolean isDropTarget) { if (myRemoveNotifyInProgress) { LOG.warn(new IllegalStateException("removeNotify in progress")); } if (myPopupInfo == info) myPopupInfo = null; if (!isDropTarget) { if (info == null || !getTabs().contains(info)) return ActionCallback.DONE; } if (isDropTarget && myLastLayoutPass != null) { myLastLayoutPass.myVisibleInfos.remove(info); } final ActionCallback result = new ActionCallback(); TabInfo toSelect; if (forcedSelectionTransfer == null) { toSelect = getToSelectOnRemoveOf(info); } else { assert myVisibleInfos.contains(forcedSelectionTransfer) : "Cannot find tab for selection transfer, tab=" + forcedSelectionTransfer; toSelect = forcedSelectionTransfer; } if (toSelect != null) { boolean clearSelection = info.equals(mySelectedInfo); processRemove(info, false); if (clearSelection) { mySelectedInfo = info; } _setSelected(toSelect, transferFocus).doWhenProcessed(() -> removeDeferred().notifyWhenDone(result)); } else { processRemove(info, true); removeDeferred().notifyWhenDone(result); } if (myVisibleInfos.isEmpty()) { removeDeferredNow(); } revalidateAndRepaint(true); fireTabRemoved(info); return result; } private void processRemove(final TabInfo info, boolean forcedNow) { remove(myInfo2Label.get(info)); remove(myInfo2Toolbar.get(info)); JComponent tabComponent = info.getComponent(); if (!isToDeferRemoveForLater(tabComponent) || forcedNow) { remove(tabComponent); } else { queueForRemove(tabComponent); } TabLabel tabLabel = myInfo2Label.get(info); if (tabLabel != null) { Disposer.dispose(tabLabel); } myVisibleInfos.remove(info); myHiddenInfos.remove(info); myInfo2Label.remove(info); myInfo2Page.remove(info); myInfo2Toolbar.remove(info); resetTabsCache(); updateAll(false); } @Nullable @Override public TabInfo findInfo(Component component) { for (TabInfo each : getTabs()) { if (each.getComponent() == component) return each; } return null; } @Override public TabInfo findInfo(MouseEvent event) { final Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), this); return _findInfo(point, false); } @Override public TabInfo findInfo(final Object object) { for (int i = 0; i < getTabCount(); i++) { final TabInfo each = getTabAt(i); final Object eachObject = each.getObject(); if (eachObject != null && eachObject.equals(object)) return each; } return null; } @Nullable private TabInfo _findInfo(final Point point, boolean labelsOnly) { Component component = findComponentAt(point); if (component == null) return null; while (component != this || component != null) { if (component instanceof TabLabel) { return ((TabLabel)component).getInfo(); } if (!labelsOnly) { final TabInfo info = findInfo(component); if (info != null) return info; } if (component == null) break; component = component.getParent(); } return null; } @Override public void removeAllTabs() { for (TabInfo each : getTabs()) { removeTab(each); } } private static class Max { final Dimension myLabel = new Dimension(); final Dimension myToolbar = new Dimension(); } private void updateContainer(boolean forced, final boolean layoutNow) { if (myProject != null && !myProject.isOpen() && !myProject.isDefault()) return; for (TabInfo each : new ArrayList<>(myVisibleInfos)) { final JComponent eachComponent = each.getComponent(); if (getSelectedInfo() == each && getSelectedInfo() != null) { unqueueFromRemove(eachComponent); final Container parent = eachComponent.getParent(); if (parent != null && parent != this) { parent.remove(eachComponent); } if (eachComponent.getParent() == null) { add(eachComponent); } } else { if (eachComponent.getParent() == null) continue; if (isToDeferRemoveForLater(eachComponent)) { queueForRemove(eachComponent); } else { remove(eachComponent); } } } mySingleRowLayout.scrollSelectionInView(); relayout(forced, layoutNow); } @Override protected void addImpl(final Component comp, final Object constraints, final int index) { unqueueFromRemove(comp); if (comp instanceof TabLabel) { ((TabLabel)comp).apply(myUiDecorator != null ? myUiDecorator.getDecoration() : ourDefaultDecorator.getDecoration()); } super.addImpl(comp, constraints, index); } private static boolean isToDeferRemoveForLater(JComponent c) { return c.getRootPane() != null; } void relayout(boolean forced, final boolean layoutNow) { if (!myForcedRelayout) { myForcedRelayout = forced; } revalidateAndRepaint(layoutNow); } public int getBorderThickness() { return myBorder.getThickness(); } @Override @NotNull public JBTabs addTabMouseListener(@NotNull MouseListener listener) { removeListeners(); myTabMouseListeners.add(listener); addListeners(); return this; } @Override @NotNull public JComponent getComponent() { return this; } private void addListeners() { for (TabInfo eachInfo : myVisibleInfos) { final TabLabel label = myInfo2Label.get(eachInfo); for (EventListener eachListener : myTabMouseListeners) { if (eachListener instanceof MouseListener) { label.addMouseListener((MouseListener)eachListener); } else if (eachListener instanceof MouseMotionListener) { label.addMouseMotionListener((MouseMotionListener)eachListener); } else { assert false; } } } } private void removeListeners() { for (TabInfo eachInfo : myVisibleInfos) { final TabLabel label = myInfo2Label.get(eachInfo); for (EventListener eachListener : myTabMouseListeners) { if (eachListener instanceof MouseListener) { label.removeMouseListener((MouseListener)eachListener); } else if (eachListener instanceof MouseMotionListener) { label.removeMouseMotionListener((MouseMotionListener)eachListener); } else { assert false; } } } } private void updateListeners() { removeListeners(); addListeners(); } @Override public JBTabs addListener(@NotNull TabsListener listener) { myTabListeners.add(listener); return this; } @Override public JBTabs setSelectionChangeHandler(SelectionChangeHandler handler) { mySelectionChangeHandler = handler; return this; } public void setFocused(final boolean focused) { if (myFocused == focused) return; myFocused = focused; if (myPaintFocus) { repaint(); } } @Override public int getIndexOf(@Nullable final TabInfo tabInfo) { return getVisibleInfos().indexOf(tabInfo); } @Override public boolean isHideTabs() { return myHideTabs; } @Override public void setHideTabs(final boolean hideTabs) { if (isHideTabs() == hideTabs) return; myHideTabs = hideTabs; relayout(true, false); } @Override public JBTabsPresentation setPaintBorder(int top, int left, int right, int bottom) { return this; } @Override public JBTabsPresentation setTabSidePaintBorder(int size) { return this; } @Override @NotNull public JBTabsPresentation setActiveTabFillIn(@Nullable final Color color) { if (!isChanged(myActiveTabFillIn, color)) return this; myActiveTabFillIn = color; revalidateAndRepaint(false); return this; } private static boolean isChanged(Object oldObject, Object newObject) { return !Comparing.equal(oldObject, newObject); } @Override @NotNull public JBTabsPresentation setTabLabelActionsAutoHide(final boolean autoHide) { if (myTabLabelActionsAutoHide != autoHide) { myTabLabelActionsAutoHide = autoHide; revalidateAndRepaint(false); } return this; } @Override public JBTabsPresentation setFocusCycle(final boolean root) { setFocusCycleRoot(root); return this; } @Override public JBTabsPresentation setPaintFocus(final boolean paintFocus) { myPaintFocus = paintFocus; return this; } private abstract static class BaseNavigationAction extends AnAction { private final ShadowAction myShadow; @NotNull private final ActionManager myActionManager; private final JBTabsImpl myTabs; BaseNavigationAction(@NotNull String copyFromID, @NotNull JBTabsImpl tabs, @NotNull ActionManager mgr) { myActionManager = mgr; myTabs = tabs; myShadow = new ShadowAction(this, myActionManager.getAction(copyFromID), tabs, tabs); setEnabledInModalContext(true); } @Override public final void update(@NotNull final AnActionEvent e) { JBTabsImpl tabs = (JBTabsImpl)e.getData(NAVIGATION_ACTIONS_KEY); e.getPresentation().setVisible(tabs != null); if (tabs == null) return; tabs = findNavigatableTabs(tabs); e.getPresentation().setEnabled(tabs != null); if (tabs != null) { _update(e, tabs, tabs.getVisibleInfos().indexOf(tabs.getSelectedInfo())); } } @Nullable JBTabsImpl findNavigatableTabs(JBTabsImpl tabs) { // The debugger UI contains multiple nested JBTabsImpl, where the innermost JBTabsImpl has only one tab. In this case, // the action should target the outer JBTabsImpl. if (tabs == null || tabs != myTabs) { return null; } if (tabs.isNavigatable()) { return tabs; } Component c = tabs.getParent(); while (c != null) { if (c instanceof JBTabsImpl && ((JBTabsImpl)c).isNavigatable()) { return (JBTabsImpl)c; } c = c.getParent(); } return null; } public void reconnect(String actionId) { myShadow.reconnect(myActionManager.getAction(actionId)); } protected abstract void _update(AnActionEvent e, final JBTabsImpl tabs, int selectedIndex); @Override public final void actionPerformed(@NotNull final AnActionEvent e) { JBTabsImpl tabs = (JBTabsImpl)e.getData(NAVIGATION_ACTIONS_KEY); tabs = findNavigatableTabs(tabs); if (tabs == null) return; List<TabInfo> infos; int index; while (true) { infos = tabs.getVisibleInfos(); index = infos.indexOf(tabs.getSelectedInfo()); if (index == -1) return; if (borderIndex(infos, index) && tabs.navigatableParent() != null) { tabs = tabs.navigatableParent(); } else { break; } } _actionPerformed(e, tabs, index); } protected abstract boolean borderIndex(List<TabInfo> infos, int index); protected abstract void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex); } private static class SelectNextAction extends BaseNavigationAction { private SelectNextAction(JBTabsImpl tabs, @NotNull ActionManager mgr) { super(IdeActions.ACTION_NEXT_TAB, tabs, mgr); } @Override protected void _update(final AnActionEvent e, final JBTabsImpl tabs, int selectedIndex) { e.getPresentation().setEnabled(tabs.findEnabledForward(selectedIndex, true) != null); } @Override protected boolean borderIndex(List<TabInfo> infos, int index) { return index == infos.size() - 1; } @Override protected void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex) { TabInfo tabInfo = tabs.findEnabledForward(selectedIndex, true); if (tabInfo != null) { JComponent lastFocus = tabInfo.getLastFocusOwner(); tabs.select(tabInfo, true); tabs.myNestedTabs.stream() .filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs)) .forEach((nestedTabs) -> { nestedTabs.selectFirstVisible(); }); } } } protected boolean isNavigatable() { final int selectedIndex = getVisibleInfos().indexOf(getSelectedInfo()); return isNavigationVisible() && selectedIndex >= 0 && myNavigationActionsEnabled; } private JBTabsImpl navigatableParent() { Component c = getParent(); while (c != null) { if (c instanceof JBTabsImpl && ((JBTabsImpl)c).isNavigatable()) { return (JBTabsImpl)c; } c = c.getParent(); } return null; } private void selectFirstVisible() { if (!isNavigatable()) return; TabInfo select = getVisibleInfos().get(0); JComponent lastFocus = select.getLastFocusOwner(); select(select, true); myNestedTabs.stream() .filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs)) .forEach((nestedTabs) -> { nestedTabs.selectFirstVisible(); }); } private void selectLastVisible() { if (!isNavigatable()) return; int last = getVisibleInfos().size() - 1; TabInfo select = getVisibleInfos().get(last); JComponent lastFocus = select.getLastFocusOwner(); select(select, true); myNestedTabs.stream() .filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs)) .forEach((nestedTabs) -> { nestedTabs.selectLastVisible(); }); } private static class SelectPreviousAction extends BaseNavigationAction { private SelectPreviousAction(JBTabsImpl tabs, @NotNull ActionManager mgr) { super(IdeActions.ACTION_PREVIOUS_TAB, tabs, mgr); } @Override protected void _update(final AnActionEvent e, final JBTabsImpl tabs, int selectedIndex) { e.getPresentation().setEnabled(tabs.findEnabledBackward(selectedIndex, true) != null); } @Override protected boolean borderIndex(List<TabInfo> infos, int index) { return index == 0; } @Override protected void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex) { TabInfo tabInfo = tabs.findEnabledBackward(selectedIndex, true); if (tabInfo != null) { JComponent lastFocus = tabInfo.getLastFocusOwner(); tabs.select(tabInfo, true); tabs.myNestedTabs.stream() .filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs)) .forEach((nestedTabs) -> { nestedTabs.selectLastVisible(); }); } } } private void disposePopupListener() { if (myActivePopup != null) { myActivePopup.removePopupMenuListener(myPopupListener); myActivePopup = null; } } @Override public JBTabsPresentation setSideComponentVertical(final boolean vertical) { myHorizontalSide = !vertical; for (TabInfo each : myVisibleInfos) { each.getChangeSupport().firePropertyChange(TabInfo.ACTION_GROUP, "new1", "new2"); } relayout(true, false); return this; } @Override public JBTabsPresentation setSideComponentOnTabs(boolean onTabs) { mySideComponentOnTabs = onTabs; relayout(true, false); return this; } @Override public JBTabsPresentation setSideComponentBefore(boolean before) { mySideComponentBefore = before; relayout(true, false); return this; } @Override public JBTabsPresentation setSingleRow(boolean singleRow) { myLayout = singleRow ? mySingleRowLayout : myTableLayout; relayout(true, false); return this; } public int getSeparatorWidth() { return mySeparatorWidth; } public boolean useSmallLabels() { return false; } public boolean useBoldLabels() { return false; } @Override public boolean isSingleRow() { return getEffectiveLayout() == mySingleRowLayout; } public boolean isSideComponentVertical() { return !myHorizontalSide; } public boolean isSideComponentOnTabs() { return mySideComponentOnTabs; } public boolean isSideComponentBefore() { return mySideComponentBefore; } public TabLayout getEffectiveLayout() { if (myLayout == myTableLayout && getTabsPosition() == JBTabsPosition.top) return myTableLayout; return mySingleRowLayout; } @Override public JBTabsPresentation setUiDecorator(@Nullable UiDecorator decorator) { myUiDecorator = decorator == null ? ourDefaultDecorator : decorator; applyDecoration(); return this; } @Override protected void setUI(final ComponentUI newUI) { super.setUI(newUI); applyDecoration(); } @Override public void updateUI() { super.updateUI(); SwingUtilities.invokeLater(() -> { applyDecoration(); revalidateAndRepaint(false); }); } private void applyDecoration() { if (myUiDecorator != null) { UiDecorator.UiDecoration uiDecoration = myUiDecorator.getDecoration(); for (TabLabel each : myInfo2Label.values()) { each.apply(uiDecoration); } } for (TabInfo each : getTabs()) { adjust(each); } relayout(true, false); } private static void adjust(final TabInfo each) { if (myAdjustBorders) { UIUtil.removeScrollBorder(each.getComponent()); } } @Override public void sortTabs(Comparator<? super TabInfo> comparator) { Collections.sort(myVisibleInfos, comparator); relayout(true, false); } private boolean isRequestFocusOnLastFocusedComponent() { return myRequestFocusOnLastFocusedComponent; } @Override public JBTabsPresentation setRequestFocusOnLastFocusedComponent(final boolean requestFocusOnLastFocusedComponent) { myRequestFocusOnLastFocusedComponent = requestFocusOnLastFocusedComponent; return this; } @Override @Nullable public Object getData(@NotNull @NonNls final String dataId) { if (myDataProvider != null) { final Object value = myDataProvider.getData(dataId); if (value != null) return value; } if (QuickActionProvider.KEY.getName().equals(dataId)) { return this; } return NAVIGATION_ACTIONS_KEY.is(dataId) ? this : null; } @NotNull @Override public List<AnAction> getActions(boolean originalProvider) { ArrayList<AnAction> result = new ArrayList<>(); TabInfo selection = getSelectedInfo(); if (selection != null) { ActionGroup group = selection.getGroup(); if (group != null) { AnAction[] children = group.getChildren(null); Collections.addAll(result, children); } } return result; } @Override public DataProvider getDataProvider() { return myDataProvider; } @Override public JBTabsImpl setDataProvider(@NotNull final DataProvider dataProvider) { myDataProvider = dataProvider; return this; } static boolean isSelectionClick(final MouseEvent e, boolean canBeQuick) { if (e.getClickCount() == 1 || canBeQuick) { if (!e.isPopupTrigger()) { return e.getButton() == MouseEvent.BUTTON1 && !e.isControlDown() && !e.isAltDown() && !e.isMetaDown(); } } return false; } private static class DefaultDecorator implements UiDecorator { @Override @NotNull public UiDecoration getDecoration() { return new UiDecoration(null, new JBInsets(5, 12, 5, 12)); } } public Rectangle layout(JComponent c, Rectangle bounds) { final Rectangle now = c.getBounds(); if (!bounds.equals(now)) { c.setBounds(bounds); } c.doLayout(); c.putClientProperty(LAYOUT_DONE, Boolean.TRUE); return bounds; } public Rectangle layout(JComponent c, int x, int y, int width, int height) { return layout(c, new Rectangle(x, y, width, height)); } public static void resetLayout(JComponent c) { if (c == null) return; c.putClientProperty(LAYOUT_DONE, null); c.putClientProperty(STRETCHED_BY_WIDTH, null); } private void applyResetComponents() { for (int i = 0; i < getComponentCount(); i++) { final Component each = getComponent(i); if (each instanceof JComponent) { final JComponent jc = (JComponent)each; if (!UIUtil.isClientPropertyTrue(jc, LAYOUT_DONE)) { layout(jc, new Rectangle(0, 0, 0, 0)); } } } } @Override @NotNull public JBTabsPresentation setTabLabelActionsMouseDeadzone(final TimedDeadzone.Length length) { myTabActionsMouseDeadzone = length; final List<TabInfo> all = getTabs(); for (TabInfo each : all) { final TabLabel eachLabel = myInfo2Label.get(each); eachLabel.updateTabActions(); } return this; } @Override @NotNull public JBTabsPresentation setTabsPosition(final JBTabsPosition position) { myPosition = position; OnePixelDivider divider = mySplitter.getDivider(); if (position.isSide() && divider.getParent() == null) { add(divider); } else if (divider.getParent() == this && !position.isSide()){ remove(divider); } relayout(true, false); return this; } @Override public JBTabsPosition getTabsPosition() { return myPosition; } public TimedDeadzone.Length getTabActionsMouseDeadzone() { return myTabActionsMouseDeadzone; } @Override public JBTabsPresentation setTabDraggingEnabled(boolean enabled) { myTabDraggingEnabled = enabled; return this; } @Override public JBTabsPresentation setAlphabeticalMode(boolean alphabeticalMode) { myAlphabeticalMode = alphabeticalMode; return this; } @Override public JBTabsPresentation setSupportsCompression(boolean supportsCompression) { mySupportsCompression = supportsCompression; updateRowLayout(); return this; } public boolean isTabDraggingEnabled() { return myTabDraggingEnabled && !mySplitter.isDragging(); } void reallocate(TabInfo source, TabInfo target) { if (source == target || source == null || target == null) return; final int targetIndex = myVisibleInfos.indexOf(target); myVisibleInfos.remove(source); myVisibleInfos.add(targetIndex, source); invalidate(); relayout(true, true); } public boolean isHorizontalTabs() { return getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom; } @Override public void putInfo(@NotNull Map<String, String> info) { final TabInfo selected = getSelectedInfo(); if (selected != null) { selected.putInfo(info); } } @Override public void resetDropOver(TabInfo tabInfo) { if (myDropInfo != null) { TabInfo dropInfo = myDropInfo; myDropInfo = null; myShowDropLocation = true; myForcedRelayout = true; setDropInfoIndex(-1); if (!isDisposed()) { removeTab(dropInfo, null, false, true); } } } @Override public Image startDropOver(TabInfo tabInfo, RelativePoint point) { myDropInfo = tabInfo; int index = myLayout.getDropIndexFor(point.getPoint(this)); setDropInfoIndex(index); addTab(myDropInfo, index, true, true); TabLabel label = myInfo2Label.get(myDropInfo); Dimension size = label.getPreferredSize(); label.setBounds(0, 0, size.width, size.height); BufferedImage img = UIUtil.createImage(this, size.width, size.height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); label.paintOffscreen(g); g.dispose(); relayout(true, false); return img; } @Override public void processDropOver(TabInfo over, RelativePoint point) { int index = myLayout.getDropIndexFor(point.getPoint(this)); if (index != getDropInfoIndex()) { setDropInfoIndex(index); relayout(true, false); } } @Override public int getDropInfoIndex() { return myDropInfoIndex; } @Override public boolean isEmptyVisible() { return myVisibleInfos.isEmpty(); } @Deprecated public int getInterTabSpaceLength() { return getTabHGap(); } public int getTabHGap() { return -myBorder.getThickness(); } @Override public String toString() { return "JBTabs visible=" + myVisibleInfos + " selected=" + mySelectedInfo; } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJBTabsImpl(); } return accessibleContext; } /** * Custom implementation of Accessible interface. Given JBTabsImpl is similar * to the built-it JTabbedPane, we expose similar behavior. The one tricky part * is that JBTabsImpl can only expose the content of the selected tab, as the * content of tabs is created/deleted on demand when a tab is selected. */ protected class AccessibleJBTabsImpl extends AccessibleJComponent implements AccessibleSelection { AccessibleJBTabsImpl() { getAccessibleComponent(); addListener(new TabsListener() { @Override public void selectionChanged(TabInfo oldSelection, TabInfo newSelection) { firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, null, null); } }); } @Override public String getAccessibleName() { String name = accessibleName; if (name == null) { name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY); } if (name == null) { // Similar to JTabbedPane, we return the name of our selected tab // as our own name. TabLabel selectedLabel = getSelectedLabel(); if (selectedLabel != null) { if (selectedLabel.getAccessibleContext() != null) { name = selectedLabel.getAccessibleContext().getAccessibleName(); } } } if (name == null) { name = super.getAccessibleName(); } return name; } @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.PAGE_TAB_LIST; } @Override public Accessible getAccessibleChild(int i) { Accessible accessibleChild = super.getAccessibleChild(i); // Note: Unlike a JTabbedPane, JBTabsImpl has many more child types than just pages. // So we wrap TabLabel instances with their corresponding AccessibleTabPage, while // leaving other types of children untouched. if (accessibleChild instanceof TabLabel) { TabLabel label = (TabLabel)accessibleChild; return myInfo2Page.get(label.getInfo()); } return accessibleChild; } @Override public AccessibleSelection getAccessibleSelection() { return this; } @Override public int getAccessibleSelectionCount() { return getSelectedInfo() == null ? 0 : 1; } @Override public Accessible getAccessibleSelection(int i) { if (getSelectedInfo() == null) return null; return myInfo2Page.get(getSelectedInfo()); } @Override public boolean isAccessibleChildSelected(int i) { return i == getIndexOf(getSelectedInfo()); } @Override public void addAccessibleSelection(int i) { TabInfo info = getTabAt(i); select(info, false); } @Override public void removeAccessibleSelection(int i) { // can't do } @Override public void clearAccessibleSelection() { // can't do } @Override public void selectAllAccessibleSelection() { // can't do } } /** * AccessibleContext implementation for a single tab page. * * A tab page has a label as the display zone, name, description, etc. * A tab page exposes a child component only if it corresponds to the * selected tab in the tab pane. Inactive tabs don't have a child * component to expose, as components are created/deleted on demand. * A tab page exposes one action: select and activate the panel. */ private class AccessibleTabPage extends AccessibleContext implements Accessible, AccessibleComponent, AccessibleAction { @NotNull private final JBTabsImpl myParent; @NotNull private final TabInfo myTabInfo; private final Component myComponent; AccessibleTabPage(@NotNull TabInfo tabInfo) { myParent = JBTabsImpl.this; myTabInfo = tabInfo; myComponent = tabInfo.getComponent(); setAccessibleParent(myParent); initAccessibleContext(); } @NotNull private TabInfo getTabInfo() { return myTabInfo; } private int getTabIndex() { return getIndexOf(myTabInfo); } private TabLabel getTabLabel() { return myInfo2Label.get(getTabInfo()); } /* * initializes the AccessibleContext for the page */ void initAccessibleContext() { // Note: null checks because we do not want to load Accessibility classes unnecessarily. if (accessibleContext != null && myComponent instanceof Accessible) { AccessibleContext ac = myComponent.getAccessibleContext(); if (ac != null) { ac.setAccessibleParent(this); } } } // Accessibility support @Override public AccessibleContext getAccessibleContext() { return this; } // AccessibleContext methods @Override public String getAccessibleName() { String name = accessibleName; if (name == null) { name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY); } if (name == null) { TabLabel label = getTabLabel(); if (label != null && label.getAccessibleContext() != null) { name = label.getAccessibleContext().getAccessibleName(); } } if (name == null) { name = super.getAccessibleName(); } return name; } @Override public String getAccessibleDescription() { String description = accessibleDescription; if (description == null) { description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY); } if (description == null) { TabLabel label = getTabLabel(); if (label != null && label.getAccessibleContext() != null) { description = label.getAccessibleContext().getAccessibleDescription(); } } if (description == null) { description = super.getAccessibleDescription(); } return description; } @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.PAGE_TAB; } @Override public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = myParent.getAccessibleContext().getAccessibleStateSet(); states.add(AccessibleState.SELECTABLE); TabInfo info = myParent.getSelectedInfo(); if (info == getTabInfo()) { states.add(AccessibleState.SELECTED); } return states; } @Override public int getAccessibleIndexInParent() { return getTabIndex(); } @Override public int getAccessibleChildrenCount() { // Expose the tab content only if it is active, as the content for // inactive tab does is usually not ready (i.e. may never have been // activated). return getSelectedInfo() == getTabInfo() && myComponent instanceof Accessible ? 1 : 0; } @Override public Accessible getAccessibleChild(int i) { return getSelectedInfo() == getTabInfo() && myComponent instanceof Accessible ? (Accessible)myComponent : null; } @Override public Locale getLocale() { return JBTabsImpl.this.getLocale(); } @Override public AccessibleComponent getAccessibleComponent() { return this; } @Override public AccessibleAction getAccessibleAction() { return this; } // AccessibleComponent methods @Override public Color getBackground() { return JBTabsImpl.this.getBackground(); } @Override public void setBackground(Color c) { JBTabsImpl.this.setBackground(c); } @Override public Color getForeground() { return JBTabsImpl.this.getForeground(); } @Override public void setForeground(Color c) { JBTabsImpl.this.setForeground(c); } @Override public Cursor getCursor() { return JBTabsImpl.this.getCursor(); } @Override public void setCursor(Cursor c) { JBTabsImpl.this.setCursor(c); } @Override public Font getFont() { return JBTabsImpl.this.getFont(); } @Override public void setFont(Font f) { JBTabsImpl.this.setFont(f); } @Override public FontMetrics getFontMetrics(Font f) { return JBTabsImpl.this.getFontMetrics(f); } @Override public boolean isEnabled() { return getTabInfo().isEnabled(); } @Override public void setEnabled(boolean b) { getTabInfo().setEnabled(b); } @Override public boolean isVisible() { return !getTabInfo().isHidden(); } @Override public void setVisible(boolean b) { getTabInfo().setHidden(!b); } @Override public boolean isShowing() { return JBTabsImpl.this.isShowing(); } @Override public boolean contains(Point p) { Rectangle r = getBounds(); return r.contains(p); } @Override public Point getLocationOnScreen() { Point parentLocation = JBTabsImpl.this.getLocationOnScreen(); Point componentLocation = getLocation(); componentLocation.translate(parentLocation.x, parentLocation.y); return componentLocation; } @Override public Point getLocation() { Rectangle r = getBounds(); return new Point(r.x, r.y); } @Override public void setLocation(Point p) { // do nothing } /** * Returns the bounds of tab. The bounds are with respect to the JBTabsImpl coordinate space. */ @Override public Rectangle getBounds() { return getTabLabel().getBounds(); } @Override public void setBounds(Rectangle r) { // do nothing } @Override public Dimension getSize() { Rectangle r = getBounds(); return new Dimension(r.width, r.height); } @Override public void setSize(Dimension d) { // do nothing } @Override public Accessible getAccessibleAt(Point p) { return myComponent instanceof Accessible ? (Accessible)myComponent : null; } @Override public boolean isFocusTraversable() { return false; } @Override public void requestFocus() { // do nothing } @Override public void addFocusListener(FocusListener l) { // do nothing } @Override public void removeFocusListener(FocusListener l) { // do nothing } @Override public AccessibleIcon [] getAccessibleIcon() { AccessibleIcon accessibleIcon = null; if (getTabInfo().getIcon() instanceof ImageIcon) { AccessibleContext ac = ((ImageIcon)getTabInfo().getIcon()).getAccessibleContext(); accessibleIcon = (AccessibleIcon)ac; } if (accessibleIcon != null) { AccessibleIcon [] returnIcons = new AccessibleIcon[1]; returnIcons[0] = accessibleIcon; return returnIcons; } else { return null; } } // AccessibleAction methods @Override public int getAccessibleActionCount() { return 1; } @Override public String getAccessibleActionDescription(int i) { if (i != 0) return null; return "Activate"; } @Override public boolean doAccessibleAction(int i) { if (i != 0) return false; select(getTabInfo(), true); return true; } } /** * @deprecated unused. You should move the painting logic to an implementation of {@link JBTabPainter} interface } */ @Deprecated public int getActiveTabUnderlineHeight() { return 0; } /** * @deprecated unused in current realization. */ @Deprecated protected static class ShapeInfo { public ShapeInfo() { } public ShapeTransform path; public ShapeTransform fillPath; public ShapeTransform labelPath; public int labelBottomY; public int labelTopY; public int labelLeftX; public int labelRightX; public Insets insets; public Color from; public Color to; } }
// $Header: /share/content/gforge/sentinel/sentinel/src/gov/nih/nci/cadsr/sentinel/util/DSRAlertV1.java,v 1.18 2008-05-16 18:28:25 hebell Exp $ // $Name: not supported by cvs2svn $ package gov.nih.nci.cadsr.sentinel.util; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * This class is used internally to the DSRAlert package and should not be referenced * externally. Use the DSRAlertImpl.factory() method and the DSRAlert Interface for * requests to the Sentinel Alert system. * * @author Larry Hebel Oct 12, 2005 */ public class DSRAlertV1 implements DSRAlert { /** * Constructor * * @param url_ The url to the Sentinel Tool */ public DSRAlertV1(String url_) { _rc = DSRAlert.RC_OK; _alertName = ""; if (url_ == null || url_.length() == 0) { url_ = "https://cadsrsentinel.nci.nih.gov/cadsrsentinel/do/"; return; } // Get the usable parts of the url. String tokens[] = url_.split("/"); int tndx = 0; // Must start with http: _url = null; if (tndx < tokens.length) { if (tokens[tndx].compareToIgnoreCase("http:") == 0) { _url = "http: ++tndx; } else if (tokens[tndx].compareToIgnoreCase("https:") == 0) { _url = "https: ++tndx; } } if (_url == null) _url = "http: if (tndx < tokens.length && (tokens[tndx] == null || tokens[tndx].length() == 0)) ++tndx; // Copy everything up to the cadsrsentinel part. for (; tndx < tokens.length && tokens[tndx].compareToIgnoreCase("cadsrsentinel") != 0; ++tndx) { _url = _url + tokens[tndx] + "/"; } // Be sure we end with the proper suffix. _url = _url + "cadsrsentinel/do/"; } /** * Create an Alert Definition for the specified ID and owned by the specified User. * * @param user_ The user id as used to Login to the Sentinel Tool. * @param idseq_ The database entity ID, a 36 character value. * @return DSRAlert.RC_EXISTS if the Alert already exists, DSRAlert.RC_CREATED if a new Alert is created, * otherwise DSRAlert.RC_FAILED (refer to the web server log for the response message). */ public int createAlert(String user_, String idseq_) { String url = _url + "crf?version=" + _version + "&user=" + user_ + "&idseq=" + idseq_; int rc = DSRAlert.RC_FAILED; _alertName = ""; if (user_ != null && user_.length() > 0 && idseq_ != null && idseq_.length() > 0) { HttpURLConnection http = null; try { boolean writeToLog = false; URL rps = new URL(url); http = (HttpURLConnection) rps.openConnection(); http.setUseCaches(false); InputStream iStream = http.getInputStream(); int response = http.getResponseCode(); // Test for redirection of the URL and open a connection to the real location. switch (response) { case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: // Log the redirect, ignore the default HTML response, we aren't a browser. _logger.info("Original URL " + url + " [" + http.getResponseCode() + " : " + http.getResponseMessage() + "]"); url = http.getHeaderField("Location"); _logger.info("Redirect URL " + url + " [" + http.getResponseCode() + " : " + http.getResponseMessage() + "]"); // Drop the old connection. http.disconnect(); // Turn up the new one. rps = new URL(url); http = (HttpURLConnection) rps.openConnection(); http.setUseCaches(false); iStream = http.getInputStream(); response = http.getResponseCode(); break; // No redirect so fall through. default: break; } // Check the results of the create request. switch (response) { case HttpURLConnection.HTTP_NOT_IMPLEMENTED: rc = DSRAlert.RC_INCOMPATIBLE; break; case HttpURLConnection.HTTP_CREATED: rc = DSRAlert.RC_CREATED; break; case HttpURLConnection.HTTP_OK: rc = DSRAlert.RC_EXISTS; break; case HttpURLConnection.HTTP_FORBIDDEN: rc = DSRAlert.RC_UNAUTHORIZED; break; default: rc = DSRAlert.RC_FAILED; _logger.error(url + " [" + http.getResponseCode() + " : " + http.getResponseMessage() + "]"); break; } // Get the Alert Name returned from the create service. if (rc >= 0) { BufferedReader in = new BufferedReader(new InputStreamReader(iStream)); while (true) { String line = in.readLine(); if (line == null) break; line = line.trim(); _alertName = line; if (writeToLog) _logger.info(line); } } } catch(MalformedURLException ex) { _logger.error("[" + url + "] " + ex.toString()); } catch(IOException ex) { _logger.error("[" + url + "] " + ex.toString()); } finally { // Clean up if (http != null) http.disconnect(); } } _rc = rc; return rc; } /** * Get the Alert Name for the latest method call if available. * * @return The alert name if available, otherwise and empty string. */ public String getAlertName() { return _alertName; } /** * Get the complete history for the specified ID in pre-formatted HTML. * * @param idseq_ The database entity ID, a 36 character value. * @return If the history can be retrieved the return will not equal null, otherwise the return is equal * null and the method getResultCode() must be used to retrieve the operation RC. */ public String getItemHistoryHTML(String idseq_) { String url = _url + "loghtml?version=" + _version + "&idseq=" + idseq_; String html = null; int rc = DSRAlert.RC_FAILED; _alertName = ""; if (idseq_ != null && idseq_.length() > 0) { try { URL rps = new URL(url); HttpURLConnection http = (HttpURLConnection) rps.openConnection(); http.setUseCaches(false); switch (http.getResponseCode()) { case HttpURLConnection.HTTP_NOT_IMPLEMENTED: rc = DSRAlert.RC_INCOMPATIBLE; break; case HttpURLConnection.HTTP_OK: rc = DSRAlert.RC_OK; break; case HttpURLConnection.HTTP_FORBIDDEN: rc = DSRAlert.RC_UNAUTHORIZED; break; default: rc = DSRAlert.RC_FAILED; _logger.error(http.getResponseMessage()); break; } // Get the Alert Name returned from the create service. if (rc >= 0) { BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); html = ""; String temp; while ((temp = in.readLine()) != null) { html += temp; } } http.disconnect(); } catch(MalformedURLException ex) { _logger.error("[" + url + "] " + ex.toString()); } catch(IOException ex) { _logger.error("[" + url + "] " + ex.toString()); } } _rc = rc; return html; } /** * Get the result code from the most recent method executed. * * @return One of the "RC_" static final values defined in this interface. */ public int getResultCode() { return _rc; } private String _url; private String _alertName; private int _rc; private static final Logger _logger = Logger.getLogger(DSRAlertV1.class.getName()); private static final String _version = "1"; }
package client; import common.*; import client.audio.*; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.JFrame; import javax.swing.Timer; import java.awt.geom.Rectangle2D; import java.util.Vector; import java.util.Random; /** * This class describes the game loop for this game * @author smaboshe * */ public class GameEngine implements Constants, ActionListener { public static final Random rand = new Random(); public boolean gameOver; public Map gameMap; public ClientViewArea gameViewArea; public LocalPlayer localPlayer; public InputListener localInputListener; // Lists public Vector<Actor> actorList; public Vector<Stone> stoneList; public Vector<Player> playerList; public Vector<Projectile> bulletList; public long lastTime; public GameSoundSystem soundSystem; public SoundEffect soundBump; public Timer timer; // CONSTRUCTORS public GameEngine(Map m) { gameOver = false; gameMap = m; gameViewArea = new ClientViewArea(); gameViewArea.setMap(gameMap); localInputListener = new InputListener(); localPlayer = new LocalPlayer(localInputListener); placePlayer(localPlayer); gameViewArea.setLocalPlayer(localPlayer); actorList = new Vector<Actor>(); actorList.add(localPlayer); stoneList = new Vector<Stone>(); playerList = new Vector<Player>(); playerList.add(localPlayer); bulletList = new Vector<Projectile>(); // Sound engine stuff: soundSystem = new GameSoundSystem(); soundBump = soundSystem.loadSoundEffect(SOUND_BUMP); } // GETTERS public LocalPlayer getLocalPlayer() { return this.localPlayer; } public Map getGameMap() { return this.gameMap; } // SETTERS public void setLocalPlayer(LocalPlayer p) { this.localPlayer = p; } public void setGameMap(Map m) { this.gameMap = m; } // OPERATIONS public boolean isGameOver() { return this.gameOver; } public void gameOver() { gameOver = true; if (timer != null) timer.stop(); } public void gameStep() { checkCollisions(); updateWorld(); } public void play() { initialize(); timer = new Timer(20, this); timer.start(); // while (!isGameOver()) { // gameStep(); // try { Thread.sleep(10); } // catch (InterruptedException er) { } } public void initialize() { String title = CLIENT_WINDOW_NAME; System.out.println(title); // Set up game window JFrame window = new JFrame(title); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gameViewArea.setActorList(actorList); // Copy the map as a bunch of Stones for (int x=0; x < gameMap.getXSize(); x++) for (int y=0; y < gameMap.getYSize(); y++) { if (gameMap.isWall(x, y)) { stoneList.add(new Stone(x, y)); actorList.add(stoneList.get(stoneList.size() - 1)); } } window.getContentPane().add(this.gameViewArea, BorderLayout.CENTER); window.addKeyListener(this.gameViewArea); localInputListener.attachListeners(window); window.pack(); window.setLocationRelativeTo(null); window.setVisible(true); lastTime = System.currentTimeMillis(); } public void checkCollisions() { // Environment, Player and projectile collision code goes here Rectangle2D bounds1, bounds2; Actor actor1, actor2; // Check players against stones for (int i=0; i < stoneList.size(); i ++) { actor1 = stoneList.get(i); bounds1 = actor1.getBounds(); for (int j=0; j < playerList.size(); j ++) { actor2 = playerList.get(j); bounds2 = actor2.getBounds(); if (bounds1.intersects(bounds2)) { actor1.collision(actor2); actor2.collision(actor1); } } } // end check players against stones // Check bullets against players and stones for (int i=0; i < bulletList.size(); i ++) { actor1 = bulletList.get(i); bounds1 = actor1.getBounds(); for (int j=0; j < playerList.size(); j ++) { actor2 = playerList.get(j); bounds2 = actor2.getBounds(); if (bounds1.intersects(bounds2)) { actor1.collision(actor2); actor2.collision(actor1); } } for (int j=0; j < stoneList.size(); j ++) { actor2 = stoneList.get(j); bounds2 = actor2.getBounds(); if (bounds1.intersects(bounds2)) { actor1.collision(actor2); actor2.collision(actor1); } } } // end check bullets against players and stones //Vector actorList = this.gameViewArea.actorList; // Rectangle2D playerBounds = this.localPlayer.getBounds(); // for (int i = 0; i < actorList.size(); i = i + 1) { // Actor actor1 = actorList.get(i); // if (actor1 instanceof TrackingObject) continue; // Rectangle2D bound1 = actor1.getBounds(); // if (bound1.intersects(playerBounds)) { // this.localPlayer.collision(actor1); // actor1.collision(this.localPlayer); // for (int j = i + 1; j < actorList.size(); j = j + 1) { // Actor actor2 = actorList.get(j); // if (actor2 instanceof TrackingObject) continue; // Rectangle2D bound2 = actor2.getBounds(); // if (bound1.intersects(bound2)) { // actor1.collision(actor2); // actor2.collision(actor1); } public void updateWorld() { long thisTime = System.currentTimeMillis(); float dTime = 0.001f*(thisTime - lastTime); boolean repaint = false; for (Actor a : actorList) { if (a.animate(dTime)) repaint = true; } lastTime = thisTime; if (repaint) gameViewArea.repaint(); } public void actionPerformed(ActionEvent e) { gameStep(); } public void placePlayer(Player p) { Vector<SpawnPoint> spawnPoints = gameMap.getSpawnPoints(); if (spawnPoints == null || spawnPoints.size() == 0) { final int width = gameMap.getXSize(), height = gameMap.getYSize(); int x = rand.nextInt(width), y = rand.nextInt(height); while (gameMap.isWall(x, y)) { x = rand.nextInt(width); y = rand.nextInt(height); } p.setPosition(x + 0.5f, y + 0.5f); } else { p.setPosition(spawnPoints.get(rand.nextInt(spawnPoints.size())).getPosition()); } } /** * Plays a bump sound effect at the specified volume. If the sound is already playing at a lower volume, it is stopped and restarted at the louder volume, otherwise nothing happens. * @param volume The volume at which to play. */ public void playBump(float volume) { playSound(volume, soundBump); } /** * A slightly more generic sound playing method so we don't have to duplicate code all over the place. * This actually handles playing or not playing the sound. * @param volume * @param sound */ private void playSound(float volume, SoundEffect sound) { if (sound.isPlaying()) { if (sound.getVolume() < volume) sound.stop(); else return; } sound.setVolume(volume); sound.play(); } }
package com.kaltura.playkit.player; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.Gravity; import android.view.SurfaceView; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.text.Cue; import com.google.android.exoplayer2.text.TextRenderer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SubtitleView; import java.util.List; /** * @hide */ public class ExoPlayerView extends PlayerView implements SimpleExoPlayer.VideoListener, TextRenderer.Output{ private static final String TAG = ExoPlayerView.class.getSimpleName(); private final View surfaceView; private final View posterView; // TODO should be changed to poster? private final SubtitleView subtitleLayout; private final AspectRatioFrameLayout layout; private SimpleExoPlayer player; public ExoPlayerView(Context context) { this(context, null); } public ExoPlayerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ExoPlayerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); layout = initFrameLayout(); posterView = initPosterView(); subtitleLayout = initSubtitleLayout(); surfaceView = initSurfaceView(); addView(layout); layout.addView(surfaceView, 0); layout.addView(posterView); layout.addView(subtitleLayout); } private View initSurfaceView() { View surfaceView = new SurfaceView(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); surfaceView.setLayoutParams(params); return surfaceView; } private SubtitleView initSubtitleLayout() { SubtitleView subtitleLayout = new SubtitleView(getContext()); subtitleLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); subtitleLayout.setUserDefaultStyle(); subtitleLayout.setUserDefaultTextSize(); return subtitleLayout; } private View initPosterView() { View posterView = new View(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); posterView.setLayoutParams(params); posterView.setBackgroundColor(Color.BLACK); return posterView; } private AspectRatioFrameLayout initFrameLayout() { AspectRatioFrameLayout frameLayout = new AspectRatioFrameLayout(getContext()); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); params.gravity = Gravity.CENTER; frameLayout.setLayoutParams(params); return frameLayout; } /** * Returns the player currently set on this view, or null if no player is set. */ public SimpleExoPlayer getPlayer() { return player; } /** * Set the {@link SimpleExoPlayer} to use. The {@link SimpleExoPlayer#setTextOutput} and * {@link SimpleExoPlayer#setVideoListener} method of the player will be called and previous * assignments are overridden. * * @param player The {@link SimpleExoPlayer} to use. */ public void setPlayer(SimpleExoPlayer player) { if (this.player == player) { return; } if (this.player != null) { this.player.setTextOutput(null); this.player.setVideoListener(null); this.player.setVideoSurface(null); } this.player = player; if (player != null) { if (surfaceView instanceof TextureView) { player.setVideoTextureView((TextureView) surfaceView); } else if (surfaceView instanceof SurfaceView) { player.setVideoSurfaceView((SurfaceView) surfaceView); } player.setVideoListener(this); player.setTextOutput(this); } else { posterView.setVisibility(VISIBLE); } } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { layout.setAspectRatio(height == 0 ? 1 : (width * pixelWidthHeightRatio) / height); } @Override public void onRenderedFirstFrame() { posterView.setVisibility(GONE); } @Override public void onCues(List<Cue> cues) { subtitleLayout.onCues(cues); } @Override public void hideVideoSurface() { surfaceView.setVisibility(GONE); subtitleLayout.setVisibility(GONE); } @Override public void showVideoSurface() { surfaceView.setVisibility(VISIBLE); subtitleLayout.setVisibility(VISIBLE); } }
package com.kaltura.playkitdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.google.gson.JsonObject; import com.kaltura.playkit.MediaEntryProvider; import com.kaltura.playkit.PKAdInfo; import com.kaltura.playkit.PKEvent; import com.kaltura.playkit.PKLog; import com.kaltura.playkit.PKMediaEntry; import com.kaltura.playkit.PlayKitManager; import com.kaltura.playkit.Player; import com.kaltura.playkit.PlayerConfig; import com.kaltura.playkit.PlayerEvent; import com.kaltura.playkit.backend.base.OnMediaLoadCompletion; import com.kaltura.playkit.backend.mock.MockMediaProvider; import com.kaltura.playkit.connect.ResultElement; import com.kaltura.playkit.plugins.SamplePlugin; import com.kaltura.playkit.plugins.ads.AdEvent; import com.kaltura.playkit.plugins.ads.AdsConfig; import com.kaltura.playkit.plugins.ads.ima.IMASimplePlugin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { public static final boolean AUTO_PLAY_ON_RESUME = true; private static final String TAG = "MainActivity"; private static final PKLog log = PKLog.get(TAG); private Player player; private MediaEntryProvider mediaProvider; private PlaybackControlsView controlsView; private boolean nowPlaying; ProgressBar progressBar; private void registerPlugins() { PlayKitManager.registerPlugins(SamplePlugin.factory); PlayKitManager.registerPlugins(IMASimplePlugin.factory); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setVisibility(View.INVISIBLE); registerPlugins(); mediaProvider = new MockMediaProvider("mock/entries.playkit.json", this, "dash"); // mediaProvider = new PhoenixMediaProvider(MockParams.sessionProvider, MediaId, MockParams.MediaType, Format); mediaProvider.load(new OnMediaLoadCompletion() { @Override public void onComplete(final ResultElement<PKMediaEntry> response) { runOnUiThread(new Runnable() { @Override public void run() { if (response.isSuccess()) { onMediaLoaded(response.getResponse()); } else { Toast.makeText(MainActivity.this, "failed to fetch media data: " + (response.getError() != null ? response.getError().getMessage() : ""), Toast.LENGTH_LONG).show(); log.e("failed to fetch media data: " + (response.getError() != null ? response.getError().getMessage() : "")); } } }); } }); } private void onMediaLoaded(PKMediaEntry mediaEntry){ PlayerConfig config = new PlayerConfig(); config.media.setMediaEntry(mediaEntry); if (player == null) { configurePlugins(config.plugins); player = PlayKitManager.loadPlayer(config, this); log.d("Player: " + player.getClass()); addPlayerListeners(progressBar); LinearLayout layout = (LinearLayout) findViewById(R.id.player_root); layout.addView(player.getView()); controlsView = (PlaybackControlsView) this.findViewById(R.id.playerControls); controlsView.setPlayer(player); //controlsView.setVisibility(View.INVISIBLE); } player.prepare(config.media); //player.play(); } private void configurePlugins(PlayerConfig.Plugins config) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("delay", 4200); config.setPluginConfig("Sample", jsonObject); addIMAPluginConfig(config); } private void addIMAPluginConfig(PlayerConfig.Plugins config) { String adTagUrl = "http: List<String> videoMimeTypes = new ArrayList<>(); //videoMimeTypes.add(MimeTypes.APPLICATION_MP4); //videoMimeTypes.add(MimeTypes.APPLICATION_M3U8); Map<Double, String> tagTimesMap = new HashMap<>(); //tagTimesMap.put(2.0,"GILAD"); AdsConfig adsConfig = new AdsConfig("en", false, true, 60000, videoMimeTypes, adTagUrl, tagTimesMap); config.setPluginConfig(IMASimplePlugin.factory.getName(), adsConfig.toJSONObject()); } @Override protected void onPause() { super.onPause(); controlsView.release(); player.onApplicationPaused(); } private void addPlayerListeners(final ProgressBar appProgressBar) { player.addEventListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { log.d("Ad Event AD_CONTENT_PAUSE_REQUESTED"); PKAdInfo adInfo = player.getAdInfo(); appProgressBar.setVisibility(View.VISIBLE); } }, AdEvent.Type.AD_CONTENT_PAUSE_REQUESTED); player.addEventListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { log.d("Ad Event AD_STARTED"); PKAdInfo adInfo = player.getAdInfo(); appProgressBar.setVisibility(View.INVISIBLE); } }, AdEvent.Type.AD_STARTED); player.addEventListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { log.d("Ad Event AD_RESUMED"); PKAdInfo adInfo = player.getAdInfo(); appProgressBar.setVisibility(View.INVISIBLE); } }, AdEvent.Type.AD_RESUMED); player.addEventListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { nowPlaying = true; } }, PlayerEvent.Type.PLAY); player.addEventListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { nowPlaying = false; } }, PlayerEvent.Type.PAUSE); player.addEventListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { nowPlaying = true; } }, AdEvent.Type.AD_STARTED); player.addStateChangeListener(new PKEvent.Listener() { @Override public void onEvent(PKEvent event) { if (event instanceof PlayerEvent.StateChanged) { PlayerEvent.StateChanged stateChanged = (PlayerEvent.StateChanged) event; log.d("State changed from " + stateChanged.oldState + " to " + stateChanged.newState); if(controlsView != null){ controlsView.setPlayerState(stateChanged.newState); } } } }); } @Override protected void onResume() { log.d("Ad Event onResume"); super.onResume(); if(player != null){ player.onApplicationResumed(); if (nowPlaying && AUTO_PLAY_ON_RESUME) { player.play(); } } if(controlsView != null){ controlsView.resume(); } } }
package org.jetbrains.idea.devkit.util; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.impl.LibraryScopeCache; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.xml.DomService; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.devkit.dom.IdeaPlugin; import java.util.Collection; public final class PluginRelatedLocatorsUtils { @NotNull public static GlobalSearchScope getCandidatesScope(@NotNull Project project) { return CachedValuesManager.getManager(project).getCachedValue(project, () -> { GlobalSearchScope scope = GlobalSearchScopesCore.projectProductionScope(project) .uniteWith(LibraryScopeCache.getInstance(project).getLibrariesOnlyScope()); Collection<VirtualFile> candidates = DomService.getInstance() .getDomFileCandidates(IdeaPlugin.class, scope); final GlobalSearchScope filesScope = GlobalSearchScope.filesWithLibrariesScope(project, candidates); return new CachedValueProvider.Result<>(filesScope, PsiModificationTracker.MODIFICATION_COUNT); }); } }
package aptgraph.server; import aptgraph.core.Domain; import aptgraph.core.Request; import info.debatty.java.graphs.Graph; import info.debatty.java.graphs.Neighbor; import info.debatty.java.graphs.NeighborList; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import static junit.framework.Assert.assertTrue; import junit.framework.TestCase; /** * * @author Thibault Debatty */ public class RequestHandlerTest extends TestCase { /** * Test of test method, of class RequestHandler. * @throws java.io.IOException * @throws java.lang.ClassNotFoundException */ public void testTest() throws IOException, ClassNotFoundException { System.out.println("\ntest"); RequestHandler handler = new RequestHandler(Paths.get("src/test/resources/dummyDir")); handler.test(); } /** * Test of dummy method, of class RequestHandler. * @throws java.io.IOException * @throws java.lang.ClassNotFoundException */ public void testDummy() throws IOException, ClassNotFoundException { System.out.println("\ndummy"); RequestHandler handler = new RequestHandler(Paths.get("src/test/resources/dummyDir")); handler.dummy(); } /** * Test of analyze method, of class RequestHandler. * @throws java.io.IOException * @throws java.lang.ClassNotFoundException */ public void testAnalyze() throws IOException, ClassNotFoundException { System.out.println("\nanalyze"); RequestHandler handler = new RequestHandler(Paths.get("src/test/resources/dummyDir")); handler.getUsers(); handler.analyze("253.115.106.54", new double[]{0.7, 0.1, 0.2}, new double[]{0.8, 0.2}, 0.0, 0.0, true, true, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); } /** * Test the integrity of the all_domains HashMap. */ public void testIntegrityAllDomains() { System.out.println("\nIntegrity : all_domains"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); HashMap<String, HashMap<String, Domain>> all_domains = handler.getMemory().getAllDomains(); // Test for (String user : handler.getMemory().getAllUsersList()) { LinkedList<Graph<Domain>> graphs = FileManager.getUserGraphs( input_dir, user); for (Graph<Domain> graph : graphs) { for (Domain dom : graph.getNodes()) { assertTrue(all_domains.get("byUsers") .get(user + ":" + dom.getName()).deepEquals(dom)); for (Request req : dom) { assertTrue(all_domains.get("all") .get(dom.getName()).contains(req)); assertTrue(all_domains.get("byUsers") .get(user + ":" + dom.getName()).contains(req)); } } } } } /** * Test of the integrity of domains during fusion of graphs. * @throws IOException * @throws ClassNotFoundException */ public void testIntegrityFusionFeatures() throws IOException, ClassNotFoundException { System.out.println("\nIntegrity : fusion of features"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); double[] weights = {0.7, 0.1, 0.2}; for (String user : handler.getMemory().getAllUsersList()) { LinkedList<Graph<Domain>> graphs = handler.getMemory().getUsersGraphs().get(user); Graph<Domain> merged_graph = handler.computeFusionGraphs(graphs, user, weights, new double[]{0.8, 0.2}, "byUsers"); HashMap<String, Domain> all_domains_merged = new HashMap<String, Domain>(); for (Domain dom : merged_graph.getNodes()) { all_domains_merged.put(dom.getName(), dom); } // Test presence of all the domains and requests after feature fusion for (Map.Entry<String, Domain> entry : handler.getMemory() .getAllDomains().get("byUsers").entrySet()) { String key = entry.getKey(); Domain dom_1 = entry.getValue(); if (key.startsWith(user)) { for (Domain dom_2 : all_domains_merged.values()) { if (dom_1.getName().equals(dom_2.getName())) { assertTrue(dom_1.deepEquals(dom_2)); } } } } // Test the lost of neighbors (domains and requests) for (Graph<Domain> graph_temp : graphs) { for (Domain dom : graph_temp.getNodes()) { NeighborList nl_temp = graph_temp.getNeighbors(dom); NeighborList nl_merged = merged_graph.getNeighbors(dom); for (Neighbor<Domain> nb : nl_temp) { if (nb.similarity != 0) { assertTrue(nl_merged.containsNode(nb.node)); for (Neighbor<Domain> nb_merged : nl_merged) { if (nb_merged.node.getName() .equals(nb.node.getName())) { assertTrue(nb.node.deepEquals(nb_merged.node)); } } } } } } // Test the similarities for (Domain dom_11 : merged_graph.getNodes()) { NeighborList nl_dom_11 = merged_graph.getNeighbors(dom_11); for (Neighbor<Domain> dom_12 : nl_dom_11) { double similarity_temp = 0.0; for (int i = 0; i < graphs.size(); i++) { Graph<Domain> feature_graph = graphs.get(i); for (Domain dom_21 : feature_graph.getNodes()) { if (dom_21.deepEquals(dom_11)) { NeighborList nl_dom_21 = feature_graph .getNeighbors(dom_21); for (Neighbor<Domain> dom_22 : nl_dom_21) { if (dom_22.node.deepEquals(dom_12.node)) { similarity_temp += weights[i] * dom_22.similarity; } } } } } assertTrue(dom_12.similarity == similarity_temp); } } } } /** * Test the good transmission of the weights. */ public void testWeightsFeatures() { System.out.println("\nFusion : test weights"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setUser(handler.getMemory().getUsersList().get(0)); LinkedList<Graph<Domain>> graphs = handler.getMemory().getUsersGraphs() .get(handler.getMemory().getUser()); // Test time weight Graph<Domain> time_graph = graphs.get(0); Graph<Domain> merged_graph_time = handler.computeFusionGraphs(graphs, handler.getMemory().getUser(), new double[]{1.0, 0.0, 0.0}, new double[]{0.8, 0.2}, "byUsers"); assertEquals(time_graph, merged_graph_time); // Test domain weight Graph<Domain> domain_graph = graphs.get(1); Graph<Domain> merged_graph_domain = handler.computeFusionGraphs(graphs, handler.getMemory().getUser(), new double[]{0.0, 1.0, 0.0}, new double[]{0.8, 0.2}, "byUsers"); assertEquals(domain_graph, merged_graph_domain); // Test URL weight (if activated) if (graphs.size() == 3) { Graph<Domain> url_graph = graphs.get(2); Graph<Domain> merged_graph_url = handler.computeFusionGraphs(graphs, handler.getMemory().getUser(), new double[]{0.0, 0.0, 1.0}, new double[]{0.8, 0.2}, "byUsers"); assertEquals(url_graph, merged_graph_url); } } /** * Test of the integrity of domains during fusion of users. * @throws IOException * @throws ClassNotFoundException */ public void testIntegrityFusionUsers() throws IOException, ClassNotFoundException { System.out.println("\nIntegrity : fusion of users"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setFeatureWeights(new double[]{0.7, 0.1, 0.2}); handler.getMemory().setFeatureOrderedWeights(new double[]{0.0, 0.0}); LinkedList<Graph<Domain>> merged_graph_users = handler.computeUsersGraph(); double[] users_weights = new double[merged_graph_users.size()]; for (int i = 0; i < merged_graph_users.size(); i++) { users_weights[i] = 1.0 / merged_graph_users.size(); } Graph<Domain> merged_graph = handler.computeFusionGraphs(merged_graph_users, "", users_weights, new double[] {0.0}, "all"); // Test presence of all the domains and requests after users fusion assertTrue(handler.getMemory().getAllDomains().get("all") .values().size() == merged_graph.size()); for (Domain dom_1 : handler.getMemory().getAllDomains().get("all").values()) { for (Domain dom_2 : merged_graph.getNodes()) { if (dom_1.getName().equals(dom_2.getName())) { assertTrue(dom_1.deepEquals(dom_2)); } } } // Test the lost of neighbors for (Graph<Domain> graph_temp : merged_graph_users) { String user_temp = graph_temp.getNodes().iterator() .next().element().getClient(); for (Domain dom : graph_temp.getNodes()) { NeighborList nl_temp = graph_temp.getNeighbors(dom); NeighborList nl_merged = merged_graph.getNeighbors( handler.getMemory().getAllDomains().get("all").get(dom.getName())); for (Neighbor<Domain> nb : nl_temp) { if (nb.similarity != 0) { assertTrue(nl_merged.containsNode( handler.getMemory().getAllDomains() .get("all").get(nb.node.getName()))); for (Neighbor<Domain> nb_merged : nl_merged) { if (nb_merged.node.getName() .equals(nb.node.getName())) { assertTrue(nb.node.deepEquals( handler.getMemory().getAllDomains() .get("byUsers").get(user_temp + ":" + nb_merged.node.getName()))); assertTrue(nb_merged.node.deepEquals( handler.getMemory().getAllDomains() .get("all").get(nb.node.getName()))); } } } } } } // Test the similarities for (Domain dom_11 : merged_graph.getNodes()) { NeighborList nl_dom_11 = merged_graph.getNeighbors(dom_11); for (Neighbor<Domain> dom_12 : nl_dom_11) { double similarity_temp = 0.0; for (int i = 0; i < merged_graph_users.size(); i++) { Graph<Domain> user_graph = merged_graph_users.get(i); String user_temp = user_graph.getNodes().iterator() .next().element().getClient(); for (Domain dom_21 : user_graph.getNodes()) { if (dom_21.deepEquals(handler.getMemory().getAllDomains() .get("byUsers").get(user_temp + ":" + dom_11.getName()))) { NeighborList nl_dom_21 = user_graph .getNeighbors(dom_21); for (Neighbor<Domain> dom_22 : nl_dom_21) { if (dom_22.node.deepEquals(handler.getMemory() .getAllDomains().get("byUsers") .get(user_temp + ":" + dom_12.node.getName()))) { similarity_temp += users_weights[i] * dom_22.similarity; } } } } } assertTrue(dom_12.similarity == similarity_temp); } } } /** * Test of the integrity of the computation of individual graphs. */ public void testIntegrityUsersGraphs() { System.out.println("\nIntegrity : users graphs"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setFeatureWeights(new double[]{0.7, 0.1, 0.2}); handler.getMemory().setFeatureOrderedWeights(new double[]{0.0, 0.0}); LinkedList<Graph<Domain>> merged_graph_users = handler.computeUsersGraph(); // Test assertTrue(handler.getMemory().getUsersList().size() == merged_graph_users.size()); } /** * Test of the integrity of domains during pruning * @throws IOException * @throws ClassNotFoundException */ public void testIntegrityDomainPruning() throws IOException, ClassNotFoundException { System.out.println("\nIntegrity : pruning"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getMemory().setStdout(""); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setFeatureWeights(new double[]{0.7, 0.1, 0.2}); handler.getMemory().setFeatureOrderedWeights(new double[]{0.0, 0.0}); LinkedList<Graph<Domain>> merged_graph_users = handler.computeUsersGraph(); double[] users_weights = new double[merged_graph_users.size()]; for (int i = 0; i < merged_graph_users.size(); i++) { users_weights[i] = 1.0 / merged_graph_users.size(); } handler.getMemory().setMergedGraph(handler.computeFusionGraphs( merged_graph_users, "", users_weights, new double[] {0.0}, "all")); ArrayList<Double> similarities = handler.listSimilarities(); Graph<Domain> merged_graph_1 = new Graph(handler.getMemory().getMergedGraph()); Graph<Domain> merged_graph_2 = new Graph(handler.getMemory().getMergedGraph()); assertEquals(merged_graph_1, handler.getMemory().getMergedGraph()); assertEquals(merged_graph_2, handler.getMemory().getMergedGraph()); // Test both method to prune handler.getMemory().setMeanVarSimilarities(Utility.getMeanVariance(similarities)); double prune_threshold = 0.01; handler.getMemory().setPruningThresholdTemp(prune_threshold); handler.getMemory().setPruneZBool(false); merged_graph_1 = handler.doPruning(merged_graph_1, (long) 0); assertFalse(merged_graph_1.equals(handler.getMemory().getMergedGraph())); handler.getMemory().setPruningThresholdTemp(0.0); handler.getMemory().setPruneZBool(true); merged_graph_2 = handler.doPruning(merged_graph_2, (long) 0); assertFalse(handler.getMemory().getMergedGraph().equals(merged_graph_2)); assertFalse(merged_graph_1.equals(merged_graph_2)); // Test presence of all domains // System.out.println("Before pruning = " + merged_graph.getNodes()); // System.out.println("After pruning (1) = " + merged_graph_1.getNodes()); // System.out.println("After pruning (2) = " + merged_graph_2.getNodes()); for (Domain dom_1 : handler.getMemory().getMergedGraph().getNodes()) { assertTrue(merged_graph_1.containsKey(dom_1)); assertTrue(merged_graph_2.containsKey(dom_1)); for (Domain dom_2 : merged_graph_1.getNodes()) { if (dom_1.getName().equals(dom_2.getName())) { assertTrue(dom_1.deepEquals(dom_2)); } } } // Test the lost of neighbors and the similarities for (Domain dom_11 : handler.getMemory().getMergedGraph().getNodes()) { NeighborList nl_dom_11 = handler.getMemory().getMergedGraph() .getNeighbors(dom_11); for (Neighbor<Domain> dom_12 : nl_dom_11) { // Pruning method 1 for (Domain dom_21 : merged_graph_1.getNodes()) { if (dom_21.getName().equals(dom_11.getName())) { NeighborList nl_dom_21 = merged_graph_1 .getNeighbors(dom_21); if (dom_12.similarity > prune_threshold) { assertTrue(nl_dom_21.containsNode(dom_12.node)); for (Neighbor<Domain> dom_22 : nl_dom_21) { if (dom_12.node.getName().equals(dom_22.node.getName())) { assertTrue(dom_12.similarity == dom_22.similarity); assertTrue(dom_12.node.deepEquals(dom_22.node)); assertTrue(dom_12.similarity == dom_22.similarity); } } } else { assertFalse(nl_dom_21.containsNode(dom_12)); } } } // Pruning method 2 for (Domain dom_21 : merged_graph_2.getNodes()) { if (dom_21.getName().equals(dom_11.getName())) { NeighborList nl_dom_21 = merged_graph_2 .getNeighbors(dom_21); if (dom_12.similarity > handler.getMemory().getMeanVarSimilarities()[0]) { assertTrue(nl_dom_21.containsNode(dom_12.node)); for (Neighbor<Domain> dom_22 : nl_dom_21) { if (dom_12.node.getName().equals(dom_22.node.getName())) { assertTrue(dom_12.similarity == dom_22.similarity); assertTrue(dom_12.node.deepEquals(dom_22.node)); assertTrue(dom_12.similarity == dom_22.similarity); } } } else { assertFalse(nl_dom_21.containsNode(dom_12)); } } } } } } /** * Test of the integrity of domains during clustering. * @throws IOException * @throws ClassNotFoundException */ public void testIntegrityDomainCluster() throws IOException, ClassNotFoundException { System.out.println("\nIntegrity : clusering"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setFeatureWeights(new double[]{0.7, 0.1, 0.2}); handler.getMemory().setFeatureOrderedWeights(new double[]{0.0, 0.0}); LinkedList<Graph<Domain>> merged_graph_users = handler.computeUsersGraph(); double[] users_weights = new double[merged_graph_users.size()]; for (int i = 0; i < merged_graph_users.size(); i++) { users_weights[i] = 1.0 / merged_graph_users.size(); } Graph<Domain> merged_graph = handler.computeFusionGraphs(merged_graph_users, "", users_weights, new double[] {0.0}, "all"); handler.getMemory().setPruningThresholdTemp(0.5); handler.getMemory().setPruneZBool(false); merged_graph = handler.doPruning(merged_graph, (long) 0); ArrayList<Graph<Domain>> clusters = merged_graph.connectedComponents(); // Test presence of all domains // System.out.println("After prune = " + merged_graph.getNodes()); // System.out.println("Clusters = " + clusters); boolean found_node; for (Domain dom_1 : merged_graph.getNodes()) { found_node = false; for (Graph<Domain> graph : clusters) { if (graph.containsKey(dom_1)) { for (Domain dom_2 : graph.getNodes()) { if (dom_1.deepEquals(dom_2)) { found_node = true; break; } } } } assertTrue(found_node); } // Test the lost of neighbors and similarities for (Domain dom_11 : merged_graph.getNodes()) { NeighborList nl_dom_11 = merged_graph.getNeighbors(dom_11); for (Neighbor<Domain> dom_12 : nl_dom_11) { for (Graph<Domain> graph : clusters) { for (Domain dom_21 : graph.getNodes()) { if (dom_11.getName().equals(dom_21.getName())) { NeighborList nl_dom_21 = graph.getNeighbors(dom_21); assertTrue(nl_dom_21.containsNode(dom_12.node)); for (Neighbor<Domain> dom_22 : nl_dom_21) { if (dom_12.node.getName() .equals(dom_22.node.getName())) { assertTrue(dom_12.node.deepEquals(dom_22.node)); assertTrue(dom_12.similarity == dom_22.similarity); } } } } } } } } /** * Test effectiveness of filtering. */ public void testFiltering() { System.out.println("\nTest : filtering"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir"); RequestHandler handler = new RequestHandler(input_dir); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setFeatureWeights(new double[]{0.7, 0.1, 0.2}); handler.getMemory().setFeatureOrderedWeights(new double[]{0.0, 0.0}); LinkedList<Graph<Domain>> merged_graph_users = handler.computeUsersGraph(); double[] users_weights = new double[merged_graph_users.size()]; for (int i = 0; i < merged_graph_users.size(); i++) { users_weights[i] = 1.0 / merged_graph_users.size(); } Graph<Domain> merged_graph = handler.computeFusionGraphs(merged_graph_users, "", users_weights, new double[] {0.0}, "all"); handler.getMemory().setPruningThresholdTemp(0.5); handler.getMemory().setPruneZBool(false); merged_graph = handler.doPruning(merged_graph, (long) 0); handler.getMemory().setClusters(merged_graph.connectedComponents()); // Method 1 handler.getMemory().setMaxClusterSizeTemp(10); handler.getMemory().setClusterZBool(false); handler.doFiltering(System.currentTimeMillis()); for (Graph<Domain> graph_1 : handler.getMemory().getClusters()) { if (graph_1.size() < 10) { boolean found_graph = false; for (Graph<Domain> graph_2 : handler.getMemory().getFiltered()) { if (graph_1.equals(graph_2)) { found_graph = true; break; } } assertTrue(found_graph); } } // Method 2 handler.getMemory().setMaxClusterSizeTemp(0); handler.getMemory().setClusterZBool(true); ArrayList<Double> cluster_sizes = handler.listClusterSizes( handler.getMemory().getClusters()); handler.getMemory().setMeanVarClusters(Utility.getMeanVariance(cluster_sizes)); handler.getMemory().setStdout(""); handler.doFiltering(System.currentTimeMillis()); for (Graph<Domain> graph_1 : handler.getMemory().getClusters()) { if (graph_1.size() < handler.getMemory().getMeanVarClusters()[0]) { boolean found_graph = false; for (Graph<Domain> graph_2 : handler.getMemory().getFiltered()) { if (graph_1.equals(graph_2)) { found_graph = true; break; } } assertTrue(found_graph); } } } /** * Test the effectiveness of the white listing of some node. * @throws java.io.IOException * @throws java.lang.ClassNotFoundException */ public void testWhiteListing() throws IOException, ClassNotFoundException { System.out.println("\nTest : white listing"); // Creation of the data Path input_dir = Paths.get("src/test/resources/dummyDir_whitelist"); RequestHandler handler = new RequestHandler(input_dir); handler.getMemory().setStdout(""); handler.getUsers(); handler.getMemory().setUsersList(handler.getMemory().getAllUsersList()); handler.loadUsersGraphs(System.currentTimeMillis()); handler.getMemory().setFeatureWeights(new double[]{0.7, 0.1, 0.2}); handler.getMemory().setFeatureOrderedWeights(new double[]{0.0, 0.0}); LinkedList<Graph<Domain>> merged_graph_users = handler.computeUsersGraph(); double[] users_weights = new double[merged_graph_users.size()]; for (int i = 0; i < merged_graph_users.size(); i++) { users_weights[i] = 1.0 / merged_graph_users.size(); } Graph<Domain> merged_graph = handler.computeFusionGraphs(merged_graph_users, "", users_weights, new double[] {0.0}, "all"); handler.getMemory().setClusters(merged_graph.connectedComponents()); handler.getMemory().setMaxClusterSizeTemp(1000); handler.getMemory().setClusterZBool(false); handler.doFiltering(System.currentTimeMillis()); // Test Graph<Domain> domain_graph = handler.getMemory().getFiltered().getFirst(); Domain domain_node_1 = new Domain(); Domain domain_node_2 = new Domain(); Domain domain_node_3 = new Domain(); for (Domain dom : domain_graph.getNodes()) { if (dom.getName().equals("stats.g.doubleclick.net")) { domain_node_1 = dom; } if (dom.getName().equals("ad.doubleclick.net")) { domain_node_2 = dom; } if (dom.getName().equals("ss.symcd.com")) { domain_node_3 = dom; } } Graph<Domain> domain_graph_new_1 = new Graph<Domain>(domain_graph); assertTrue(domain_graph.equals(domain_graph_new_1)); assertTrue(domain_graph_new_1.containsKey(domain_node_1)); assertTrue(domain_graph_new_1.containsKey(domain_node_2)); assertTrue(domain_graph_new_1.containsKey(domain_node_3)); handler.getMemory().setWhiteOngo("ss.symcd.com"); handler.getMemory().setNumberRequests(0); handler.whiteListing(); Graph<Domain> domain_graph_new_2 = handler.getMemory().getFilteredWhiteListed().getFirst(); assertFalse(domain_graph_new_2.containsKey(domain_node_1)); for (Domain dom : domain_graph_new_2.getNodes()) { NeighborList nl = domain_graph_new_2.getNeighbors(dom); for (Neighbor<Domain> nb : nl) { assertFalse(nb.node.deepEquals(domain_node_1)); } } assertFalse(domain_graph_new_2.containsKey(domain_node_2)); for (Domain dom : domain_graph_new_2.getNodes()) { NeighborList nl = domain_graph_new_2.getNeighbors(dom); for (Neighbor<Domain> nb : nl) { assertFalse(nb.node.deepEquals(domain_node_2)); } } assertFalse(domain_graph_new_2.containsKey(domain_node_3)); for (Domain dom : domain_graph_new_2.getNodes()) { NeighborList nl = domain_graph_new_2.getNeighbors(dom); for (Neighbor<Domain> nb : nl) { assertFalse(nb.node.deepEquals(domain_node_3)); } } // Test white listing by minimum number of requests (based on graph // without any domain to whitelist) handler.getMemory().setNumberRequests(2); handler.whiteListing(); Graph<Domain> domain_graph_new_3 = handler.getMemory().getFilteredWhiteListed().getFirst(); for (Domain dom : domain_graph_new_2.getNodes()) { for (String user : handler.getMemory().getUsersList()) { if (handler.getMemory().getAllDomains().get("byUsers").get(user + ":" + dom.getName()) != null) { if (handler.getMemory().getAllDomains().get("byUsers") .get(user + ":" + dom.getName()).toArray().length < 2) { assertFalse(domain_graph_new_3.containsKey(dom)); } else { assertTrue(domain_graph_new_3.containsKey(dom)); } } } } } public void testStages() throws IOException, ClassNotFoundException { System.out.println("\nTest Stages"); RequestHandler handler = new RequestHandler(Paths.get( "src/test/resources/dummyDir_whitelist")); handler.getUsers(); // Test Stage 0 Output out_0 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); Output out_1 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_0.equals(out_1)); Output out_2 = handler.analyze("253.115.106.54", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_1.equals(out_2)); Output out_3 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_3)); // Test Stage 1 Output out_4 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_4)); Output out_5 = handler.analyze("0.0.0.0", new double[]{0.7, 0.2, 0.1}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_4.equals(out_5)); Output out_6 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_4.equals(out_6)); // Test Stage 2 Output out_7 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_7)); Output out_8 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.0, 1000.0, true, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_7.equals(out_8)); Output out_9 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_7.equals(out_9)); // Test Stage 3 Output out_10 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_10)); Output out_11 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 1, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_10.equals(out_11)); Output out_12 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_10.equals(out_12)); // Test Stage 4 Output out_13 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_13)); Output out_14 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 0.0, false, true, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_13.equals(out_14)); Output out_15 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_13.equals(out_15)); // Test Stage 5 Output out_16 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_16)); Output out_17 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 5.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_16.equals(out_17)); Output out_18 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_16.equals(out_18)); // Test Stage 6 Output out_19 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_19)); Output out_20 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, false, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_19.equals(out_20)); Output out_21 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_19.equals(out_21)); // Test Stage 6 Output out_22 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_22)); Output out_23 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "e.visualdna.com", 2, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_22.equals(out_23)); Output out_24 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_22.equals(out_24)); // Test Stage 6 Output out_25 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_25)); Output out_26 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 1, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_25.equals(out_26)); Output out_27 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_25.equals(out_27)); // Test Stage 7 Output out_28 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_28)); Output out_29 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.5, 0.5, 0.0}, true); assertFalse(out_28.equals(out_29)); Output out_30 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_28.equals(out_30)); // Test Stage 7 Output out_31 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_1.equals(out_31)); Output out_32 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, false); assertFalse(out_31.equals(out_32)); Output out_33 = handler.analyze("0.0.0.0", new double[]{0.7, 0.3, 0.0}, new double[]{0.8, 0.2}, 0.02, 1000.0, false, false, true, "", 2, new double[]{0.45, 0.45, 0.1}, true); assertTrue(out_31.equals(out_33)); // Test integrity of Domains RequestHandler handler_bis = new RequestHandler(Paths.get( "src/test/resources/dummyDir/")); Output out_34 = handler_bis.analyze("202.154.66.0", new double[]{0.6, 0.4, 0.0}, new double[]{0.8, 0.2}, 0.02, 5, false, false, true, "", 1, new double[]{0.45, 0.45, 0.1}, true); Output out_35 = handler_bis.analyze("219.253.0.0", new double[]{0.6, 0.4, 0.0}, new double[]{0.8, 0.2}, 0.02, 5, false, false, true, "", 1, new double[]{0.45, 0.45, 0.1}, true); assertFalse(out_34.equals(out_35)); for (Graph<Domain> graph : out_34.getFilteredWhiteListed()) { for (Domain dom : graph.getNodes()) { for (Request req : dom) { assertFalse(req.getClient().startsWith("219.253.")); assertTrue(req.getClient().startsWith("202.154.66.")); } } } for (Graph<Domain> graph : out_35.getFilteredWhiteListed()) { for (Domain dom : graph.getNodes()) { for (Request req : dom) { assertFalse(req.getClient().startsWith("202.154.66.")); assertTrue(req.getClient().startsWith("219.253.")); } } } for (Entry<Double, LinkedList<Domain>> entry : out_34.getRanking().entrySet()) { for (Domain dom : entry.getValue()) { for (Request req : dom) { assertFalse(req.getClient().startsWith("219.253.")); assertTrue(req.getClient().startsWith("202.154.66.")); } } } for (Entry<Double, LinkedList<Domain>> entry : out_35.getRanking().entrySet()) { for (Domain dom : entry.getValue()) { for (Request req : dom) { assertFalse(req.getClient().startsWith("202.154.66.")); assertTrue(req.getClient().startsWith("219.253.")); } } } } }
package com.theoryinpractice.testng.model; import com.intellij.execution.Location; import com.intellij.execution.PsiLocation; import com.intellij.execution.testframework.Filter; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.junit2.states.StackTraceLine; import com.intellij.ide.util.EditSourceUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diff.LineTokenizer; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.pom.Navigatable; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.theoryinpractice.testng.ui.Printable; import com.theoryinpractice.testng.ui.TestNGConsoleView; import org.testng.remote.strprotocol.MessageHelper; import org.testng.remote.strprotocol.TestResultMessage; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class TestProxy implements AbstractTestProxy { private List<TestProxy> results = new ArrayList<TestProxy>(); private TestResultMessage resultMessage; private String name; private TestProxy parent; private List<Printable> output; private PsiElement psiElement; private boolean inProgress; private int myExceptionMark; public TestProxy() {} public TestProxy(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public PsiElement getPsiElement() { return psiElement; } public void setPsiElement(PsiElement psiElement) { this.psiElement = psiElement; } public boolean isResult() { return resultMessage != null; } public List<AbstractTestProxy> getResults(Filter filter) { return filter.select(results); } public List<Printable> getOutput() { if (output != null) return output; List<Printable> total = new ArrayList<Printable>(); for (TestProxy child : results) { total.addAll(child.getOutput()); } return total; } public List<TestProxy> getResults() { return results; } public TestResultMessage getResultMessage() { return resultMessage; } public void setResultMessage(final TestResultMessage resultMessage) { //if we have a result, then our parent is a class, so we can look up our method //this is a bit fragile as it assumes parent is set first and correctly ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { PsiClass psiClass = (PsiClass)getParent().getPsiElement(); PsiMethod[] methods = psiClass.getMethods(); for (PsiMethod method : methods) { if (method.getName().equals(resultMessage.getMethod())) { psiElement = method; break; } } } }); this.resultMessage = resultMessage; TestProxy current = this; while (current != null) { current.inProgress = resultMessage.getResult() == MessageHelper.TEST_STARTED; current = current.getParent(); } this.name = resultMessage.toDisplayString(); } public boolean isInProgress() { final TestProxy parentProxy = getParent(); return (parentProxy == null || parentProxy.isInProgress()) && inProgress; } public boolean isDefect() { return isNotPassed(); } public boolean shouldRun() { return true; } public int getMagnitude() { return -1; } public boolean isLeaf() { return isResult(); } public Location getLocation(final Project project) { if (psiElement == null) return null; return new PsiLocation<PsiElement>(project, psiElement); } public Navigatable getDescriptor(final Location location) { if (location == null) return null; if (isNotPassed() && output != null) { final PsiLocation<?> psiLocation = location.toPsiLocation(); final PsiClass containingClass = psiLocation.getParentElement(PsiClass.class); if (containingClass != null) { String containingMethod = null; for (Iterator<Location<PsiMethod>> iterator = psiLocation.getAncestors(PsiMethod.class, false); iterator.hasNext();) { final PsiMethod psiMethod = iterator.next().getPsiElement(); if (containingClass.equals(psiMethod.getContainingClass())) containingMethod = psiMethod.getName(); } if (containingMethod != null) { final String qualifiedName = containingClass.getQualifiedName(); for (Printable aStackTrace : output) { if (aStackTrace instanceof TestNGConsoleView.Chunk) { final String[] stackTrace = new LineTokenizer(((TestNGConsoleView.Chunk)aStackTrace).text).execute(); for (String line : stackTrace) { final StackTraceLine stackLine = new StackTraceLine(containingClass.getProject(), line); if (containingMethod.equals(stackLine.getMethodName()) && Comparing.strEqual(qualifiedName, stackLine.getClassName())) { return stackLine.getOpenFileDescriptor(containingClass.getContainingFile().getVirtualFile()); } } } } } } } return EditSourceUtil.getDescriptor(location.getPsiElement()); } public TestProxy[] getPathFromRoot() { ArrayList<TestProxy> arraylist = new ArrayList<TestProxy>(); TestProxy testproxy = this; do { arraylist.add(testproxy); } while ((testproxy = testproxy.getParent()) != null); Collections.reverse(arraylist); return arraylist.toArray(new TestProxy[arraylist.size()]); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final TestProxy testProxy = (TestProxy)o; if (name != null ? !name.equals(testProxy.name) : testProxy.name != null) return false; if (resultMessage != null ? !resultMessage.equals(testProxy.resultMessage) : testProxy.resultMessage != null) return false; return true; } @Override public int hashCode() { int result = resultMessage != null ? resultMessage.hashCode() : 0; result = 29 * result + (name != null ? name.hashCode() : 0); return result; } @Override public String toString() { return name + ' ' + results; } public void addResult(TestProxy proxy) { results.add(proxy); proxy.setParent(this); } public void setParent(TestProxy parent) { this.parent = parent; } public TestProxy getParent() { return parent; } public void setOutput(List<Printable> output) { this.output = output; } public boolean isNotPassed() { if (resultNotPassed()) return true; //we just added the node, so we don't know if it has passes or fails if (resultMessage == null && results.size() == 0) return true; for (TestProxy child : results) { if (child.isNotPassed()) return true; } return false; } private boolean resultNotPassed() { return resultMessage != null && resultMessage.getResult() != MessageHelper.PASSED_TEST; } public List<TestProxy> getAllTests() { List<TestProxy> total = new ArrayList<TestProxy>(); total.add(this); for (TestProxy child : results) { total.addAll(child.getAllTests()); } return total; } public int getChildCount() { return results.size(); } public TestProxy getChildAt(int i) { return results.get(i); } public TestProxy getFirstDefect() { for (TestProxy child : results) { if (child.isNotPassed() && child.isResult()) return child; TestProxy firstDefect = child.getFirstDefect(); if (firstDefect != null) return firstDefect; } return null; } public boolean childExists(String child) { for (int count = 0; count < getChildCount(); count++) { if (child.equals(getChildAt(count).getName())) { return true; } } return false; } public int getExceptionMark() { if (myExceptionMark == 0 && getChildCount() > 0) { return (output != null ? output.size() : 0) + getChildAt(0).getExceptionMark(); } return myExceptionMark; } public void setExceptionMark(int exceptionMark) { myExceptionMark = exceptionMark; } }
package org.batfish.main; import static org.batfish.common.plugin.PluginConsumer.DEFAULT_HEADER_LENGTH_BYTES; import static org.batfish.common.plugin.PluginConsumer.detectFormat; import com.google.common.base.Throwables; import com.google.common.io.Closer; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.io.Serializable; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; import javax.annotation.Nullable; import net.jpountz.lz4.LZ4FrameInputStream; import net.jpountz.lz4.LZ4FrameOutputStream; import org.apache.commons.lang3.exception.ExceptionUtils; import org.batfish.common.BatfishException; import org.batfish.common.BatfishLogger; import org.batfish.common.BfConsts; import org.batfish.common.Version; import org.batfish.common.plugin.PluginConsumer.Format; import org.batfish.common.util.CommonUtil; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.answers.ConvertConfigurationAnswerElement; /** A utility class that abstracts the underlying file system storage used by {@link Batfish}. */ final class BatfishStorage { private final BatfishLogger _logger; private final Path _containerDir; private final BiFunction<String, Integer, AtomicInteger> _newBatch; /** Create a new {@link BatfishStorage} instance that uses the given root path as a container. */ public BatfishStorage( Path containerDir, BatfishLogger logger, BiFunction<String, Integer, AtomicInteger> newBatch) { _containerDir = containerDir; _logger = logger; _newBatch = newBatch; } /** * Returns the compressed configuration files for the given testrig. If a serialized copy of these * configurations is not already present, then this function returns {@code null}. */ @Nullable public SortedMap<String, Configuration> loadCompressedConfigurations(String testrig) { Path testrigDir = getTestrigDir(testrig); Path indepDir = testrigDir.resolve(BfConsts.RELPATH_COMPRESSED_CONFIG_DIR); return loadConfigurations(testrig, indepDir); } /** * Returns the configuration files for the given testrig. If a serialized copy of these * configurations is not already present, then this function returns {@code null}. */ @Nullable public SortedMap<String, Configuration> loadConfigurations(String testrig) { Path testrigDir = getTestrigDir(testrig); Path indepDir = testrigDir.resolve(BfConsts.RELPATH_VENDOR_INDEPENDENT_CONFIG_DIR); return loadConfigurations(testrig, indepDir); } private SortedMap<String, Configuration> loadConfigurations(String testrig, Path indepDir) { // If the directory that would contain these configs does not even exist, no cache exists. if (!Files.exists(indepDir)) { _logger.debugf("Unable to load configs for %s from disk: no cache directory", testrig); return null; } // If the directory exists, then likely the configs exist and are useful. Still, we need to // confirm that they were serialized with a compatible version of Batfish first. if (!cachedConfigsAreCompatible(testrig)) { _logger.debugf( "Unable to load configs for %s from disk: error or incompatible version", testrig); return null; } _logger.info("\n*** DESERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n"); Map<Path, String> namesByPath = new TreeMap<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(indepDir)) { for (Path serializedConfig : stream) { String name = serializedConfig.getFileName().toString(); namesByPath.put(serializedConfig, name); } } catch (IOException e) { throw new BatfishException( "Error reading vendor-independent configs directory: '" + indepDir + "'", e); } try { return deserializeObjects(namesByPath, Configuration.class); } catch (BatfishException e) { return null; } } @Nullable public ConvertConfigurationAnswerElement loadConvertConfigurationAnswerElement(String testrig) { Path ccaePath = getTestrigDir(testrig).resolve(BfConsts.RELPATH_CONVERT_ANSWER_PATH); if (!Files.exists(ccaePath)) { return null; } try { return deserializeObject(ccaePath, ConvertConfigurationAnswerElement.class); } catch (BatfishException e) { _logger.errorf( "Failed to deserialize ConvertConfigurationAnswerElement: %s", ExceptionUtils.getStackTrace(e)); return null; } } /** * Stores the configurations into the compressed config path for the given testrig. Will replace * any previously-stored compressed configurations. */ public void storeCompressedConfigurations( Map<String, Configuration> configurations, String testrig) { Path testrigDir = getTestrigDir(testrig); if (!testrigDir.toFile().exists() && !testrigDir.toFile().mkdirs()) { throw new BatfishException( String.format("Unable to create testrig directory '%s'", testrigDir)); } Path outputDir = testrigDir.resolve(BfConsts.RELPATH_COMPRESSED_CONFIG_DIR); String batchName = String.format( "Serializing %s compressed configuration structures for testrig %s", configurations.size(), testrig); storeConfigurations(outputDir, batchName, configurations); } /** * Stores the configuration information into the given testrig. Will replace any previously-stored * configurations. */ public void storeConfigurations( Map<String, Configuration> configurations, ConvertConfigurationAnswerElement convertAnswerElement, String testrig) { Path testrigDir = getTestrigDir(testrig); if (!testrigDir.toFile().exists() && !testrigDir.toFile().mkdirs()) { throw new BatfishException( String.format("Unable to create testrig directory '%s'", testrigDir)); } // Save the convert configuration answer element. Path ccaePath = testrigDir.resolve(BfConsts.RELPATH_CONVERT_ANSWER_PATH); CommonUtil.deleteIfExists(ccaePath); serializeObject(convertAnswerElement, ccaePath); Path outputDir = testrigDir.resolve(BfConsts.RELPATH_VENDOR_INDEPENDENT_CONFIG_DIR); String batchName = String.format( "Serializing %s vendor-independent configuration structures for testrig %s", configurations.size(), testrig); storeConfigurations(outputDir, batchName, configurations); } private void storeConfigurations( Path outputDir, String batchName, Map<String, Configuration> configurations) { _logger.infof("\n*** %s***\n", batchName.toUpperCase()); AtomicInteger progressCount = _newBatch.apply(batchName, configurations.size()); // Delete any existing output, then recreate. CommonUtil.deleteDirectory(outputDir); if (!outputDir.toFile().exists() && !outputDir.toFile().mkdirs()) { throw new BatfishException( String.format("Unable to create output directory '%s'", outputDir)); } configurations .entrySet() .parallelStream() .forEach( e -> { Path currentOutputPath = outputDir.resolve(e.getKey()); serializeObject(e.getValue(), currentOutputPath); progressCount.incrementAndGet(); }); } /** * Returns a single object of the given class deserialized from the given file. Uses the {@link * BatfishStorage} default file encoding including serialization format and compression. */ private static <S extends Serializable> S deserializeObject(Path inputFile, Class<S> outputClass) throws BatfishException { try (Closer closer = Closer.create()) { FileInputStream fis = closer.register(new FileInputStream(inputFile.toFile())); PushbackInputStream pbstream = new PushbackInputStream(fis, DEFAULT_HEADER_LENGTH_BYTES); Format f = detectFormat(pbstream); ObjectInputStream ois; if (f == Format.GZIP) { GZIPInputStream gis = closer.register(new GZIPInputStream(pbstream, 8192 /* enlarge buffer */)); ois = new ObjectInputStream(gis); } else if (f == Format.LZ4) { LZ4FrameInputStream lis = closer.register(new LZ4FrameInputStream(pbstream)); ois = new ObjectInputStream(lis); } else if (f == Format.JAVA_SERIALIZED) { ois = new ObjectInputStream(pbstream); } else { throw new BatfishException( String.format("Could not detect format of the file %s", inputFile)); } closer.register(ois); return outputClass.cast(ois.readObject()); } catch (IOException | ClassNotFoundException | ClassCastException e) { throw new BatfishException( String.format( "Failed to deserialize object of type %s from file %s", outputClass.getCanonicalName(), inputFile), e); } } private <S extends Serializable> SortedMap<String, S> deserializeObjects( Map<Path, String> namesByPath, Class<S> outputClass) { String outputClassName = outputClass.getName(); AtomicInteger completed = _newBatch.apply( String.format("Deserializing objects of type '%s' from files", outputClassName), namesByPath.size()); return new TreeMap<>( namesByPath .entrySet() .parallelStream() .collect( Collectors.toMap( Entry::getValue, entry -> { Path inputPath = entry.getKey(); String name = entry.getValue(); _logger.debugf( "Reading %s '%s' from '%s'\n", outputClassName, name, inputPath); S output = deserializeObject(inputPath, outputClass); completed.incrementAndGet(); return output; }))); } /** * Writes a single object of the given class to the given file. Uses the {@link BatfishStorage} * default file encoding including serialization format and compression. */ private static void serializeObject(Serializable object, Path outputFile) { try { try (OutputStream out = Files.newOutputStream(outputFile); LZ4FrameOutputStream gos = new LZ4FrameOutputStream(out); ObjectOutputStream oos = new ObjectOutputStream(gos)) { oos.writeObject(object); } } catch (IOException e) { throw new BatfishException("Failed to serialize object to output file: " + outputFile, e); } } private boolean cachedConfigsAreCompatible(String testrig) { try { ConvertConfigurationAnswerElement ccae = loadConvertConfigurationAnswerElement(testrig); return ccae != null && Version.isCompatibleVersion( BatfishStorage.class.getCanonicalName(), "Old processed configurations", ccae.getVersion()); } catch (BatfishException e) { _logger.warnf( "Unexpected exception caught while deserializing configs for testrig %s: %s", testrig, Throwables.getStackTraceAsString(e)); return false; } } private Path getTestrigDir(String testrig) { return _containerDir.resolve(BfConsts.RELPATH_TESTRIGS_DIR).resolve(testrig); } }
package net.wurstclient.features.mods.retro; import net.minecraft.network.play.client.CPacketPlayer; import net.wurstclient.compatibility.WConnection; import net.wurstclient.compatibility.WMinecraft; import net.wurstclient.events.listeners.UpdateListener; import net.wurstclient.features.Mod; import net.wurstclient.settings.CheckboxSetting; import net.wurstclient.settings.SliderSetting; import net.wurstclient.settings.SliderSetting.ValueDisplay; @Mod.Bypasses(ghostMode = false, latestNCP = false, olderNCP = false) public final class RegenMod extends RetroMod implements UpdateListener { private final SliderSetting speed = new SliderSetting("Speed", 100, 10, 1000, 10, ValueDisplay.INTEGER); private final CheckboxSetting pauseInMidAir = new CheckboxSetting("Pause in mid-air", true); public RegenMod() { super("Regen", "Regenerates your health much faster.\n" + "Can sometimes get you kicked for \"Flying is not enabled\"."); } @Override public void initSettings() { settings.add(speed); settings.add(pauseInMidAir); } @Override public void onEnable() { wurst.events.add(UpdateListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); } @Override public void onUpdate() { if(WMinecraft.getPlayer().capabilities.isCreativeMode || WMinecraft.getPlayer().getHealth() == 0) return; if(pauseInMidAir.isChecked() && !WMinecraft.getPlayer().onGround) return; if(WMinecraft.getPlayer().getFoodStats().getFoodLevel() < 18) return; if(WMinecraft.getPlayer().getHealth() >= WMinecraft.getPlayer() .getMaxHealth()) return; for(int i = 0; i < speed.getValueI(); i++) WConnection.sendPacket(new CPacketPlayer()); } }
package nl.idgis.publisher.job; import java.sql.Timestamp; import java.util.List; import java.util.concurrent.TimeUnit; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import nl.idgis.publisher.database.messages.CreateHarvestJob; import nl.idgis.publisher.database.messages.CreateImportJob; import nl.idgis.publisher.database.messages.DatasetStatus; import nl.idgis.publisher.database.messages.GetDataSourceStatus; import nl.idgis.publisher.database.messages.DataSourceStatus; import nl.idgis.publisher.database.messages.GetDatasetStatus; import nl.idgis.publisher.domain.job.JobState; import nl.idgis.publisher.domain.service.Column; import nl.idgis.publisher.utils.TypedIterable; import akka.actor.ActorRef; import akka.actor.Props; import akka.event.Logging; import akka.event.LoggingAdapter; public class Creator extends Scheduled { private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); private final ActorRef database; private static final FiniteDuration HARVEST_INTERVAL = Duration.create(15, TimeUnit.MINUTES); public Creator(ActorRef database) { this.database = database; } public static Props props(ActorRef database) { return Props.create(Creator.class, database); } @Override protected void doElse(Object msg) { log.debug("message received: "+ msg); if(msg instanceof TypedIterable) { doIterable((TypedIterable<?>)msg); } else { unhandled(msg); } } private void scheduleImportJobs(Iterable<DatasetStatus> datasetStatuses) { log.debug("scheduling import jobs"); for(DatasetStatus datasetStatus : datasetStatuses) { String datasetId = datasetStatus.getDatasetId(); Timestamp importedRevision = datasetStatus.getImportedRevision(); if(importedRevision == null) { log.debug("not yet imported"); } else { Timestamp revision = datasetStatus.getRevision(); if(revision.getTime() != importedRevision.getTime()) { log.debug("revision changed"); List<Column> columns = datasetStatus.getColumns(); List<Column> importedColumns = datasetStatus.getColumns(); if(columns.equals(importedColumns)) { log.debug("columns unchanged"); } else { log.debug("columns changed -> needs confirmation"); continue; } } else { log.debug("no imported need for: " + datasetId); continue; } } log.debug("creating import job for: " + datasetId); database.tell(new CreateImportJob(datasetId), getSelf()); } } private void scheduleHarvestJobs(Iterable<DataSourceStatus> dataSourceStatuses) { log.debug("scheduling harvest jobs"); for(DataSourceStatus dataSourceStatus : dataSourceStatuses) { final String dataSourceId = dataSourceStatus.getDataSourceId(); final JobState state = dataSourceStatus.getFinishedState(); final Timestamp time = dataSourceStatus.getLastHarvested(); final long timeDiff; if(time != null) { timeDiff = System.currentTimeMillis() - time.getTime(); } else { timeDiff = Long.MAX_VALUE; } if(!JobState.SUCCEEDED.equals(state) || timeDiff > HARVEST_INTERVAL.toMillis()) { log.debug("creating harvest job for: " + dataSourceId); database.tell(new CreateHarvestJob(dataSourceId), getSelf()); } else { log.debug("not yet creating harvest job for: " + dataSourceId); } } } private void doIterable(TypedIterable<?> msg) { if(msg.contains(DataSourceStatus.class)) { scheduleHarvestJobs(msg.cast(DataSourceStatus.class)); } else if(msg.contains(DatasetStatus.class)) { scheduleImportJobs(msg.cast(DatasetStatus.class)); } else { unhandled(msg); } } @Override protected void doInitiate() { log.debug("requesting statuses"); database.tell(new GetDataSourceStatus(), getSelf()); database.tell(new GetDatasetStatus(), getSelf()); } }
package querqy.parser; import java.util.regex.Pattern; import com.google.common.base.Splitter; import querqy.model.Clause.Occur; import querqy.model.DisjunctionMaxQuery; import querqy.model.Query; import querqy.model.Term; public class WhiteSpaceQuerqyParser implements QuerqyParser { private final static Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); /* * (non-Javadoc) * * @see querqy.parser.QuerqyParser#parse(java.lang.String) */ @Override public Query parse(String input) { Query query = new Query(); for (String token : Splitter.on(WHITESPACE_PATTERN).split(input)) { Occur occur = Occur.SHOULD; if (token.length() > 1) { if (token.startsWith("+")) { occur = Occur.MUST; token = token.substring(1); } else if (token.startsWith("-")) { occur = Occur.MUST_NOT; token = token.substring(1); } } DisjunctionMaxQuery dmq = new DisjunctionMaxQuery(query, occur, false); query.addClause(dmq); dmq.addClause(new Term(dmq, token)); } return query; } }
package com.rexsl.page; import com.jcabi.log.Logger; import java.net.URI; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; final class ForwardedUriInfo implements UriInfo { /** * Original {@link UriInfo}. */ private final transient UriInfo info; /** * Http headers, injected by JAX-RS implementation. */ private final transient AtomicReference<HttpHeaders> headers; /** * TRUE if HTTP headers already where analyzed. */ private transient boolean analyzed; /** * New host, or empty string if not required, or NULL if not yet sure. */ private transient String host; /** * Scheme to set, or NULL if not necessary. */ private transient String scheme; /** * Public ctor. * @param inf The original UriInfo * @param hdrs HTTP headers */ public ForwardedUriInfo(final UriInfo inf, final AtomicReference<HttpHeaders> hdrs) { if (inf == null) { throw new IllegalStateException( "UriInfo is incorrectly injected into BaseResource" ); } this.info = inf; this.headers = hdrs; } /** * {@inheritDoc} */ @Override public URI getAbsolutePath() { return this.getAbsolutePathBuilder().build(); } /** * {@inheritDoc} */ @Override public UriBuilder getAbsolutePathBuilder() { return this.forward(this.info.getAbsolutePathBuilder()); } /** * {@inheritDoc} */ @Override public URI getBaseUri() { return this.getBaseUriBuilder().build(); } /** * {@inheritDoc} */ @Override public UriBuilder getBaseUriBuilder() { return this.forward(this.info.getBaseUriBuilder()); } /** * {@inheritDoc} */ @Override public URI getRequestUri() { return this.getRequestUriBuilder().build(); } /** * {@inheritDoc} */ @Override public UriBuilder getRequestUriBuilder() { return this.forward(this.info.getRequestUriBuilder()); } /** * {@inheritDoc} */ @Override public List<Object> getMatchedResources() { return this.info.getMatchedResources(); } /** * {@inheritDoc} */ @Override public List<String> getMatchedURIs() { return this.info.getMatchedURIs(); } /** * {@inheritDoc} */ @Override public List<String> getMatchedURIs(final boolean decode) { return this.info.getMatchedURIs(decode); } /** * {@inheritDoc} */ @Override public String getPath() { return this.info.getPath(); } /** * {@inheritDoc} */ @Override public String getPath(final boolean decode) { return this.info.getPath(decode); } /** * {@inheritDoc} */ @Override public MultivaluedMap<String, String> getPathParameters() { return this.info.getPathParameters(); } /** * {@inheritDoc} */ @Override public MultivaluedMap<String, String> getPathParameters( final boolean decode) { return this.info.getPathParameters(decode); } /** * {@inheritDoc} */ @Override public List<PathSegment> getPathSegments() { return this.info.getPathSegments(); } /** * {@inheritDoc} */ @Override public List<PathSegment> getPathSegments(final boolean decode) { return this.info.getPathSegments(decode); } /** * {@inheritDoc} */ @Override public MultivaluedMap<String, String> getQueryParameters() { return this.info.getQueryParameters(); } /** * {@inheritDoc} */ @Override public MultivaluedMap<String, String> getQueryParameters( final boolean decode) { return this.info.getQueryParameters(decode); } /** * Forward this builder to the right host/port (if necessary). * @param builder The builder to forward * @return The same builder */ private UriBuilder forward(final UriBuilder builder) { if (!this.analyzed) { if (this.headers.get() == null) { throw new IllegalStateException( "HttpHeaders is not injected into BaseResource" ); } for (Map.Entry<String, List<String>> header : this.headers.get().getRequestHeaders().entrySet()) { for (String value : header.getValue()) { this.consume(header.getKey(), value); } } Logger.debug( this, "#forward(..): analyzed, host=%s, scheme=%s", this.host, this.scheme ); this.analyzed = true; } if (this.host != null) { builder.host(this.host); } if (this.scheme != null) { builder.scheme(this.scheme); } return builder; } private void consume(final String name, final String value) { if (this.host == null && "x-forwarded-host".equals(name.toLowerCase(Locale.ENGLISH))) { this.host = value; } else if (this.scheme == null && "x-forwarded-proto".equals(name.toLowerCase(Locale.ENGLISH))) { this.scheme = value; } else if ("forwarded".equals(name.toLowerCase(Locale.ENGLISH))) { this.forwarded(value); } } /** * Consume specifically "Forwarded" header. * @param value HTTP header value */ private void forwarded(final String value) { for (String sector : value.split("\\s*,\\s*")) { for (String opt : sector.split("\\s*;\\s*")) { final String[] parts = opt.split("=", 2); if (this.host == null && "host".equals(parts[0])) { this.host = parts[1]; } if (this.scheme == null && "proto".equals(parts[0])) { this.scheme = parts[1]; } } } } }
package org.fxmisc.richtext; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.IntUnaryOperator; import javafx.beans.NamedArg; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import javafx.css.CssMetaData; import javafx.css.PseudoClass; import javafx.css.StyleConverter; import javafx.css.Styleable; import javafx.css.StyleableObjectProperty; import javafx.event.Event; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.IndexRange; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.TextFlow; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; import org.fxmisc.flowless.Virtualized; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.model.Codec; import org.fxmisc.richtext.model.EditableStyledDocument; import org.fxmisc.richtext.model.GenericEditableStyledDocument; import org.fxmisc.richtext.model.Paragraph; import org.fxmisc.richtext.model.ReadOnlyStyledDocument; import org.fxmisc.richtext.model.PlainTextChange; import org.fxmisc.richtext.model.RichTextChange; import org.fxmisc.richtext.model.SegmentOps; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyledDocument; import org.fxmisc.richtext.model.StyledSegment; import org.fxmisc.richtext.model.TextOps; import org.fxmisc.richtext.model.TwoDimensional; import org.fxmisc.richtext.model.TwoLevelNavigator; import org.fxmisc.richtext.event.MouseOverTextEvent; import org.fxmisc.richtext.util.UndoUtils; import org.fxmisc.undo.UndoManager; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.Guard; import org.reactfx.Subscription; import org.reactfx.Suspendable; import org.reactfx.SuspendableEventStream; import org.reactfx.SuspendableNo; import org.reactfx.collection.LiveList; import org.reactfx.collection.SuspendableList; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; import org.reactfx.value.Var; public class GenericStyledArea<PS, SEG, S> extends Region implements TextEditingArea<PS, SEG, S>, EditActions<PS, SEG, S>, ClipboardActions<PS, SEG, S>, NavigationActions<PS, SEG, S>, StyleActions<PS, S>, UndoActions, ViewActions<PS, SEG, S>, TwoDimensional, Virtualized { /** * Index range [0, 0). */ public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0); private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("read-only"); private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret"); private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph"); private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph"); /** * Background fill for highlighted text. */ private final StyleableObjectProperty<Paint> highlightFill = new CustomStyleableProperty<>(Color.DODGERBLUE, "highlightFill", this, HIGHLIGHT_FILL); /** * Text color for highlighted text. */ private final StyleableObjectProperty<Paint> highlightTextFill = new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL); /** * Controls the blink rate of the caret, when one is displayed. Setting * the duration to zero disables blinking. */ private final StyleableObjectProperty<javafx.util.Duration> caretBlinkRate = new CustomStyleableProperty<>(javafx.util.Duration.millis(500), "caretBlinkRate", this, CARET_BLINK_RATE); // editable property private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) { @Override protected void invalidated() { ((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get()); } }; @Override public final boolean isEditable() { return editable.get(); } @Override public final void setEditable(boolean value) { editable.set(value); } @Override public final BooleanProperty editableProperty() { return editable; } // wrapText property private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText"); @Override public final boolean isWrapText() { return wrapText.get(); } @Override public final void setWrapText(boolean value) { wrapText.set(value); } @Override public final BooleanProperty wrapTextProperty() { return wrapText; } // undo manager private UndoManager undoManager; @Override public UndoManager getUndoManager() { return undoManager; } @Override public void setUndoManager(UndoManager undoManager) { this.undoManager.close(); this.undoManager = undoManager; } private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null); @Override public void setMouseOverTextDelay(Duration delay) { mouseOverTextDelay.set(delay); } @Override public Duration getMouseOverTextDelay() { return mouseOverTextDelay.get(); } @Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; } private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null); @Override public void setParagraphGraphicFactory(IntFunction<? extends Node> factory) { paragraphGraphicFactory.set(factory); } @Override public IntFunction<? extends Node> getParagraphGraphicFactory() { return paragraphGraphicFactory.get(); } @Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; } private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null); @Override public final ContextMenu getContextMenu() { return contextMenu.get(); } @Override public final void setContextMenu(ContextMenu menu) { contextMenu.setValue(menu); } @Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; } protected final boolean isContextMenuPresent() { return contextMenu.get() != null; } private double contextMenuXOffset = 2; @Override public final double getContextMenuXOffset() { return contextMenuXOffset; } @Override public final void setContextMenuXOffset(double offset) { contextMenuXOffset = offset; } private double contextMenuYOffset = 2; @Override public final double getContextMenuYOffset() { return contextMenuYOffset; } @Override public final void setContextMenuYOffset(double offset) { contextMenuYOffset = offset; } private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty(); @Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; } @Override public void setUseInitialStyleForInsertion(boolean value) { useInitialStyleForInsertion.set(value); } @Override public boolean getUseInitialStyleForInsertion() { return useInitialStyleForInsertion.get(); } private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty(); @Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) { styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec)); } @Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() { return styleCodecs; } @Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); } @Override public double getEstimatedScrollX() { return virtualFlow.estimatedScrollXProperty().getValue(); } @Override public void setEstimatedScrollX(double value) { virtualFlow.estimatedScrollXProperty().setValue(value); } @Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); } @Override public double getEstimatedScrollY() { return virtualFlow.estimatedScrollYProperty().getValue(); } @Override public void setEstimatedScrollY(double value) { virtualFlow.estimatedScrollYProperty().setValue(value); } private final Property<Consumer<MouseEvent>> onOutsideSelectionMousePress = new SimpleObjectProperty<>(e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.CLEAR); }); @Override public final void setOnOutsideSelectionMousePress(Consumer<MouseEvent> consumer) { onOutsideSelectionMousePress.setValue(consumer); } @Override public final Consumer<MouseEvent> getOnOutsideSelectionMousePress() { return onOutsideSelectionMousePress.getValue(); } private final Property<Consumer<MouseEvent>> onInsideSelectionMousePressRelease = new SimpleObjectProperty<>(e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.CLEAR); }); @Override public final void setOnInsideSelectionMousePressRelease(Consumer<MouseEvent> consumer) { onInsideSelectionMousePressRelease.setValue(consumer); } @Override public final Consumer<MouseEvent> getOnInsideSelectionMousePressRelease() { return onInsideSelectionMousePressRelease.getValue(); } private final Property<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); @Override public final void setOnNewSelectionDrag(Consumer<Point2D> consumer) { onNewSelectionDrag.setValue(consumer); } @Override public final Consumer<Point2D> getOnNewSelectionDrag() { return onNewSelectionDrag.getValue(); } private final Property<Consumer<MouseEvent>> onNewSelectionDragEnd = new SimpleObjectProperty<>(e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); @Override public final void setOnNewSelectionDragEnd(Consumer<MouseEvent> consumer) { onNewSelectionDragEnd.setValue(consumer); } @Override public final Consumer<MouseEvent> getOnNewSelectionDragEnd() { return onNewSelectionDragEnd.getValue(); } private final Property<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); displaceCaret(hit.getInsertionIndex()); }); @Override public final void setOnSelectionDrag(Consumer<Point2D> consumer) { onSelectionDrag.setValue(consumer); } @Override public final Consumer<Point2D> getOnSelectionDrag() { return onSelectionDrag.getValue(); } private final Property<Consumer<MouseEvent>> onSelectionDrop = new SimpleObjectProperty<>(e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveSelectedText(hit.getInsertionIndex()); }); @Override public final void setOnSelectionDrop(Consumer<MouseEvent> consumer) { onSelectionDrop.setValue(consumer); } @Override public final Consumer<MouseEvent> getOnSelectionDrop() { return onSelectionDrop.getValue(); } // not a hook, but still plays a part in the default mouse behavior private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true); @Override public final void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); } @Override public final boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); } // text @Override public final String getText() { return content.getText(); } @Override public final ObservableValue<String> textProperty() { return content.textProperty(); } // rich text @Override public final StyledDocument<PS, SEG, S> getDocument() { return content; } private final CaretSelectionBind<PS, SEG, S> caretSelectionBind; @Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; } // length @Override public final int getLength() { return content.getLength(); } @Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); } // paragraphs @Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); } private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs; @Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; } // beingUpdated private final SuspendableNo beingUpdated = new SuspendableNo(); @Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; } @Override public final boolean isBeingUpdated() { return beingUpdated.get(); } // total width estimate @Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); } @Override public double getTotalWidthEstimate() { return virtualFlow.totalWidthEstimateProperty().getValue(); } // total height estimate @Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); } @Override public double getTotalHeightEstimate() { return virtualFlow.totalHeightEstimateProperty().getValue(); } // text changes @Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); } // rich text changes @Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); } private final SuspendableEventStream<?> viewportDirty; @Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; } private Subscription subscriptions = () -> {}; private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow; // used for two-level navigation, where on the higher level are // paragraphs and on the lower level are lines within a paragraph private final TwoLevelNavigator paragraphLineNavigator; private boolean followCaretRequested = false; private final EditableStyledDocument<PS, SEG, S> content; @Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; } private final S initialTextStyle; @Override public final S getInitialTextStyle() { return initialTextStyle; } private final PS initialParagraphStyle; @Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; } private final BiConsumer<TextFlow, PS> applyParagraphStyle; @Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; } // TODO: Currently, only undo/redo respect this flag. private final boolean preserveStyle; @Override public final boolean isPreserveStyle() { return preserveStyle; } private final TextOps<SEG, S> segmentOps; @Override public final SegmentOps<SEG, S> getSegOps() { return segmentOps; } private final EventStream<Boolean> autoCaretBlinksSteam; final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; } private final EventStream<javafx.util.Duration> caretBlinkRateStream; final EventStream<javafx.util.Duration> caretBlinkRateEvents() { return caretBlinkRateStream; } final EventStream<?> boundsDirtyFor(EventStream<?> dirtyStream) { return EventStreams.merge(viewportDirty, dirtyStream).suppressWhen(beingUpdatedProperty()); } /** * Creates a text area with empty text content. * * @param initialParagraphStyle style to use in places where no other style is * specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is * specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param nodeFactory A function which is used to create the JavaFX scene nodes for a * particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory); } /** * Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one * to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory); } /** * The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that * this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same * {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory); } /** * Creates an area with flexibility in all of its options. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param document the document to render and edit * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this.initialTextStyle = initialTextStyle; this.initialParagraphStyle = initialParagraphStyle; this.preserveStyle = preserveStyle; this.content = document; this.applyParagraphStyle = applyParagraphStyle; this.segmentOps = segmentOps; undoManager = UndoUtils.defaultUndoManager(this); // allow tab traversal into area setFocusTraversable(true); this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); getStyleClass().add("styled-text-area"); getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm()); // keeps track of currently used non-empty cells @SuppressWarnings("unchecked") ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet(); // Initialize content virtualFlow = VirtualFlow.createVertical( getParagraphs(), par -> { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell( par, applyParagraphStyle, nodeFactory); nonEmptyCells.add(cell.getNode()); return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode())) .afterUpdateItem(p -> nonEmptyCells.add(cell.getNode())); }); getChildren().add(virtualFlow); // initialize navigator IntSupplier cellCount = () -> getParagraphs().size(); IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount(); paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength); viewportDirty = merge( // no need to check for width & height invalidations as scroll values update when these do // scale invalidationsOf(scaleXProperty()), invalidationsOf(scaleYProperty()), // scroll invalidationsOf(estimatedScrollXProperty()), invalidationsOf(estimatedScrollYProperty()) ).suppressible(); autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty() .and(editableProperty()) .and(disabledProperty().not()) ); caretBlinkRateStream = EventStreams.valuesOf(caretBlinkRate); caretSelectionBind = new CaretSelectionBindImpl<>(this); manageSubscription(caretSelectionBind::dispose); visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable(); final Suspendable omniSuspendable = Suspendable.combine( beingUpdated, // must be first, to be the last one to release visibleParagraphs ); manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty())); // dispatch MouseOverTextEvents when mouseOverTextDelay is not null EventStreams.valuesOf(mouseOverTextDelayProperty()) .flatMap(delay -> delay != null ? mouseOverTextEvents(nonEmptyCells, delay) : EventStreams.never()) .subscribe(evt -> Event.fireEvent(this, evt)); new GenericStyledAreaBehavior(this); } /** * Returns x coordinate of the caret in the current paragraph. */ final ParagraphBox.CaretOffsetX getCaretOffsetX(int paragraphIndex) { return getCell(paragraphIndex).getCaretOffsetX(); } CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) { int parIdx = targetLine.getMajor(); ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode(); CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor()); return parHit.offset(getParagraphOffset(parIdx)); } CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) { // don't account for padding here since height of virtualFlow is used, not area + potential padding VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hitText(x, cellOffset.getY()); return parHit.offset(parOffset); } } @Override public final double getViewportHeight() { return virtualFlow.getHeight(); } @Override public final Optional<Integer> allParToVisibleParIndex(int allParIndex) { if (allParIndex < 0) { throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + allParIndex); } if (allParIndex >= getVisibleParagraphs().size()) { throw new IllegalArgumentException(String.format( "Paragraphs' last index is [%s] but allParIndex was [%s]", getParagraphs().size() - 1, allParIndex) ); } Paragraph<PS, SEG, S> p = getParagraph(allParIndex); for (int index = 0; index < getVisibleParagraphs().size(); index++) { if (getVisibleParagraphs().get(index) == p) { return Optional.of(index); } } return Optional.empty(); } @Override public final int visibleParToAllParIndex(int visibleParIndex) { if (visibleParIndex < 0) { throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex); } if (visibleParIndex >= getVisibleParagraphs().size()) { throw new IllegalArgumentException(String.format( "Visible paragraphs' last index is [%s] but visibleParIndex was [%s]", getVisibleParagraphs().size() - 1, visibleParIndex) ); } Paragraph<PS, SEG, S> visibleP = getVisibleParagraphs().get(visibleParIndex); for (int index = 0; index < getParagraphs().size(); index++) { if (getParagraph(index) == visibleP) { return index; } } throw new AssertionError("Unreachable code"); } @Override public final int firstVisibleParToAllParIndex() { return visibleParToAllParIndex(0); } @Override public final int lastVisibleParToAllParIndex() { return visibleParToAllParIndex(visibleParagraphs.size() - 1); } @Override public CharacterHit hit(double x, double y) { // mouse position used, so account for padding double adjustedX = x - getInsets().getLeft(); double adjustedY = y - getInsets().getTop(); VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(adjustedX, adjustedY); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hit(cellOffset); return parHit.offset(parOffset); } } /** * Returns the current line as a two-level index. * The major number is the paragraph index, the minor * number is the line number within the paragraph. * * <p>This method has a side-effect of bringing the current * paragraph to the viewport if it is not already visible. */ TwoDimensional.Position currentLine() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); int lineIdx = cell.getNode().getCurrentLineIndex(); return paragraphLineNavigator.position(parIdx, lineIdx); } @Override public final int lineIndex(int paragraphIndex, int columnPosition) { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(paragraphIndex); return cell.getNode().getCurrentLineIndex(columnPosition); } @Override public int getParagraphLinesCount(int paragraphIndex) { return virtualFlow.getCell(paragraphIndex).getNode().getLineCount(); } @Override public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) { if (from < 0) { throw new IllegalArgumentException("From is negative: " + from); } if (from > to) { throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to)); } if (to > getLength()) { throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to)); } // no bounds exist if range is just a newline character if (getText(from, to).equals("\n")) { return Optional.empty(); } // if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose // minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it. int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from; Position startPosition = offsetToPosition(realFrom, Bias.Forward); int startRow = startPosition.getMajor(); Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward); int endRow = endPosition.getMajor(); if (startRow == endRow) { return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor()); } else { Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(), getParagraph(startRow).length()); for (int i = startRow + 1; i <= endRow; i++) { Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0, i == endRow ? endPosition.getMinor() : getParagraph(i).length() ); if (nextLineBounds.isPresent()) { if (rangeBounds.isPresent()) { Bounds lineBounds = nextLineBounds.get(); rangeBounds = rangeBounds.map(b -> { double minX = Math.min(b.getMinX(), lineBounds.getMinX()); double minY = Math.min(b.getMinY(), lineBounds.getMinY()); double maxX = Math.max(b.getMaxX(), lineBounds.getMaxX()); double maxY = Math.max(b.getMaxY(), lineBounds.getMaxY()); return new BoundingBox(minX, minY, maxX - minX, maxY - minY); }); } else { rangeBounds = nextLineBounds; } } } return rangeBounds; } } @Override public final String getText(int start, int end) { return content.getText(start, end); } @Override public String getText(int paragraph) { return content.getText(paragraph); } @Override public String getText(IndexRange range) { return content.getText(range); } @Override public StyledDocument<PS, SEG, S> subDocument(int start, int end) { return content.subSequence(start, end); } @Override public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) { return content.subDocument(paragraphIndex); } @Override public IndexRange getParagraphSelection(Selection selection, int paragraph) { int startPar = selection.getStartParagraphIndex(); int endPar = selection.getEndParagraphIndex(); if(paragraph < startPar || paragraph > endPar) { return EMPTY_RANGE; } int start = paragraph == startPar ? selection.getStartColumnPosition() : 0; int end = paragraph == endPar ? selection.getEndColumnPosition() : getParagraphLength(paragraph) + 1; // force rangeProperty() to be valid selection.getRange(); return new IndexRange(start, end); } @Override public S getStyleOfChar(int index) { return content.getStyleOfChar(index); } @Override public S getStyleAtPosition(int position) { return content.getStyleAtPosition(position); } @Override public IndexRange getStyleRangeAtPosition(int position) { return content.getStyleRangeAtPosition(position); } @Override public StyleSpans<S> getStyleSpans(int from, int to) { return content.getStyleSpans(from, to); } @Override public S getStyleOfChar(int paragraph, int index) { return content.getStyleOfChar(paragraph, index); } @Override public S getStyleAtPosition(int paragraph, int position) { return content.getStyleAtPosition(paragraph, position); } @Override public IndexRange getStyleRangeAtPosition(int paragraph, int position) { return content.getStyleRangeAtPosition(paragraph, position); } @Override public StyleSpans<S> getStyleSpans(int paragraph) { return content.getStyleSpans(paragraph); } @Override public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) { return content.getStyleSpans(paragraph, from, to); } @Override public int getAbsolutePosition(int paragraphIndex, int columnIndex) { return content.getAbsolutePosition(paragraphIndex, columnIndex); } @Override public Position position(int row, int col) { return content.position(row, col); } @Override public Position offsetToPosition(int charOffset, Bias bias) { return content.offsetToPosition(charOffset, bias); } @Override public void scrollXToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollXToPixel(pixel)); } @Override public void scrollYToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollYToPixel(pixel)); } @Override public void scrollXBy(double deltaX) { suspendVisibleParsWhile(() -> virtualFlow.scrollXBy(deltaX)); } @Override public void scrollYBy(double deltaY) { suspendVisibleParsWhile(() -> virtualFlow.scrollYBy(deltaY)); } @Override public void scrollBy(Point2D deltas) { suspendVisibleParsWhile(() -> virtualFlow.scrollBy(deltas)); } @Override public void showParagraphInViewport(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex)); } @Override public void showParagraphAtTop(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsFirst(paragraphIndex)); } @Override public void showParagraphAtBottom(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsLast(paragraphIndex)); } @Override public void showParagraphRegion(int paragraphIndex, Bounds region) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex, region)); } void showCaretAtBottom() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double y = caretBounds.getMaxY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, getViewportHeight() - y)); } void showCaretAtTop() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double y = caretBounds.getMinY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, -y)); } @Override public void requestFollowCaret() { followCaretRequested = true; requestLayout(); } /** Assumes this method is called within a {@link #suspendVisibleParsWhile(Runnable)} block */ private void followCaret() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double graphicWidth = cell.getNode().getGraphicPrefWidth(); Bounds region = extendLeft(caretBounds, graphicWidth); virtualFlow.show(parIdx, region); } @Override public void lineStart(SelectionPolicy policy) { int columnPos = virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineStartPosition(); moveTo(getCurrentParagraph(), columnPos, policy); } @Override public void lineEnd(SelectionPolicy policy) { int columnPos = virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineEndPosition(); moveTo(getCurrentParagraph(), columnPos, policy); } @Override public void prevPage(SelectionPolicy selectionPolicy) { showCaretAtBottom(); CharacterHit hit = hit(getTargetCaretOffset(), 1.0); moveTo(hit.getInsertionIndex(), selectionPolicy); } @Override public void nextPage(SelectionPolicy selectionPolicy) { showCaretAtTop(); CharacterHit hit = hit(getTargetCaretOffset(), getViewportHeight() - 1.0); moveTo(hit.getInsertionIndex(), selectionPolicy); } @Override public void displaceCaret(int pos) { caretSelectionBind.displaceCaret(pos); } @Override public final void hideContextMenu() { ContextMenu menu = getContextMenu(); if (menu != null && menu.isShowing()) { menu.hide(); } } @Override public void setStyle(int from, int to, S style) { content.setStyle(from, to, style); } @Override public void setStyle(int paragraph, S style) { content.setStyle(paragraph, style); } @Override public void setStyle(int paragraph, int from, int to, S style) { content.setStyle(paragraph, from, to, style); } @Override public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(from, styleSpans); } @Override public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(paragraph, from, styleSpans); } @Override public void setParagraphStyle(int paragraph, PS paragraphStyle) { content.setParagraphStyle(paragraph, paragraphStyle); } @Override public void replaceText(int start, int end, String text) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromString( text, getParagraphStyleForInsertionAt(start), getTextStyleForInsertionAt(start), segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, SEG seg, S style) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromSegment( seg, getParagraphStyleForInsertionAt(start), style, segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) { content.replace(start, end, replacement); int newCaretPos = start + replacement.length(); selectRange(newCaretPos, newCaretPos); } @Override public void dispose() { if (undoManager != null) { undoManager.close(); } subscriptions.unsubscribe(); virtualFlow.dispose(); } @Override protected void layoutChildren() { Insets ins = getInsets(); visibleParagraphs.suspendWhile(() -> { virtualFlow.resizeRelocate( ins.getLeft(), ins.getTop(), getWidth() - ins.getLeft() - ins.getRight(), getHeight() - ins.getTop() - ins.getBottom()); if(followCaretRequested) { followCaretRequested = false; try (Guard g = viewportDirty.suspend()) { followCaret(); } } }); } private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell( Paragraph<PS, SEG, S> paragraph, BiConsumer<TextFlow, PS> applyParagraphStyle, Function<StyledSegment<SEG, S>, Node> nodeFactory) { ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory); box.highlightFillProperty().bind(highlightFill); box.highlightTextFillProperty().bind(highlightTextFill); box.wrapTextProperty().bind(wrapTextProperty()); box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty()); box.graphicOffset.bind(virtualFlow.breadthOffsetProperty()); Val<Boolean> hasCaret = Val.combine( box.indexProperty(), currentParagraphProperty(), (bi, cp) -> bi.intValue() == cp.intValue()); Subscription hasCaretPseudoClass = hasCaret.values().subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value)); Subscription firstParPseudoClass = box.indexProperty().values().subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0)); Subscription lastParPseudoClass = EventStreams.combine( box.indexProperty().values(), getParagraphs().sizeProperty().values() ).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1))); // caret is visible only in the paragraph with the caret Val<Boolean> cellCaretVisible = hasCaret.flatMap(x -> x ? caretSelectionBind.visibleProperty() : Val.constant(false)); box.caretVisibleProperty().bind(cellCaretVisible); // bind cell's caret position to area's caret column, // when the cell is the one with the caret box.caretPositionProperty().bind(hasCaret.flatMap(has -> has ? caretColumnProperty() : Val.constant(0))); // keep paragraph selection updated ObjectBinding<IndexRange> cellSelection = Bindings.createObjectBinding(() -> { int idx = box.getIndex(); return idx != -1 ? getParagraphSelection(idx) : StyledTextArea.EMPTY_RANGE; }, selectionProperty(), box.indexProperty()); box.selectionProperty().bind(cellSelection); return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() { @Override public ParagraphBox<PS, SEG, S> getNode() { return box; } @Override public void updateIndex(int index) { box.setIndex(index); } @Override public void dispose() { box.highlightFillProperty().unbind(); box.highlightTextFillProperty().unbind(); box.wrapTextProperty().unbind(); box.graphicFactoryProperty().unbind(); box.graphicOffset.unbind(); hasCaretPseudoClass.unsubscribe(); firstParPseudoClass.unsubscribe(); lastParPseudoClass.unsubscribe(); box.caretVisibleProperty().unbind(); box.caretPositionProperty().unbind(); box.selectionProperty().unbind(); cellSelection.dispose(); } }; } private ParagraphBox<PS, SEG, S> getCell(int index) { return virtualFlow.getCell(index).getNode(); } private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) { return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify( l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)), r -> MouseOverTextEvent.end()))); } private int getParagraphOffset(int parIdx) { return position(parIdx, 0).toOffset(); } @Override public Bounds getVisibleParagraphBoundsOnScreen(int visibleParagraphIndex) { return getParagraphBoundsOnScreen(virtualFlow.visibleCells().get(visibleParagraphIndex)); } @Override public Optional<Bounds> getParagraphBoundsOnScreen(int paragraphIndex) { return virtualFlow.getCellIfVisible(paragraphIndex).map(this::getParagraphBoundsOnScreen); } private Bounds getParagraphBoundsOnScreen(Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell) { Bounds nodeLocal = cell.getNode().getBoundsInLocal(); Bounds nodeScreen = cell.getNode().localToScreen(nodeLocal); Bounds areaLocal = getBoundsInLocal(); Bounds areaScreen = localToScreen(areaLocal); // use area's minX if scrolled right and paragraph's left is not visible double minX = nodeScreen.getMinX() < areaScreen.getMinX() ? areaScreen.getMinX() : nodeScreen.getMinX(); // use area's minY if scrolled down vertically and paragraph's top is not visible double minY = nodeScreen.getMinY() < areaScreen.getMinY() ? areaScreen.getMinY() : nodeScreen.getMinY(); // use area's width whether paragraph spans outside of it or not // so that short or long paragraph takes up the entire space double width = areaScreen.getWidth(); // use area's maxY if scrolled up vertically and paragraph's bottom is not visible double maxY = nodeScreen.getMaxY() < areaScreen.getMaxY() ? nodeScreen.getMaxY() : areaScreen.getMaxY(); return new BoundingBox(minX, minY, width, maxY - minY); } private Optional<Bounds> getRangeBoundsOnScreen(int paragraphIndex, int from, int to) { return virtualFlow.getCellIfVisible(paragraphIndex) .map(c -> c.getNode().getRangeBoundsOnScreen(from, to)); } @Override public final Optional<Bounds> getCaretBoundsOnScreen(int paragraphIndex) { return virtualFlow.getCellIfVisible(paragraphIndex) .map(c -> c.getNode().getCaretBoundsOnScreen()); } final Optional<Bounds> getSelectionBoundsOnScreen(Selection selection) { if (selection.getLength() == 0) { return Optional.empty(); } List<Bounds> bounds = new ArrayList<>(selection.getParagraphSpan()); for (int i = selection.getStartParagraphIndex(); i <= selection.getEndParagraphIndex(); i++) { final int i0 = i; virtualFlow.getCellIfVisible(i).ifPresent(c -> { IndexRange rangeWithinPar = getParagraphSelection(selection, i0); Bounds b = c.getNode().getRangeBoundsOnScreen(rangeWithinPar); bounds.add(b); }); } if(bounds.size() == 0) { return Optional.empty(); } double minX = bounds.stream().mapToDouble(Bounds::getMinX).min().getAsDouble(); double maxX = bounds.stream().mapToDouble(Bounds::getMaxX).max().getAsDouble(); double minY = bounds.stream().mapToDouble(Bounds::getMinY).min().getAsDouble(); double maxY = bounds.stream().mapToDouble(Bounds::getMaxY).max().getAsDouble(); return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY)); } private <T> void subscribeTo(EventStream<T> src, Consumer<T> cOnsumer) { manageSubscription(src.subscribe(cOnsumer)); } private void manageSubscription(Subscription subscription) { subscriptions = subscriptions.and(subscription); } private void manageBinding(Binding<?> binding) { subscriptions = subscriptions.and(binding::dispose); } private static Bounds extendLeft(Bounds b, double w) { if(w == 0) { return b; } else { return new BoundingBox( b.getMinX() - w, b.getMinY(), b.getWidth() + w, b.getHeight()); } } @Override public final S getTextStyleForInsertionAt(int pos) { if(useInitialStyleForInsertion.get()) { return initialTextStyle; } else { return content.getStyleAtPosition(pos); } } @Override public final PS getParagraphStyleForInsertionAt(int pos) { if(useInitialStyleForInsertion.get()) { return initialParagraphStyle; } else { return content.getParagraphStyleAtPosition(pos); } } private void suspendVisibleParsWhile(Runnable runnable) { Suspendable.combine(beingUpdated, visibleParagraphs).suspendWhile(runnable); } void clearTargetCaretOffset() { caretSelectionBind.clearTargetOffset(); } ParagraphBox.CaretOffsetX getTargetCaretOffset() { return caretSelectionBind.getTargetOffset(); } private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_FILL = new CustomCssMetaData<>( "-fx-highlight-fill", StyleConverter.getPaintConverter(), Color.DODGERBLUE, s -> s.highlightFill ); private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_TEXT_FILL = new CustomCssMetaData<>( "-fx-highlight-text-fill", StyleConverter.getPaintConverter(), Color.WHITE, s -> s.highlightTextFill ); private static final CssMetaData<GenericStyledArea<?, ?, ?>, javafx.util.Duration> CARET_BLINK_RATE = new CustomCssMetaData<>("-fx-caret-blink-rate", StyleConverter.getDurationConverter(), javafx.util.Duration.millis(500), s -> s.caretBlinkRate ); private static final List<CssMetaData<? extends Styleable, ?>> CSS_META_DATA_LIST; static { List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Region.getClassCssMetaData()); styleables.add(HIGHLIGHT_FILL); styleables.add(HIGHLIGHT_TEXT_FILL); styleables.add(CARET_BLINK_RATE); CSS_META_DATA_LIST = Collections.unmodifiableList(styleables); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return CSS_META_DATA_LIST; } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return CSS_META_DATA_LIST; } }
package org.fxmisc.richtext; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.IntUnaryOperator; import javafx.application.Platform; import javafx.beans.NamedArg; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener.Change; import javafx.collections.ObservableSet; import javafx.css.CssMetaData; import javafx.css.PseudoClass; import javafx.css.StyleConverter; import javafx.css.Styleable; import javafx.css.StyleableObjectProperty; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.IndexRange; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.LineTo; import javafx.scene.shape.PathElement; import javafx.scene.text.TextFlow; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; import org.fxmisc.flowless.Virtualized; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.model.Codec; import org.fxmisc.richtext.model.EditableStyledDocument; import org.fxmisc.richtext.model.GenericEditableStyledDocument; import org.fxmisc.richtext.model.Paragraph; import org.fxmisc.richtext.model.ReadOnlyStyledDocument; import org.fxmisc.richtext.model.PlainTextChange; import org.fxmisc.richtext.model.Replacement; import org.fxmisc.richtext.model.RichTextChange; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyledDocument; import org.fxmisc.richtext.model.StyledSegment; import org.fxmisc.richtext.model.TextOps; import org.fxmisc.richtext.model.TwoDimensional; import org.fxmisc.richtext.model.TwoLevelNavigator; import org.fxmisc.richtext.event.MouseOverTextEvent; import org.fxmisc.richtext.util.SubscribeableContentsObsSet; import org.fxmisc.richtext.util.UndoUtils; import org.fxmisc.undo.UndoManager; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.Guard; import org.reactfx.Subscription; import org.reactfx.Suspendable; import org.reactfx.SuspendableEventStream; import org.reactfx.SuspendableNo; import org.reactfx.collection.LiveList; import org.reactfx.collection.SuspendableList; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; import org.reactfx.value.Var; public class GenericStyledArea<PS, SEG, S> extends Region implements TextEditingArea<PS, SEG, S>, EditActions<PS, SEG, S>, ClipboardActions<PS, SEG, S>, NavigationActions<PS, SEG, S>, StyleActions<PS, S>, UndoActions, ViewActions<PS, SEG, S>, TwoDimensional, Virtualized { /** * Index range [0, 0). */ public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0); private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("readonly"); private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret"); private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph"); private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph"); /** * Text color for highlighted text. */ private final StyleableObjectProperty<Paint> highlightTextFill = new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL); // editable property private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) { @Override protected void invalidated() { ((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get()); } }; @Override public final BooleanProperty editableProperty() { return editable; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setEditable(boolean value) { editable.set(value); } @Override public boolean isEditable() { return editable.get(); } // wrapText property private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText"); @Override public final BooleanProperty wrapTextProperty() { return wrapText; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setWrapText(boolean value) { wrapText.set(value); } @Override public boolean isWrapText() { return wrapText.get(); } // undo manager private UndoManager undoManager; @Override public UndoManager getUndoManager() { return undoManager; } /** * @param undoManager may be null in which case a no op undo manager will be set. */ @Override public void setUndoManager(UndoManager undoManager) { this.undoManager.close(); this.undoManager = undoManager != null ? undoManager : UndoUtils.noOpUndoManager(); } private Locale textLocale = Locale.getDefault(); /** * This is used to determine word and sentence breaks while navigating or selecting. * Override this method if your paragraph or text style accommodates Locales as well. * @return Locale.getDefault() by default */ @Override public Locale getLocale() { return textLocale; } public void setLocale( Locale editorLocale ) { textLocale = editorLocale; } private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null); @Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; } private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null); @Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; } public void recreateParagraphGraphic( int parNdx ) { ObjectProperty<IntFunction<? extends Node>> gProp; gProp = getCell(parNdx).graphicFactoryProperty(); gProp.unbind(); gProp.bind(paragraphGraphicFactoryProperty()); } public Node getParagraphGraphic( int parNdx ) { return getCell(parNdx).getGraphic(); } /** * This Node is shown to the user, centered over the area, when the area has no text content. */ private ObjectProperty<Node> placeHolderProp = new SimpleObjectProperty<>(this, "placeHolder", null); public final ObjectProperty<Node> placeholderProperty() { return placeHolderProp; } public final void setPlaceholder(Node value) { placeHolderProp.set(value); } public final Node getPlaceholder() { return placeHolderProp.get(); } private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null); @Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenu(ContextMenu menu) { contextMenu.set(menu); } @Override public ContextMenu getContextMenu() { return contextMenu.get(); } protected final boolean isContextMenuPresent() { return contextMenu.get() != null; } private DoubleProperty contextMenuXOffset = new SimpleDoubleProperty(2); @Override public final DoubleProperty contextMenuXOffsetProperty() { return contextMenuXOffset; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenuXOffset(double offset) { contextMenuXOffset.set(offset); } @Override public double getContextMenuXOffset() { return contextMenuXOffset.get(); } private DoubleProperty contextMenuYOffset = new SimpleDoubleProperty(2); @Override public final DoubleProperty contextMenuYOffsetProperty() { return contextMenuYOffset; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setContextMenuYOffset(double offset) { contextMenuYOffset.set(offset); } @Override public double getContextMenuYOffset() { return contextMenuYOffset.get(); } private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty(); @Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; } private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty(); @Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) { styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec)); } @Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() { return styleCodecs; } @Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); } @Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); } private final SubscribeableContentsObsSet<CaretNode> caretSet; private final SubscribeableContentsObsSet<Selection<PS, SEG, S>> selectionSet; public final boolean addCaret(CaretNode caret) { if (caret.getArea() != this) { throw new IllegalArgumentException(String.format( "The caret (%s) is associated with a different area (%s), " + "not this area (%s)", caret, caret.getArea(), this)); } return caretSet.add(caret); } public final boolean removeCaret(CaretNode caret) { if (caret != caretSelectionBind.getUnderlyingCaret()) { return caretSet.remove(caret); } else { return false; } } public final boolean addSelection(Selection<PS, SEG, S> selection) { if (selection.getArea() != this) { throw new IllegalArgumentException(String.format( "The selection (%s) is associated with a different area (%s), " + "not this area (%s)", selection, selection.getArea(), this)); } return selectionSet.add(selection); } public final boolean removeSelection(Selection<PS, SEG, S> selection) { if (selection != caretSelectionBind.getUnderlyingSelection()) { return selectionSet.remove(selection); } else { return false; } } @Override public final EventHandler<MouseEvent> getOnOutsideSelectionMousePressed() { return onOutsideSelectionMousePressed.get(); } @Override public final void setOnOutsideSelectionMousePressed(EventHandler<MouseEvent> handler) { onOutsideSelectionMousePressed.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressedProperty() { return onOutsideSelectionMousePressed; } private final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressed = new SimpleObjectProperty<>( e -> { moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR ); }); @Override public final EventHandler<MouseEvent> getOnInsideSelectionMousePressReleased() { return onInsideSelectionMousePressReleased.get(); } @Override public final void setOnInsideSelectionMousePressReleased(EventHandler<MouseEvent> handler) { onInsideSelectionMousePressReleased.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleasedProperty() { return onInsideSelectionMousePressReleased; } private final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleased = new SimpleObjectProperty<>( e -> { moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR ); }); private final ObjectProperty<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); @Override public final ObjectProperty<Consumer<Point2D>> onNewSelectionDragProperty() { return onNewSelectionDrag; } @Override public final EventHandler<MouseEvent> getOnNewSelectionDragFinished() { return onNewSelectionDragFinished.get(); } @Override public final void setOnNewSelectionDragFinished(EventHandler<MouseEvent> handler) { onNewSelectionDragFinished.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinishedProperty() { return onNewSelectionDragFinished; } private final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinished = new SimpleObjectProperty<>( e -> { CharacterHit hit = hit(e.getX(), e.getY()); moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST); }); private final ObjectProperty<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> { CharacterHit hit = hit(p.getX(), p.getY()); displaceCaret(hit.getInsertionIndex()); }); @Override public final ObjectProperty<Consumer<Point2D>> onSelectionDragProperty() { return onSelectionDrag; } @Override public final EventHandler<MouseEvent> getOnSelectionDropped() { return onSelectionDropped.get(); } @Override public final void setOnSelectionDropped(EventHandler<MouseEvent> handler) { onSelectionDropped.set( handler ); } @Override public final ObjectProperty<EventHandler<MouseEvent>> onSelectionDroppedProperty() { return onSelectionDropped; } private final ObjectProperty<EventHandler<MouseEvent>> onSelectionDropped = new SimpleObjectProperty<>( e -> { moveSelectedText( hit( e.getX(), e.getY() ).getInsertionIndex() ); }); // not a hook, but still plays a part in the default mouse behavior private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true); @Override public final BooleanProperty autoScrollOnDragDesiredProperty() { return autoScrollOnDragDesired; } // Don't remove as FXMLLoader doesn't recognise default methods ! @Override public void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); } @Override public boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); } // text @Override public final ObservableValue<String> textProperty() { return content.textProperty(); } // rich text @Override public final StyledDocument<PS, SEG, S> getDocument() { return content; } private CaretSelectionBind<PS, SEG, S> caretSelectionBind; @Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; } // length @Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); } // paragraphs @Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); } private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs; @Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; } // beingUpdated private final SuspendableNo beingUpdated = new SuspendableNo(); @Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; } // total width estimate @Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); } // total height estimate @Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); } @Override public EventStream<List<RichTextChange<PS, SEG, S>>> multiRichChanges() { return content.multiRichChanges(); } @Override public EventStream<List<PlainTextChange>> multiPlainChanges() { return content.multiPlainChanges(); } // text changes @Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); } // rich text changes @Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); } private final SuspendableEventStream<?> viewportDirty; @Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; } private Subscription subscriptions = () -> {}; private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow; // used for two-level navigation, where on the higher level are // paragraphs and on the lower level are lines within a paragraph private final TwoLevelNavigator paragraphLineNavigator; private boolean paging, followCaretRequested = false; private final EditableStyledDocument<PS, SEG, S> content; @Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; } private final S initialTextStyle; @Override public final S getInitialTextStyle() { return initialTextStyle; } private final PS initialParagraphStyle; @Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; } private final BiConsumer<TextFlow, PS> applyParagraphStyle; @Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; } // TODO: Currently, only undo/redo respect this flag. private final boolean preserveStyle; @Override public final boolean isPreserveStyle() { return preserveStyle; } private final TextOps<SEG, S> segmentOps; @Override public final TextOps<SEG, S> getSegOps() { return segmentOps; } private final EventStream<Boolean> autoCaretBlinksSteam; final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; } /** * Creates a text area with empty text content. * * @param initialParagraphStyle style to use in places where no other style is * specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is * specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param nodeFactory A function which is used to create the JavaFX scene nodes for a * particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory); } /** * Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one * to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory); } /** * The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that * this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same * {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory); } /** * Creates an area with flexibility in all of its options. * * @param initialParagraphStyle style to use in places where no other style is specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. * @param initialTextStyle style to use in places where no other style is specified (yet). * @param document the document to render and edit * @param segmentOps The operations which are defined on the text segment objects. * @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or * {@link PlainTextChange}s * @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment. */ public GenericStyledArea( @NamedArg("initialParagraphStyle") PS initialParagraphStyle, @NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle, @NamedArg("initialTextStyle") S initialTextStyle, @NamedArg("document") EditableStyledDocument<PS, SEG, S> document, @NamedArg("segmentOps") TextOps<SEG, S> segmentOps, @NamedArg("preserveStyle") boolean preserveStyle, @NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) { this.initialTextStyle = initialTextStyle; this.initialParagraphStyle = initialParagraphStyle; this.preserveStyle = preserveStyle; this.content = document; this.applyParagraphStyle = applyParagraphStyle; this.segmentOps = segmentOps; undoManager = UndoUtils.defaultUndoManager(this); // allow tab traversal into area setFocusTraversable(true); this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); getStyleClass().add("styled-text-area"); getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm()); // keeps track of currently used non-empty cells @SuppressWarnings("unchecked") ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet(); caretSet = new SubscribeableContentsObsSet<>(); manageSubscription(() -> { List<CaretNode> l = new ArrayList<>(caretSet); caretSet.clear(); l.forEach(CaretNode::dispose); }); selectionSet = new SubscribeableContentsObsSet<>(); manageSubscription(() -> { List<Selection<PS, SEG, S>> l = new ArrayList<>(selectionSet); selectionSet.clear(); l.forEach(Selection::dispose); }); // Initialize content virtualFlow = VirtualFlow.createVertical( getParagraphs(), par -> { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell( par, applyParagraphStyle, nodeFactory); nonEmptyCells.add(cell.getNode()); return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode())) .afterUpdateItem(p -> nonEmptyCells.add(cell.getNode())); }); getChildren().add(virtualFlow); // initialize navigator IntSupplier cellCount = () -> getParagraphs().size(); IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount(); paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength); viewportDirty = merge( // no need to check for width & height invalidations as scroll values update when these do // scale invalidationsOf(scaleXProperty()), invalidationsOf(scaleYProperty()), // scroll invalidationsOf(estimatedScrollXProperty()), invalidationsOf(estimatedScrollYProperty()) ).suppressible(); autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty() .and(editableProperty()) .and(disabledProperty().not()) ); caretSelectionBind = new CaretSelectionBindImpl<>("main-caret", "main-selection",this); caretSet.add(caretSelectionBind.getUnderlyingCaret()); selectionSet.add(caretSelectionBind.getUnderlyingSelection()); visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable(); final Suspendable omniSuspendable = Suspendable.combine( beingUpdated, // must be first, to be the last one to release visibleParagraphs ); manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty())); // dispatch MouseOverTextEvents when mouseOverTextDelay is not null EventStreams.valuesOf(mouseOverTextDelayProperty()) .flatMap(delay -> delay != null ? mouseOverTextEvents(nonEmptyCells, delay) : EventStreams.never()) .subscribe(evt -> Event.fireEvent(this, evt)); new GenericStyledAreaBehavior(this); // Setup place holder visibility & placement final Val<Boolean> showPlaceholder = Val.create ( () -> getLength() == 0 && ! isFocused(), lengthProperty(), focusedProperty() ); placeHolderProp.addListener( (ob,ov,newNode) -> displayPlaceHolder( showPlaceholder.getValue(), newNode ) ); showPlaceholder.addListener( (ob,ov,show) -> displayPlaceHolder( show, getPlaceholder() ) ); } private Node placeholder; private void displayPlaceHolder( boolean show, Node newNode ) { if ( placeholder != null && (! show || newNode != placeholder) ) { placeholder.layoutXProperty().unbind(); placeholder.layoutYProperty().unbind(); getChildren().remove( placeholder ); placeholder = null; setClip( null ); } if ( newNode != null && show && newNode != placeholder ) { configurePlaceholder( newNode ); getChildren().add( newNode ); placeholder = newNode; } } protected void configurePlaceholder( Node placeholder ) { placeholder.layoutYProperty().bind( Bindings.createDoubleBinding( () -> (getHeight() - placeholder.getLayoutBounds().getHeight()) / 2, heightProperty(), placeholder.layoutBoundsProperty() ) ); placeholder.layoutXProperty().bind( Bindings.createDoubleBinding( () -> (getWidth() - placeholder.getLayoutBounds().getWidth()) / 2, widthProperty(), placeholder.layoutBoundsProperty() ) ); } @Override public final double getViewportHeight() { return virtualFlow.getHeight(); } @Override public final Optional<Integer> allParToVisibleParIndex(int allParIndex) { if (allParIndex < 0) { throw new IllegalArgumentException("The given paragraph index (allParIndex) cannot be negative but was " + allParIndex); } if (allParIndex >= getParagraphs().size()) { throw new IllegalArgumentException(String.format( "Paragraphs' last index is [%s] but allParIndex was [%s]", getParagraphs().size() - 1, allParIndex) ); } List<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> visibleList = virtualFlow.visibleCells(); int firstVisibleParIndex = visibleList.get( 0 ).getNode().getIndex(); int targetIndex = allParIndex - firstVisibleParIndex; if ( allParIndex >= firstVisibleParIndex && targetIndex < visibleList.size() ) { if ( visibleList.get( targetIndex ).getNode().getIndex() == allParIndex ) { return Optional.of( targetIndex ); } } return Optional.empty(); } @Override public final int visibleParToAllParIndex(int visibleParIndex) { if (visibleParIndex < 0) { throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex); } if (visibleParIndex >= getVisibleParagraphs().size()) { throw new IllegalArgumentException(String.format( "Visible paragraphs' last index is [%s] but visibleParIndex was [%s]", getVisibleParagraphs().size() - 1, visibleParIndex) ); } return virtualFlow.visibleCells().get( visibleParIndex ).getNode().getIndex(); } @Override public CharacterHit hit(double x, double y) { // mouse position used, so account for padding double adjustedX = x - getInsets().getLeft(); double adjustedY = y - getInsets().getTop(); VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(adjustedX, adjustedY); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hit(cellOffset); return parHit.offset(parOffset); } } @Override public final int lineIndex(int paragraphIndex, int columnPosition) { Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(paragraphIndex); return cell.getNode().getCurrentLineIndex(columnPosition); } @Override public int getParagraphLinesCount(int paragraphIndex) { return virtualFlow.getCell(paragraphIndex).getNode().getLineCount(); } @Override public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) { if (from < 0) { throw new IllegalArgumentException("From is negative: " + from); } if (from > to) { throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to)); } if (to > getLength()) { throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to)); } // no bounds exist if range is just a newline character if (getText(from, to).equals("\n")) { return Optional.empty(); } // if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose // minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it. int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from; Position startPosition = offsetToPosition(realFrom, Bias.Forward); int startRow = startPosition.getMajor(); Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward); int endRow = endPosition.getMajor(); if (startRow == endRow) { return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor()); } else { Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(), getParagraph(startRow).length()); for (int i = startRow + 1; i <= endRow; i++) { Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0, i == endRow ? endPosition.getMinor() : getParagraph(i).length() ); if (nextLineBounds.isPresent()) { if (rangeBounds.isPresent()) { Bounds lineBounds = nextLineBounds.get(); rangeBounds = rangeBounds.map(b -> { double minX = Math.min(b.getMinX(), lineBounds.getMinX()); double minY = Math.min(b.getMinY(), lineBounds.getMinY()); double maxX = Math.max(b.getMaxX(), lineBounds.getMaxX()); double maxY = Math.max(b.getMaxY(), lineBounds.getMaxY()); return new BoundingBox(minX, minY, maxX - minX, maxY - minY); }); } else { rangeBounds = nextLineBounds; } } } return rangeBounds; } } @Override public final String getText(int start, int end) { return content.getText(start, end); } @Override public String getText(int paragraph) { return content.getText(paragraph); } @Override public String getText(IndexRange range) { return content.getText(range); } @Override public StyledDocument<PS, SEG, S> subDocument(int start, int end) { return content.subSequence(start, end); } @Override public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) { return content.subDocument(paragraphIndex); } @Override public IndexRange getParagraphSelection(Selection selection, int paragraph) { int startPar = selection.getStartParagraphIndex(); int endPar = selection.getEndParagraphIndex(); if(selection.getLength() == 0 || paragraph < startPar || paragraph > endPar) { return EMPTY_RANGE; } int start = paragraph == startPar ? selection.getStartColumnPosition() : 0; int end = paragraph == endPar ? selection.getEndColumnPosition() : getParagraphLength(paragraph) + 1; // force rangeProperty() to be valid selection.getRange(); return new IndexRange(start, end); } @Override public S getStyleOfChar(int index) { return content.getStyleOfChar(index); } @Override public S getStyleAtPosition(int position) { return content.getStyleAtPosition(position); } @Override public IndexRange getStyleRangeAtPosition(int position) { return content.getStyleRangeAtPosition(position); } @Override public StyleSpans<S> getStyleSpans(int from, int to) { return content.getStyleSpans(from, to); } @Override public S getStyleOfChar(int paragraph, int index) { return content.getStyleOfChar(paragraph, index); } @Override public S getStyleAtPosition(int paragraph, int position) { return content.getStyleAtPosition(paragraph, position); } @Override public IndexRange getStyleRangeAtPosition(int paragraph, int position) { return content.getStyleRangeAtPosition(paragraph, position); } @Override public StyleSpans<S> getStyleSpans(int paragraph) { return content.getStyleSpans(paragraph); } @Override public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) { return content.getStyleSpans(paragraph, from, to); } @Override public int getAbsolutePosition(int paragraphIndex, int columnIndex) { return content.getAbsolutePosition(paragraphIndex, columnIndex); } @Override public Position position(int row, int col) { return content.position(row, col); } @Override public Position offsetToPosition(int charOffset, Bias bias) { return content.offsetToPosition(charOffset, bias); } @Override public Bounds getVisibleParagraphBoundsOnScreen(int visibleParagraphIndex) { return getParagraphBoundsOnScreen(virtualFlow.visibleCells().get(visibleParagraphIndex)); } @Override public Optional<Bounds> getParagraphBoundsOnScreen(int paragraphIndex) { return virtualFlow.getCellIfVisible(paragraphIndex).map(this::getParagraphBoundsOnScreen); } @Override public final <T extends Node & Caret> Optional<Bounds> getCaretBoundsOnScreen(T caret) { return virtualFlow.getCellIfVisible(caret.getParagraphIndex()) .map(c -> c.getNode().getCaretBoundsOnScreen(caret)); } @Override public void scrollXToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollXToPixel(pixel)); } @Override public void scrollYToPixel(double pixel) { suspendVisibleParsWhile(() -> virtualFlow.scrollYToPixel(pixel)); } @Override public void scrollXBy(double deltaX) { suspendVisibleParsWhile(() -> virtualFlow.scrollXBy(deltaX)); } @Override public void scrollYBy(double deltaY) { suspendVisibleParsWhile(() -> virtualFlow.scrollYBy(deltaY)); } @Override public void scrollBy(Point2D deltas) { suspendVisibleParsWhile(() -> virtualFlow.scrollBy(deltas)); } @Override public void showParagraphInViewport(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex)); } @Override public void showParagraphAtTop(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsFirst(paragraphIndex)); } @Override public void showParagraphAtBottom(int paragraphIndex) { suspendVisibleParsWhile(() -> virtualFlow.showAsLast(paragraphIndex)); } @Override public void showParagraphRegion(int paragraphIndex, Bounds region) { suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex, region)); } @Override public void requestFollowCaret() { followCaretRequested = true; requestLayout(); } @Override public void lineStart(SelectionPolicy policy) { moveTo(getCurrentParagraph(), getCurrentLineStartInParargraph(), policy); } @Override public void lineEnd(SelectionPolicy policy) { moveTo(getCurrentParagraph(), getCurrentLineEndInParargraph(), policy); } public int getCurrentLineStartInParargraph() { return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineStartPosition(caretSelectionBind.getUnderlyingCaret()); } public int getCurrentLineEndInParargraph() { return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineEndPosition(caretSelectionBind.getUnderlyingCaret()); } private double caretPrevY = -1; private LineSelection<PS, SEG, S> lineHighlighter; private ObjectProperty<Paint> lineHighlighterFill; /** * The default fill is "highlighter" yellow. It can also be styled using CSS with:<br> * <code>.styled-text-area .line-highlighter { -fx-fill: lime; }</code><br> * CSS selectors from Path, Shape, and Node can also be used. */ public void setLineHighlighterFill( Paint highlight ) { if ( lineHighlighterFill != null && highlight != null ) { lineHighlighterFill.set( highlight ); } else { boolean lineHighlightOn = isLineHighlighterOn(); if ( lineHighlightOn ) setLineHighlighterOn( false ); if ( highlight == null ) lineHighlighterFill = null; else lineHighlighterFill = new SimpleObjectProperty( highlight ); if ( lineHighlightOn ) setLineHighlighterOn( true ); } } public boolean isLineHighlighterOn() { return lineHighlighter != null && selectionSet.contains( lineHighlighter ) ; } /** * Highlights the line that the main caret is on.<br> * Line highlighting automatically follows the caret. */ public void setLineHighlighterOn( boolean show ) { if ( show ) { if ( lineHighlighter != null ) return; lineHighlighter = new LineSelection<>( this, lineHighlighterFill ); Consumer<Bounds> caretListener = b -> { if ( lineHighlighter != null && (b.getMinY() != caretPrevY || getCaretColumn() == 1) ) { lineHighlighter.selectCurrentLine(); caretPrevY = b.getMinY(); } }; caretBoundsProperty().addListener( (ob,ov,nv) -> nv.ifPresent( caretListener ) ); getCaretBounds().ifPresent( caretListener ); selectionSet.add( lineHighlighter ); } else if ( lineHighlighter != null ) { selectionSet.remove( lineHighlighter ); lineHighlighter.deselect(); lineHighlighter = null; caretPrevY = -1; } } @Override public void prevPage(SelectionPolicy selectionPolicy) { page( -1, selectionPolicy ); } @Override public void nextPage(SelectionPolicy selectionPolicy) { page( +1, selectionPolicy ); } /** * @param pgCount the number of pages to page up/down. * <br>Negative numbers for paging up and positive for down. */ private void page(int pgCount, SelectionPolicy selectionPolicy) { // Use underlying caret to get the same behaviour as navigating up/down a line where the x position is sticky Optional<Bounds> cb = caretSelectionBind.getUnderlyingCaret().getCaretBounds(); paging = true; // Prevent scroll from reverting back to the current caret position scrollYBy( pgCount * getViewportHeight() ); cb.map( this::screenToLocal ) // Place caret near the same on screen position as before .map( b -> hit( b.getMinX(), b.getMinY()+b.getHeight()/2.0 ).getInsertionIndex() ) .ifPresent( i -> caretSelectionBind.moveTo( i, selectionPolicy ) ); // Adjust scroll by a few pixels to get the caret at the exact on screen location as before cb.ifPresent( prev -> getCaretBounds().map( newB -> newB.getMinY() - prev.getMinY() ) .filter( delta -> delta != 0.0 ).ifPresent( delta -> scrollYBy( delta ) ) ); } @Override public void displaceCaret(int pos) { caretSelectionBind.displaceCaret(pos); } @Override public void setStyle(int from, int to, S style) { content.setStyle(from, to, style); } @Override public void setStyle(int paragraph, S style) { content.setStyle(paragraph, style); } @Override public void setStyle(int paragraph, int from, int to, S style) { content.setStyle(paragraph, from, to, style); } @Override public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(from, styleSpans); } @Override public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { content.setStyleSpans(paragraph, from, styleSpans); } @Override public void setParagraphStyle(int paragraph, PS paragraphStyle) { content.setParagraphStyle(paragraph, paragraphStyle); } /** * If you want to preset the style to be used for inserted text. Note that useInitialStyleForInsertion overrides this if true. */ public final void setTextInsertionStyle( S txtStyle ) { insertionTextStyle = txtStyle; } public final S getTextInsertionStyle() { return insertionTextStyle; } private S insertionTextStyle; @Override public final S getTextStyleForInsertionAt(int pos) { if ( insertionTextStyle != null ) { return insertionTextStyle; } else if ( useInitialStyleForInsertion.get() ) { return initialTextStyle; } else { return content.getStyleAtPosition(pos); } } private PS insertionParagraphStyle; /** * If you want to preset the style to be used. Note that useInitialStyleForInsertion overrides this if true. */ public final void setParagraphInsertionStyle( PS paraStyle ) { insertionParagraphStyle = paraStyle; } public final PS getParagraphInsertionStyle() { return insertionParagraphStyle; } @Override public final PS getParagraphStyleForInsertionAt(int pos) { if ( insertionParagraphStyle != null ) { return insertionParagraphStyle; } else if ( useInitialStyleForInsertion.get() ) { return initialParagraphStyle; } else { return content.getParagraphStyleAtPosition(pos); } } @Override public void replaceText(int start, int end, String text) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromString( text, getParagraphStyleForInsertionAt(start), getTextStyleForInsertionAt(start), segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, SEG seg, S style) { StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromSegment( seg, getParagraphStyleForInsertionAt(start), style, segmentOps ); replace(start, end, doc); } @Override public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) { content.replace(start, end, replacement); int newCaretPos = start + replacement.length(); selectRange(newCaretPos, newCaretPos); } void replaceMulti(List<Replacement<PS, SEG, S>> replacements) { content.replaceMulti(replacements); // don't update selection as this is not the main method through which the area is updated // leave that up to the developer using it to determine what to do } @Override public MultiChangeBuilder<PS, SEG, S> createMultiChange() { return new MultiChangeBuilder<>(this); } @Override public MultiChangeBuilder<PS, SEG, S> createMultiChange(int initialNumOfChanges) { return new MultiChangeBuilder<>(this, initialNumOfChanges); } @Override public void dispose() { if (undoManager != null) { undoManager.close(); } subscriptions.unsubscribe(); virtualFlow.dispose(); } private BooleanProperty autoHeightProp = new SimpleBooleanProperty(); public BooleanProperty autoHeightProperty() { return autoHeightProp; } public void setAutoHeight( boolean value ) { autoHeightProp.set( value ); } public boolean isAutoHeight() { return autoHeightProp.get(); } @Override protected double computePrefHeight( double width ) { if ( autoHeightProp.get() ) { if ( getWidth() == 0.0 ) Platform.runLater( () -> requestLayout() ); else { double height = 0.0; Insets in = getInsets(); for ( int p = 0; p < getParagraphs().size(); p++ ) { height += getCell( p ).getHeight(); } if ( height > 0.0 ) { return height + in.getTop() + in.getBottom(); } } } return super.computePrefHeight( width ); } @Override protected void layoutChildren() { Insets ins = getInsets(); visibleParagraphs.suspendWhile(() -> { virtualFlow.resizeRelocate( ins.getLeft(), ins.getTop(), getWidth() - ins.getLeft() - ins.getRight(), getHeight() - ins.getTop() - ins.getBottom()); if(followCaretRequested && ! paging) { try (Guard g = viewportDirty.suspend()) { followCaret(); } } followCaretRequested = false; paging = false; }); Node holder = placeholder; if (holder != null && holder.isResizable() && holder.isManaged()) { holder.autosize(); } } /** * Returns the current line as a two-level index. * The major number is the paragraph index, the minor * number is the line number within the paragraph. * * <p>This method has a side-effect of bringing the current * paragraph to the viewport if it is not already visible. */ TwoDimensional.Position currentLine() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); int lineIdx = cell.getNode().getCurrentLineIndex(caretSelectionBind.getUnderlyingCaret()); return paragraphLineNavigator.position(parIdx, lineIdx); } void showCaretAtBottom() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret()); double y = caretBounds.getMaxY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, getViewportHeight() - y)); } void showCaretAtTop() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret()); double y = caretBounds.getMinY(); suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, -y)); } /** * Returns x coordinate of the caret in the current paragraph. */ final ParagraphBox.CaretOffsetX getCaretOffsetX(CaretNode caret) { return getCell(caret.getParagraphIndex()).getCaretOffsetX(caret); } CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) { int parIdx = targetLine.getMajor(); ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode(); CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor()); return parHit.offset(getParagraphOffset(parIdx)); } CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) { // don't account for padding here since height of virtualFlow is used, not area + potential padding VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hitText(x, cellOffset.getY()); return parHit.offset(parOffset); } } final Optional<Bounds> getSelectionBoundsOnScreen(Selection<PS, SEG, S> selection) { if (selection.getLength() == 0) { return Optional.empty(); } List<Bounds> bounds = new ArrayList<>(selection.getParagraphSpan()); for (int i = selection.getStartParagraphIndex(); i <= selection.getEndParagraphIndex(); i++) { virtualFlow.getCellIfVisible(i) .ifPresent(c -> c.getNode() .getSelectionBoundsOnScreen(selection) .ifPresent(bounds::add) ); } if(bounds.size() == 0) { return Optional.empty(); } double minX = bounds.stream().mapToDouble(Bounds::getMinX).min().getAsDouble(); double maxX = bounds.stream().mapToDouble(Bounds::getMaxX).max().getAsDouble(); double minY = bounds.stream().mapToDouble(Bounds::getMinY).min().getAsDouble(); double maxY = bounds.stream().mapToDouble(Bounds::getMaxY).max().getAsDouble(); return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY)); } void clearTargetCaretOffset() { caretSelectionBind.clearTargetOffset(); } ParagraphBox.CaretOffsetX getTargetCaretOffset() { return caretSelectionBind.getTargetOffset(); } private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell( Paragraph<PS, SEG, S> paragraph, BiConsumer<TextFlow, PS> applyParagraphStyle, Function<StyledSegment<SEG, S>, Node> nodeFactory) { ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory); box.highlightTextFillProperty().bind(highlightTextFill); box.wrapTextProperty().bind(wrapTextProperty()); box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty()); box.graphicOffset.bind(virtualFlow.breadthOffsetProperty()); EventStream<Integer> boxIndexValues = box.indexProperty().values().filter(i -> i != -1); Subscription firstParPseudoClass = boxIndexValues.subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0)); Subscription lastParPseudoClass = EventStreams.combine( boxIndexValues, getParagraphs().sizeProperty().values() ).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1))); // set up caret Function<CaretNode, Subscription> subscribeToCaret = caret -> { EventStream<Integer> caretIndexStream = EventStreams.nonNullValuesOf(caret.paragraphIndexProperty()); // a new event stream needs to be created for each caret added, so that it will immediately // fire the box's current index value as an event, thereby running the code in the subscribe block // Reusing boxIndexValues will not fire its most recent event, leading to a caret not being added // Thus, we'll call the new event stream "fresh" box index values EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1); return EventStreams.combine(caretIndexStream, freshBoxIndexValues) .subscribe(t -> { int caretParagraphIndex = t.get1(); int boxIndex = t.get2(); if (caretParagraphIndex == boxIndex) { box.caretsProperty().add(caret); } else { box.caretsProperty().remove(caret); } }); }; Subscription caretSubscription = caretSet.addSubscriber(subscribeToCaret); // TODO: how should 'hasCaret' be handled now? Subscription hasCaretPseudoClass = EventStreams .combine(boxIndexValues, Val.wrap(currentParagraphProperty()).values()) // box index (t1) == caret paragraph index (t2) .map(t -> t.get1().equals(t.get2())) .subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value)); Function<Selection<PS, SEG, S>, Subscription> subscribeToSelection = selection -> { EventStream<Integer> startParagraphValues = EventStreams.nonNullValuesOf(selection.startParagraphIndexProperty()); EventStream<Integer> endParagraphValues = EventStreams.nonNullValuesOf(selection.endParagraphIndexProperty()); // see comment in caret section about why a new box index EventStream is needed EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1); return EventStreams.combine(startParagraphValues, endParagraphValues, freshBoxIndexValues) .subscribe(t -> { int startPar = t.get1(); int endPar = t.get2(); int boxIndex = t.get3(); if (startPar <= boxIndex && boxIndex <= endPar) { // So that we don't add multiple paths for the same selection, // which leads to not removing the additional paths when selection is removed, // this is a `Map#putIfAbsent(Key, Value)` implementation that creates the path lazily SelectionPath p = box.selectionsProperty().get(selection); if (p == null) { // create & configure path Val<IndexRange> range = Val.create( () -> box.getIndex() != -1 ? getParagraphSelection(selection, box.getIndex()) : EMPTY_RANGE, selection.rangeProperty() ); SelectionPath path = new SelectionPath(range); path.getStyleClass().add( selection.getSelectionName() ); selection.configureSelectionPath(path); box.selectionsProperty().put(selection, path); } } else { box.selectionsProperty().remove(selection); } }); }; Subscription selectionSubscription = selectionSet.addSubscriber(subscribeToSelection); return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() { @Override public ParagraphBox<PS, SEG, S> getNode() { return box; } @Override public void updateIndex(int index) { box.setIndex(index); } @Override public void dispose() { box.highlightTextFillProperty().unbind(); box.wrapTextProperty().unbind(); box.graphicFactoryProperty().unbind(); box.graphicOffset.unbind(); box.dispose(); firstParPseudoClass.unsubscribe(); lastParPseudoClass.unsubscribe(); caretSubscription.unsubscribe(); hasCaretPseudoClass.unsubscribe(); selectionSubscription.unsubscribe(); } }; } /** Assumes this method is called within a {@link #suspendVisibleParsWhile(Runnable)} block */ private void followCaret() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = caretSelectionBind.getUnderlyingCaret().getLayoutBounds(); double graphicWidth = cell.getNode().getGraphicPrefWidth(); Bounds region = extendLeft(caretBounds, graphicWidth); double scrollX = virtualFlow.getEstimatedScrollX(); // Ordinarily when a caret ends a selection in the target paragraph and scrolling left is required to follow // the caret then the selection won't be visible. So here we check for this scenario and adjust if needed. if ( ! isWrapText() && scrollX > 0.0 && getParagraphSelection( parIdx ).getLength() > 0 ) { double visibleLeftX = cell.getNode().getWidth() * scrollX / 100 - getWidth() + graphicWidth; CaretNode selectionStart = new CaretNode( "", this, getSelection().getStart() ); cell.getNode().caretsProperty().add( selectionStart ); Bounds startBounds = cell.getNode().getCaretBounds( selectionStart ); cell.getNode().caretsProperty().remove( selectionStart ); if ( startBounds.getMinX() - graphicWidth < visibleLeftX ) { region = extendLeft( startBounds, graphicWidth ); } } // Addresses https://github.com/FXMisc/RichTextFX/issues/937#issuecomment-674319602 if ( parIdx == getParagraphs().size()-1 && cell.getNode().getLineCount() == 1 ) { region = new BoundingBox // Correcting the region's height ( region.getMinX(), region.getMinY(), region.getWidth(), cell.getNode().getLayoutBounds().getHeight() ); } virtualFlow.show(parIdx, region); } private ParagraphBox<PS, SEG, S> getCell(int index) { return virtualFlow.getCell(index).getNode(); } private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) { return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify( l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)), r -> MouseOverTextEvent.end()))); } private int getParagraphOffset(int parIdx) { return position(parIdx, 0).toOffset(); } private Bounds getParagraphBoundsOnScreen(Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell) { Bounds nodeLocal = cell.getNode().getBoundsInLocal(); Bounds nodeScreen = cell.getNode().localToScreen(nodeLocal); Bounds areaLocal = getBoundsInLocal(); Bounds areaScreen = localToScreen(areaLocal); // use area's minX if scrolled right and paragraph's left is not visible double minX = nodeScreen.getMinX() < areaScreen.getMinX() ? areaScreen.getMinX() : nodeScreen.getMinX(); // use area's minY if scrolled down vertically and paragraph's top is not visible double minY = nodeScreen.getMinY() < areaScreen.getMinY() ? areaScreen.getMinY() : nodeScreen.getMinY(); // use area's width whether paragraph spans outside of it or not // so that short or long paragraph takes up the entire space double width = areaScreen.getWidth(); // use area's maxY if scrolled up vertically and paragraph's bottom is not visible double maxY = nodeScreen.getMaxY() < areaScreen.getMaxY() ? nodeScreen.getMaxY() : areaScreen.getMaxY(); return new BoundingBox(minX, minY, width, maxY - minY); } private Optional<Bounds> getRangeBoundsOnScreen(int paragraphIndex, int from, int to) { return virtualFlow.getCellIfVisible(paragraphIndex) .map(c -> c.getNode().getRangeBoundsOnScreen(from, to)); } private void manageSubscription(Subscription subscription) { subscriptions = subscriptions.and(subscription); } private static Bounds extendLeft(Bounds b, double w) { if(w == 0) { return b; } else { return new BoundingBox( b.getMinX() - w, b.getMinY(), b.getWidth() + w, b.getHeight()); } } private void suspendVisibleParsWhile(Runnable runnable) { Suspendable.combine(beingUpdated, visibleParagraphs).suspendWhile(runnable); } private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_TEXT_FILL = new CustomCssMetaData<>( "-fx-highlight-text-fill", StyleConverter.getPaintConverter(), Color.WHITE, s -> s.highlightTextFill ); private static final List<CssMetaData<? extends Styleable, ?>> CSS_META_DATA_LIST; static { List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Region.getClassCssMetaData()); styleables.add(HIGHLIGHT_TEXT_FILL); CSS_META_DATA_LIST = Collections.unmodifiableList(styleables); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return CSS_META_DATA_LIST; } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return CSS_META_DATA_LIST; } }
package com.ripple.client.requests; import com.ripple.client.Client; import com.ripple.client.responses.Response; import com.ripple.client.enums.Command; import com.ripple.client.pubsub.Publisher; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; // We can just shift to using delegation public class Request extends Publisher<Request.events> { public void json(JSONObject jsonObject) { Iterator keys = jsonObject.keys(); while (keys.hasNext()) { String next = (String) keys.next(); json(next, jsonObject.opt(next)); } } // Base events class and aliases public static abstract class events<T> extends Publisher.Callback<T> {} public abstract static class OnSuccess extends events<Response> {} public abstract static class OnError extends events<Response> {} public abstract static class OnResponse extends events<Response> {} Client client; public Command cmd; public Response response; private JSONObject json; public int id; public Request(Command command, int assignedId, Client client) { this.client = client; cmd = command; id = assignedId; json = new JSONObject(); json("command", cmd.toString()); json("id", assignedId); } public JSONObject json() { return json; } public void json(String key, Object value) { try { json.put(key, value); } catch (JSONException e) { throw new RuntimeException(e); } } public void request() { Client.OnConnected onConnected = new Client.OnConnected() { @Override public void called(final Client client) { client.requests.put(id, Request.this); client.sendMessage(toJSON()); // TODO client.schedule(60000, new Runnable() { @Override public void run() { client.requests.remove(id); } }); } }; if (client.connected) { onConnected.called(client); } else { client.once(Client.OnConnected.class, onConnected); } } private JSONObject toJSON() { return json(); } public static class ResponseError { } public void handleResponse(JSONObject msg) { try { response = new Response(this, msg); } catch (Exception e) { try { System.out.println(msg.toString(4)); } catch (JSONException ignored) { } throw new RuntimeException(e); } if (response.succeeded) { emit(OnSuccess.class, response); } else { emit(OnError.class, response); } emit(OnResponse.class, response); } }
package org.obolibrary.robot; import java.util.*; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.*; import org.semanticweb.owlapi.model.parameters.OntologyCopy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Remove axioms from an ontology based on a series of inputs. * * @author <a href="mailto:rctauber@gmail.com">Becky Tauber</a> */ public class RemoveCommand implements Command { /** Logger. */ private static final Logger logger = LoggerFactory.getLogger(RemoveCommand.class); /** Store the command-line options for the command. */ private Options options; /** Initialze the command. */ public RemoveCommand() { Options o = CommandLineHelper.getCommonOptions(); o.addOption("i", "input", true, "load ontology from a file"); o.addOption("I", "input-iri", true, "load ontology from an IRI"); o.addOption("o", "output", true, "save ontology to a file"); o.addOption(null, "base-iri", true, "specify a base namespace"); o.addOption("t", "term", true, "term to remove"); o.addOption("T", "term-file", true, "load terms from a file"); o.addOption("e", "exclude-term", true, "term to exclude from removal"); o.addOption("E", "exclude-terms", true, "set of terms in text file to exclude from removal"); o.addOption("n", "include-term", true, "term to force include"); o.addOption("N", "include-terms", true, "set of terms in file to force include"); o.addOption("s", "select", true, "select a set of terms based on relations"); o.addOption("a", "axioms", true, "filter only for given axiom types"); o.addOption("r", "trim", true, "if true, remove axioms containing any selected object"); o.addOption( "S", "signature", true, "if true, remove axioms with any selected entity in their signature"); o.addOption( "p", "preserve-structure", true, "if false, do not preserve hierarchical relationships"); options = o; } /** * Name of the command. * * @return name */ public String getName() { return "remove"; } /** * Brief description of the command. * * @return description */ public String getDescription() { return "remove axioms from an ontology"; } /** * Command-line usage for the command. * * @return usage */ public String getUsage() { return "robot remove --input <file> " + "--output <file>"; } /** * Command-line options for the command. * * @return options */ public Options getOptions() { return options; } /** * Handle the command-line and file operations. * * @param args strings to use as arguments */ public void main(String[] args) { try { execute(null, args); } catch (Exception e) { CommandLineHelper.handleException(getUsage(), getOptions(), e); } } /** * Given an input state and command line arguments, create a new ontology with removed axioms and * return a new state. The input ontology is not changed. * * @param state the state from the previous command, or null * @param args the command-line arguments * @return a new state with the new ontology * @throws Exception on any problem */ public CommandState execute(CommandState state, String[] args) throws Exception { CommandLine line = CommandLineHelper.getCommandLine(getUsage(), getOptions(), args); if (line == null) { return null; } IOHelper ioHelper = CommandLineHelper.getIOHelper(line); state = CommandLineHelper.updateInputOntology(ioHelper, state, line); OWLOntology ontology = state.getOntology(); OWLOntologyManager manager = ontology.getOWLOntologyManager(); // Get a set of relation types, or annotations to select List<String> selects = CommandLineHelper.getOptionalValues(line, "select"); // If the select option wasn't provided, default to self if (selects.isEmpty()) { selects.add("self"); } // Selects should be processed in order, allowing unions in one --select List<List<String>> selectGroups = new ArrayList<>(); boolean anonymous = false; for (String select : selects) { // The single group is a split of the one --select List<String> selectGroup = CommandLineHelper.splitSelects(select); // Imports should be handled separately if (selectGroup.contains("imports")) { OntologyHelper.removeImports(ontology); selectGroup.remove("imports"); } if (selectGroup.contains("ontology")) { OntologyHelper.removeOntologyAnnotations(ontology); selectGroup.remove("ontology"); } if (selectGroup.contains("anonymous")) { anonymous = true; } if (!selectGroup.isEmpty()) { selectGroups.add(selectGroup); } } // Get the objects to remove Set<OWLObject> relatedObjects = getObjects(line, ioHelper, ontology, selectGroups); if (relatedObjects.isEmpty()) { // nothing to remove - save and exit CommandLineHelper.maybeSaveOutput(line, ontology); state.setOntology(ontology); return state; } // Copy the unchanged ontology to reserve for filling gaps later OWLOntology copy = OWLManager.createOWLOntologyManager().copyOntology(ontology, OntologyCopy.DEEP); // Remove specific axioms manager.removeAxioms(ontology, getAxioms(line, ioHelper, ontology, relatedObjects)); // Handle gaps boolean preserveStructure = CommandLineHelper.getBooleanValue(line, "preserve-structure", true); if (preserveStructure) { // Since we are preserving the structure between the objects that were NOT removed, we need to // get the complement of the removed object set and build relationships between those objects. Set<OWLObject> complementObjects = RelatedObjectsHelper.select(ontology, ioHelper, relatedObjects, "complement"); manager.addAxioms( ontology, RelatedObjectsHelper.spanGaps(copy, complementObjects, anonymous)); } // Save the changed ontology and return the state CommandLineHelper.maybeSaveOutput(line, ontology); state.setOntology(ontology); return state; } /** * Given a command line, an IOHelper, an ontology, and a list of select groups, return the objects * from the ontology based on the select groups. * * @param line CommandLine to get options from * @param ioHelper IOHelper to get IRIs * @param ontology OWLOntology to get objects from * @param selectGroups List of select groups (lists of select options) * @return set of selected objects from the ontology * @throws Exception on issue getting terms or processing selects */ protected static Set<OWLObject> getObjects( CommandLine line, IOHelper ioHelper, OWLOntology ontology, List<List<String>> selectGroups) throws Exception { // Get a set of entities to start with Set<OWLObject> objects = new HashSet<>(); // track if a set of input IRIs were provided boolean hasInputIRIs = false; if (line.hasOption("term") || line.hasOption("term-file")) { Set<IRI> entityIRIs = CommandLineHelper.getTerms(ioHelper, line, "term", "term-file"); if (!entityIRIs.isEmpty()) { objects.addAll(OntologyHelper.getEntities(ontology, entityIRIs)); hasInputIRIs = true; } } boolean hadSelection = CommandLineHelper.hasFlagOrCommand(line, "select"); boolean internal = false; boolean external = false; if (line.hasOption("axioms")) { for (String ats : CommandLineHelper.getOptionalValue(line, "axioms").split(" ")) { if (ats.equalsIgnoreCase("internal")) { internal = true; } else if (ats.equalsIgnoreCase("external")) { external = true; } } } if (hadSelection && selectGroups.isEmpty() && objects.isEmpty() && !internal && !external) { // If removing imports or ontology annotations // and there are no other selects, save and return return objects; } else if (objects.isEmpty() && hasInputIRIs && !internal && !external) { // if objects is empty AND there WERE input IRIs // there is nothing to remove because the IRIs do not exist in the ontology return objects; } else if (objects.isEmpty()) { // if objects is empty AND there were NO input IRIs add all // OR internal/external were selected // this means that we are adding everything to the set to start objects.addAll(OntologyHelper.getObjects(ontology)); } // Use the select statements to get a set of objects to remove Set<OWLObject> relatedObjects = RelatedObjectsHelper.selectGroups(ontology, ioHelper, objects, selectGroups); // Remove all the excluded terms from that set if (line.hasOption("exclude-term") || line.hasOption("exclude-terms")) { Set<IRI> excludeIRIs = CommandLineHelper.getTerms(ioHelper, line, "exclude-term", "exclude-terms"); Set<OWLObject> excludeObjects = new HashSet<>(OntologyHelper.getEntities(ontology, excludeIRIs)); relatedObjects.removeAll(excludeObjects); } // Add all the include terms if (line.hasOption("include-term") || line.hasOption("include-terms")) { Set<IRI> includeIRIs = CommandLineHelper.getTerms(ioHelper, line, "include-term", "include-terms"); Set<OWLObject> includeObjects = new HashSet<>(OntologyHelper.getEntities(ontology, includeIRIs)); relatedObjects.addAll(includeObjects); } return relatedObjects; } /** * Given a command line, an IOHelper, an ontology, and a set of objects, return the related axioms * for those objects to remove from the ontology. * * @param line command line to use * @param ioHelper IOHelper to resolve prefixes for base namespaces * @param ontology ontology to select axioms from * @param relatedObjects objects to select axioms for * @return set of axioms to remove */ private static Set<OWLAxiom> getAxioms( CommandLine line, IOHelper ioHelper, OWLOntology ontology, Set<OWLObject> relatedObjects) { // Get a set of axiom types boolean internal = false; boolean external = false; if (line.hasOption("axioms")) { for (String ats : CommandLineHelper.getOptionalValue(line, "axioms").split(" ")) { if (ats.equalsIgnoreCase("internal")) { internal = true; } else if (ats.equalsIgnoreCase("external")) { external = true; } } } Set<Class<? extends OWLAxiom>> axiomTypes = CommandLineHelper.getAxiomValues(line); // Use these two options to determine which axioms to remove boolean trim = CommandLineHelper.getBooleanValue(line, "trim", true); boolean signature = CommandLineHelper.getBooleanValue(line, "signature", false); // Get the axioms and remove them Set<OWLAxiom> axiomsToRemove = RelatedObjectsHelper.getAxioms(ontology, relatedObjects, axiomTypes, trim, signature); // Then select internal or external, if present List<String> baseNamespaces = CommandLineHelper.getBaseNamespaces(line, ioHelper); if (internal && external) { logger.warn( "Both 'internal' and 'external' axioms are selected - these axiom selectors will be ignored."); } else if (internal) { axiomsToRemove = RelatedObjectsHelper.getInternalAxioms(baseNamespaces, axiomsToRemove); } else if (external) { axiomsToRemove = RelatedObjectsHelper.getExternalAxioms(baseNamespaces, axiomsToRemove); } return axiomsToRemove; } }
package io.spine.server.event.model; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.protobuf.Message; import io.spine.core.CommandContext; import io.spine.core.DispatchedCommand; import io.spine.core.EventContext; import io.spine.core.EventEnvelope; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.ImmutableList.of; import static io.spine.protobuf.AnyPacker.unpack; import static io.spine.util.Exceptions.newIllegalStateException; /** * @author Dmytro Dashenkov */ enum EventAcceptor { MESSAGE(of(Message.class)) { @Override List<?> arguments(EventEnvelope envelope) { Message message = envelope.getMessage(); return of(message); } }, MESSAGE_EVENT_CXT(of(Message.class, EventContext.class)) { @Override List<?> arguments(EventEnvelope envelope) { Message message = envelope.getMessage(); EventContext context = envelope.getEventContext(); return of(message, context); } }, MESSAGE_COMMAND_CXT(of(Message.class, CommandContext.class)) { @Override List<?> arguments(EventEnvelope envelope) { Message message = envelope.getMessage(); CommandContext context = envelope.getRejectionOrigin() .getContext(); return of(message, context); } }, MESSAGE_COMMAND_MSG(of(Message.class, Message.class)) { @Override List<?> arguments(EventEnvelope envelope) { Message message = envelope.getMessage(); Message commandMessage = unpack(envelope.getRejectionOrigin() .getMessage()); return of(message, commandMessage); } }, MESSAGE_COMMAND_MSG_COMMAND_CXT(of(Message.class, Message.class, CommandContext.class)) { @Override List<?> arguments(EventEnvelope envelope) { Message message = envelope.getMessage(); DispatchedCommand origin = envelope.getRejectionOrigin(); Message commandMessage = unpack(origin.getMessage()); CommandContext context = origin.getContext(); return of(message, commandMessage, context); } }; private final ImmutableList<Class<?>> expectedParameters; EventAcceptor(ImmutableList<Class<?>> types) { this.expectedParameters = types; } static Object accept(Object receiver, Method method, EventEnvelope envelope) throws InvocationTargetException { EventAcceptor acceptor = from(method).orElseThrow( () -> newIllegalStateException("Method %s is not a valid event acceptor.", method.toString()) ); method.setAccessible(true); Object result = acceptor.doAccept(receiver, method, envelope); return result; } @VisibleForTesting // Would be private otherwise. static Optional<EventAcceptor> from(Method method) { List<Class<?>> parameters = copyOf(method.getParameterTypes()); Optional<EventAcceptor> result = Stream.of(values()) .filter(acceptor -> acceptor.matches(parameters)) .findFirst(); return result; } abstract List<?> arguments(EventEnvelope envelope); private Object doAccept(Object receiver, Method acceptorMethod, EventEnvelope envelope) throws InvocationTargetException { Object[] arguments = arguments(envelope).toArray(); try { return acceptorMethod.invoke(receiver, arguments); } catch (IllegalAccessException e) { throw newIllegalStateException(e, "Method %s is inaccessible.", acceptorMethod); } } private boolean matches(List<Class<?>> methodParams) { if (methodParams.size() != expectedParameters.size()) { return false; } for (int i = 0; i < methodParams.size(); i++) { Class<?> actual = methodParams.get(i); Class<?> expected = expectedParameters.get(i); if (!expected.isAssignableFrom(actual)) { return false; } } return true; } }
package fi.nls.oskari.util; /** * Conversion helper methods */ public class ConversionHelper { /** * Count the number of instances of substring within a string. * * @param string String to look for substring in. * @param substring Sub-string to look for. * @return Count of substrings in string. */ public static int count(final String string, final String substring) { int count = 0; int idx = 0; while ((idx = string.indexOf(substring, idx)) != -1) { idx++; count++; } return count; } /** * Returns a string that if its not null and default value if it is * * @param str * @param defaultValue * @return string */ public static final String getString(final String str, final String defaultValue) { if (str != null) { return str; } return defaultValue; } /** * Parses long from String * * @param strToParse * @param defaultValue * @return long */ public static final long getLong(final String strToParse, final long defaultValue) { try { return Long.parseLong(strToParse); } catch (Exception e) { return defaultValue; } } /** * Parses int from String * * @param strToParse * @param defaultValue * @return */ public static final int getInt(final String strToParse, final int defaultValue) { if(strToParse == null) { return defaultValue; } try { return Integer.parseInt(strToParse); } catch (Exception e) { return defaultValue; } } /** * Parses double from String * * @param strToParse * @param defaultValue * @return */ public static final double getDouble(final String strToParse, final double defaultValue) { try { return Double.parseDouble(strToParse); } catch (Exception e) { return defaultValue; } } /** * Parses boolean from String. Returns defaultValue if strToParse is null. * * @param strToParse * @param defaultValue * @return */ public static final boolean getBoolean(final String strToParse, final boolean defaultValue) { if(strToParse == null) { return defaultValue; } try { return Boolean.parseBoolean(strToParse); } catch (Exception ex) { return defaultValue; } } }
package zero.thrift.proxy; import com.zero.common.ResultInfo; import com.zero.thrift.protocol.response.TBankInfo; import com.zero.thrift.protocol.response.TGetBankCardListResult; import com.zero.thrift.protocol.response.TResponseStatus; import com.zero.thrift.protocol.service.ThriftBankCardService; import org.apache.thrift.TException; import org.springframework.beans.factory.annotation.Autowired; import zero.annotation.ThriftHandler; import zero.model.FtcSupportBank; import zero.service.BankCardService; import zero.util.DozerUtil; import java.util.HashMap; import java.util.List; import java.util.Map; @ThriftHandler public class BankCardServiceHandler implements ThriftBankCardService.Iface { @Autowired private BankCardService bankCardService; @Override public TGetBankCardListResult getBankCardList() throws TException { TGetBankCardListResult result = new TGetBankCardListResult(); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("flag", true); ResultInfo resultInfo = bankCardService.getSupportBankList(paramMap); if (resultInfo.isSuccess()) { List<FtcSupportBank> resultData = (List<FtcSupportBank>) resultInfo.getResultData(); List<TBankInfo> tBankInfoList = DozerUtil.mapAsList(resultData, TBankInfo.class); result.setDataList(tBankInfoList); } result.setResponseStatus(new TResponseStatus(resultInfo.getCode(), resultInfo.getMsg())); return result; } }
package org.neo4j.api.core; import org.neo4j.impl.transaction.TransactionUtil; /** * A utility class to manage transactions in Neo. All operations that work with * the node space (even read operations) must be wrapped in a transaction. * Fortunately, the Transaction class makes this very easy. Here's the idiomatic * use of transactions in Neo:<pre><code> Transaction tx = Transaction.begin(); * try * { * ... // any operation that works with the node space * tx.success(); * } * finally * { * tx.finish(); * } </code></pre> * <p> * Let's walk through this example line by line. First we retrieve a Transaction * object by invoking the static {@link #begin()} factory method. This creates * a new Transaction instance which has internal state to keep track of whether * the current transaction is successful. Then we wrap all operations that work * with the node space in a try-finally block. At the end of the block, we * invoke the {@link #finish() tx.success()} method to indicate that the * transaction is successful. As we exit the block, the finally clause will * kick in and {@link #finish() tx.finish} will commit the transaction if the * internal state indicates success or else mark it for rollback. * <p> * If an exception is raised in the try-block, <code>tx.success()</code> will * never be invoked and the internal state of the transaction object will cause * <code>tx.finish()</code> to roll back the transaction. This is very * important: unless {@link #success()} is invoked, the transaction will fail * upon {@link #finish()}. A transaction can be explicitly marked for rollback * by invoking the {@link #failure() tx.failure()} method. */ public class Transaction { private static final Transaction PLACEBO_TRANSACTION = new Transaction() { @Override public void failure() { TransactionUtil.markAsRollbackOnly(); } @Override public void finish() { // Do nothing } @Override public void success() { // Do nothing } }; private boolean success = false; /** * Private constructor. */ private Transaction() { } /** * Starts a new transaction. * @return a transaction object representing the current transaction */ public static Transaction begin() { if ( TransactionUtil.beginTx() ) { return new Transaction(); } else { return PLACEBO_TRANSACTION; } } /** * Marks this transaction as failed, which means that it will inexplicably be * rolled back upon invocation of {@link #finish()}. Once this method has * been invoked, it doesn't matter how many times {@link #success()} is * invoked -- the transaction will still be rolled back. */ public void failure() { this.success = false; TransactionUtil.markAsRollbackOnly(); } /** * Marks this transaction as successful, which means that it will be * commited upon invocation of {@link #finish()} unless {@link #failure()} * has or will be invoked before then. */ public void success() { success = true; } /** * Commits or marks this transaction for rollback, depending on whether * {@link #success()} or {@link #failure()} has been previously invoked. */ public void finish() { TransactionUtil.finishTx( success, true ); } }
package com.concurrent_ruby.ext; import java.io.IOException; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyModule; import org.jruby.RubyObject; import org.jruby.RubyBasicObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.load.Library; import org.jruby.runtime.Block; import org.jruby.runtime.Visibility; import org.jruby.runtime.ThreadContext; import org.jruby.util.unsafe.UnsafeHolder; public class SynchronizationLibrary implements Library { private static final ObjectAllocator JRUBY_OBJECT_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new JRubyObject(runtime, klazz); } }; private static final ObjectAllocator OBJECT_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new Object(runtime, klazz); } }; private static final ObjectAllocator ABSTRACT_LOCKABLE_OBJECT_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new AbstractLockableObject(runtime, klazz); } }; private static final ObjectAllocator JRUBY_LOCKABLE_OBJECT_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new JRubyLockableObject(runtime, klazz); } }; public void load(Ruby runtime, boolean wrap) throws IOException { RubyModule synchronizationModule = runtime. defineModule("Concurrent"). defineModuleUnder("Synchronization"); RubyModule jrubyAttrVolatileModule = synchronizationModule.defineModuleUnder("JRubyAttrVolatile"); jrubyAttrVolatileModule.defineAnnotatedMethods(JRubyAttrVolatile.class); defineClass(runtime, synchronizationModule, "AbstractObject", "JRubyObject", JRubyObject.class, JRUBY_OBJECT_ALLOCATOR); defineClass(runtime, synchronizationModule, "JRubyObject", "Object", Object.class, OBJECT_ALLOCATOR); defineClass(runtime, synchronizationModule, "Object", "AbstractLockableObject", AbstractLockableObject.class, ABSTRACT_LOCKABLE_OBJECT_ALLOCATOR); defineClass(runtime, synchronizationModule, "AbstractLockableObject", "JRubyLockableObject", JRubyLockableObject.class, JRUBY_LOCKABLE_OBJECT_ALLOCATOR); } private RubyClass defineClass(Ruby runtime, RubyModule namespace, String parentName, String name, Class javaImplementation, ObjectAllocator allocator) { final RubyClass parentClass = namespace.getClass(parentName); if (parentClass == null) { System.out.println("not found " + parentName); throw runtime.newRuntimeError(namespace.toString() + "::" + parentName + " is missing"); } final RubyClass newClass = namespace.defineClassUnder(name, parentClass, allocator); newClass.defineAnnotatedMethods(javaImplementation); return newClass; } // Facts: // - all ivar reads are without any synchronisation of fences see // https://github.com/jruby/jruby/blob/master/core/src/main/java/org/jruby/runtime/ivars/VariableAccessor.java#L110-110 // - writes depend on UnsafeHolder.U, null -> SynchronizedVariableAccessor, !null -> StampedVariableAccessor // SynchronizedVariableAccessor wraps with synchronized block, StampedVariableAccessor uses fullFence or // volatilePut // module JRubyAttrVolatile public static class JRubyAttrVolatile { // volatile threadContext is used as a memory barrier per the JVM memory model happens-before semantic // on volatile fields. any volatile field could have been used but using the thread context is an // attempt to avoid code elimination. private static volatile ThreadContext threadContext = null; @JRubyMethod(name = "full_memory_barrier", visibility = Visibility.PUBLIC) public static IRubyObject fullMemoryBarrier(ThreadContext context, IRubyObject self) { // Prevent reordering of ivar writes with publication of this instance if (UnsafeHolder.U == null || !UnsafeHolder.SUPPORTS_FENCES) { // Assuming that following volatile read and write is not eliminated it simulates fullFence. // If it's eliminated it'll cause problems only on non-x86 platforms. final ThreadContext oldContext = threadContext; threadContext = context; } else { UnsafeHolder.fullFence(); } return context.nil; } @JRubyMethod(name = "instance_variable_get_volatile", visibility = Visibility.PUBLIC) public static IRubyObject instanceVariableGetVolatile(ThreadContext context, IRubyObject self, IRubyObject name) { // Ensure we ses latest value with loadFence if (UnsafeHolder.U == null || !UnsafeHolder.SUPPORTS_FENCES) { // piggybacking on volatile read, simulating loadFence final ThreadContext oldContext = threadContext; return ((RubyBasicObject)self).instance_variable_get(context, name); } else { UnsafeHolder.loadFence(); return ((RubyBasicObject)self).instance_variable_get(context, name); } } @JRubyMethod(name = "instance_variable_set_volatile", visibility = Visibility.PUBLIC) public static IRubyObject InstanceVariableSetVolatile(ThreadContext context, IRubyObject self, IRubyObject name, IRubyObject value) { // Ensure we make last update visible if (UnsafeHolder.U == null || !UnsafeHolder.SUPPORTS_FENCES) { // piggybacking on volatile write, simulating storeFence final IRubyObject result = ((RubyBasicObject)self).instance_variable_set(name, value); threadContext = context; return result; } else { // JRuby uses StampedVariableAccessor which calls fullFence // so no additional steps needed. // See https://github.com/jruby/jruby/blob/master/core/src/main/java/org/jruby/runtime/ivars/StampedVariableAccessor.java#L151-L159 return ((RubyBasicObject)self).instance_variable_set(name, value); } } } @JRubyClass(name = "JRubyObject", parent = "AbstractObject") public static class JRubyObject extends RubyObject { public JRubyObject(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } } @JRubyClass(name = "Object", parent = "JRubyObject") public static class Object extends JRubyObject { public Object(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } } @JRubyClass(name = "AbstractLockableObject", parent = "Object") public static class AbstractLockableObject extends Object { public AbstractLockableObject(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } } @JRubyClass(name = "JRubyLockableObject", parent = "AbstractLockableObject") public static class JRubyLockableObject extends JRubyObject { public JRubyLockableObject(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } @JRubyMethod(name = "synchronize", visibility = Visibility.PROTECTED) public IRubyObject rubySynchronize(ThreadContext context, Block block) { synchronized (this) { return block.yield(context, null); } } @JRubyMethod(name = "ns_wait", optional = 1, visibility = Visibility.PROTECTED) public IRubyObject nsWait(ThreadContext context, IRubyObject[] args) { Ruby runtime = context.runtime; if (args.length > 1) { throw runtime.newArgumentError(args.length, 1); } Double timeout = null; if (args.length > 0 && !args[0].isNil()) { timeout = args[0].convertToFloat().getDoubleValue(); if (timeout < 0) { throw runtime.newArgumentError("time interval must be positive"); } } if (Thread.interrupted()) { throw runtime.newConcurrencyError("thread interrupted"); } boolean success = false; try { success = context.getThread().wait_timeout(this, timeout); } catch (InterruptedException ie) { throw runtime.newConcurrencyError(ie.getLocalizedMessage()); } finally { // An interrupt or timeout may have caused us to miss // a notify that we consumed, so do another notify in // case someone else is available to pick it up. if (!success) { this.notify(); } } return this; } @JRubyMethod(name = "ns_signal", visibility = Visibility.PROTECTED) public IRubyObject nsSignal(ThreadContext context) { notify(); return this; } @JRubyMethod(name = "ns_broadcast", visibility = Visibility.PROTECTED) public IRubyObject nsBroadcast(ThreadContext context) { notifyAll(); return this; } } }
package org.minimalj.rest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.minimalj.application.Application; import org.minimalj.application.Configuration; import org.minimalj.backend.Backend; import org.minimalj.metamodel.model.MjEntity; import org.minimalj.metamodel.model.MjModel; import org.minimalj.repository.query.By; import org.minimalj.repository.query.Query; import org.minimalj.repository.query.Query.QueryLimitable; import org.minimalj.rest.openapi.OpenAPIFactory; import org.minimalj.security.Subject; import org.minimalj.transaction.InputStreamTransaction; import org.minimalj.transaction.OutputStreamTransaction; import org.minimalj.transaction.Transaction; import org.minimalj.util.SerializationContainer; import org.minimalj.util.StringUtils; import org.minimalj.util.resources.Resources; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoHTTPD.Response.Status; public class RestHTTPD extends NanoHTTPD { private final Map<String, Class<?>> classByName; public RestHTTPD( int port, boolean secure) { super(port); if (secure) { try { String keyAndTrustStoreClasspathPath = Configuration.get("MjKeystore"); // in example '/mjdevkeystore.jks' char[] passphrase = Configuration.get("MjKeystorePassphrase").toCharArray(); // ub example 'mjdev1' makeSecure(makeSSLSocketFactory(keyAndTrustStoreClasspathPath, passphrase), null); } catch (IOException e) { e.printStackTrace(); } } classByName = initClassMap(); } protected Map<String, Class<?>> initClassMap() { Map<String, Class<?>> classByName = new HashMap<>(); MjModel model = new MjModel(Application.getInstance().getEntityClasses()); for (MjEntity entity : model.entities) { classByName.put(entity.getClazz().getSimpleName(), entity.getClazz()); } return classByName; } @Override public Response serve(String uriString, Method method, Map<String, String> headers, Map<String, String> parameters, Map<String, String> files) { String[] pathElements; try { URI uri = new URI(uriString); String path = uri.getPath(); if (path.startsWith("/")) { path = path.substring(1); } pathElements = path.split("/"); } catch (URISyntaxException e) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/html", e.getMessage()); } Class<?> clazz = null; if (pathElements.length > 0 && !Character.isLowerCase(pathElements[0].charAt(0))) { clazz = classByName.get(pathElements[0]); if (clazz == null) { return newFixedLengthResponse(Status.NOT_FOUND, "text/html", "Class not available"); } } if (method == Method.GET) { if (pathElements.length == 0) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/html", "Please specify class"); } if (StringUtils.equals("swagger-ui", pathElements[0])) { if (pathElements.length == 1) { return newChunkedResponse(Status.OK, "text/html", getClass().getResourceAsStream(uriString + "/index.html")); } else if (StringUtils.equals("swagger.json", pathElements[1])) { return newFixedLengthResponse(Status.OK, "text/json", new OpenAPIFactory().create(Application.getInstance())); } else { int pos = uriString.lastIndexOf('.'); String mimeType = Resources.getMimeType(uriString.substring(pos + 1)); return newChunkedResponse(Status.OK, mimeType, getClass().getResourceAsStream(uriString)); } } if (pathElements.length == 1) { // GET entity (get all or pages of size x) Query query = By.all(); String sizeParameter = parameters.get("size"); if (!StringUtils.isBlank(sizeParameter)) { int offset = 0; String offsetParameter = parameters.get("offset"); if (!StringUtils.isBlank(offsetParameter)) { try { offset = Integer.valueOf(offsetParameter); } catch (NumberFormatException e) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/json", "page parameter invalid: " + offsetParameter); } } try { int size = Integer.valueOf(sizeParameter); query = ((QueryLimitable) query).limit(offset, size); } catch (NumberFormatException e) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/json", "size parameter invalid: " + sizeParameter); } } List<?> object = Backend.find(clazz, query); return newFixedLengthResponse(Status.OK, "text/json", EntityJsonWriter.write(object)); } if (pathElements.length == 2) { // GET entity/id (get one) String id = pathElements[1]; Object object = Backend.read(clazz, id); return newFixedLengthResponse(Status.OK, "text/json", EntityJsonWriter.write(object)); } } else if (method == Method.POST) { if (clazz != null) { if (pathElements.length >= 2) { String id = pathElements[1]; String inputString = files.get("postData"); if (inputString == null) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "No Input"); } Object inputObject = EntityJsonReader.read(clazz, inputString); Backend.update(inputObject); return newFixedLengthResponse(Status.OK, "text/json", "success"); } else { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Post excepts id in url"); } } } else if (method == Method.DELETE) { if (clazz != null) { if (pathElements.length >= 2) { String id = pathElements[1]; Backend.delete(clazz, id); } else { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Post expects id in url"); } } } else if (method == Method.PUT) { String inputFileName = files.get("content"); if (inputFileName == null) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "No Input"); } if (pathElements.length > 0) { if (StringUtils.equals("java-transaction", pathElements[0])) { return transaction(headers, inputFileName); } } if (clazz != null) { String input = ""; try { List<String> inputLines = Files.readAllLines(new File(inputFileName).toPath()); for (String line : inputLines) { input = input + line; } Object inputObject = EntityJsonReader.read(clazz, input); // IdUtils.setId(inputObject, null); Object id = Backend.insert(inputObject); return newFixedLengthResponse(Status.OK, "text/plain", id.toString()); } catch (IOException x) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Could not read input"); } } } else if (method == Method.OPTIONS) { Response response = newFixedLengthResponse(Status.OK, "text/plain", null); response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, PATCH, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "API-Key,accept, Content-Type"); response.addHeader("Access-Control-Max-Age", "1728000"); return response; } else { return newFixedLengthResponse(Status.METHOD_NOT_ALLOWED, "text/plain", "Method not allowed: " + method); } return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Not a valid request url"); } private Response transaction(Map<String, String> headers, String inputFileName) { try (InputStream is = new FileInputStream(inputFileName)) { if (Backend.getInstance().isAuthenticationActive()) { String token = headers.get("token"); return transaction(token, is); } else { return transaction(is); } } catch (Exception e) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", e.getMessage()); } } private Response transaction(String token, InputStream is) { if (!StringUtils.isEmpty(token)) { Subject subject = Backend.getInstance().getAuthentication().getUserByToken(UUID.fromString(token)); if (subject != null) { Subject.setCurrent(subject); } else { return newFixedLengthResponse(Status.UNAUTHORIZED, "text/plain", "Invalid token"); } } try { return transaction(is); } finally { Subject.setCurrent(null); } } private Response transaction(InputStream inputStream) { try (ObjectInputStream ois = new ObjectInputStream(inputStream)) { Object input = ois.readObject(); if (!(input instanceof Transaction)) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Input not a Transaction but a " + input.getClass().getName()); } Transaction<?> transaction = (Transaction<?>) input; if (transaction instanceof InputStreamTransaction) { InputStreamTransaction<?> inputStreamTransaction = (InputStreamTransaction<?>) transaction; inputStreamTransaction.setStream(ois); } if (transaction instanceof OutputStreamTransaction) { return newFixedLengthResponse(Status.NOT_IMPLEMENTED, "text/plain", "OutputStreamTransaction not implemented"); } Object output; try { output = Backend.execute((Transaction<?>) transaction); } catch (Exception e) { return newFixedLengthResponse(Status.INTERNAL_ERROR, "text/plain", e.getMessage()); } try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream)) { oos.writeObject(SerializationContainer.wrap(output)); oos.flush(); byte[] bytes = byteArrayOutputStream.toByteArray(); try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) { return newFixedLengthResponse(Status.OK, "application/octet-stream", byteArrayInputStream, bytes.length); } } } catch (Exception e) { return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", e.getMessage()); } } }
package be.ugent.zeus.hydra; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import android.widget.TextView; import be.ugent.zeus.hydra.data.rss.Item; import com.actionbarsherlock.app.SherlockActivity; import java.text.SimpleDateFormat; /** * TODO: implement this properly as a fragment, so we can display this a lot cleaner on tablets (running 4.0+, * i think) * * @author Thomas Meire */ public class SchamperDailyItem extends SherlockActivity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.schamper_item); Item item = (Item) getIntent().getSerializableExtra("item"); String date = String.format(new SimpleDateFormat("dd MMM yyyy hh:mm").format(item.pubDate)); String html = "<body>" + " <header><h1>" + item.title + "</h1><p class='meta'>" + date + "<br />door " + item.creator + "</div></header>" + " <div class='content'>" + item.description + "</div>" + "</body>"; WebView content = (WebView) findViewById(R.id.schamper_item); String withCss = "<link rel=\"stylesheet\" type=\"text/css\" href=\"schamper.css\" />" + html; content.loadDataWithBaseURL("file:///android_asset/", withCss, "text/html", "UTF-8", null); } }
package com.xenon.greenup; import java.util.ArrayList; import com.xenon.greenup.api.APIServerInterface; import com.xenon.greenup.api.Comment; import com.xenon.greenup.api.CommentPage; import android.support.v4.app.ListFragment; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FeedSectionFragment extends ListFragment { private final APIServerInterface api = new APIServerInterface(); private int lastPageLoaded = 1; private ArrayList<Comment> comments = new ArrayList<Comment>(60); // Default to having enough space for 3 spaces public FeedSectionFragment(){ } public void onCreate(Bundle bundle){ super.onCreate(bundle); CommentPage cp = api.getComments(null,lastPageLoaded ); this.comments = cp.getCommentsList(); //Set the adapter Activity currentActivity = getActivity(); //If we have no internet then we will get nothing back from the api if(this.comments == null) this.comments = new ArrayList<Comment>(60); //Do feed rendering async or else it will take orders of magnitude longer to render new ASYNCLoadTask(this,currentActivity,this.comments).execute(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.feed, container, false); } private class ASYNCLoadTask extends AsyncTask<Void,Void,Integer>{ private final Activity act; private final ArrayList<Comment> cmts; private final FeedSectionFragment fsf; //Constructor for GET requests public ASYNCLoadTask(FeedSectionFragment fsf, Activity a, ArrayList<Comment> c) { //apparently I've jumped back to 1982 when variable length matters this.act = a; this.cmts = c; this.fsf = fsf; } @Override protected Integer doInBackground(Void...voids) { this.fsf.setListAdapter(new CommentAdapter(this.act,this.cmts)); return 0; } } }
package com.icfi.api; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * This class is a 'Hello World' REST API application example to show our expertise of Java, Spring Boot, and DevSecOps. * */ @Controller @EnableAutoConfiguration public class ApiApplication { private static Properties props; private static final Logger logger = LoggerFactory.getLogger(ApiApplication.class); /** * Initializes all properties for config * */ @PostConstruct public void init() { try { props = PropertiesLoaderUtils.loadProperties(new ClassPathResource("/META-INF/build-info.properties")); } catch (IOException e) { logger.error("Unable to load build.properties", e); props = new Properties(); } } /** * Exposes a REST endpoint '/greet' to return a Hello World message to the client. * * @return Map response body with message info */ @RequestMapping(value = { "/greet" }, method = RequestMethod.GET) public @ResponseBody Map<String, String> greet() { Map<String, String> message = new HashMap<String, String>(); message.put("greeting", "Hello World"); return message; } /** * Exposes a REST endpoint '/' to return application build info to the client. * * @return Map response body with message info */ @RequestMapping(value = { "/", "/version" }, method = RequestMethod.GET) public @ResponseBody Map<String, String> version() { Map<String, String> message = new HashMap<String, String>(); message.put("name", props.getProperty("build.artifact")); message.put("version", props.getProperty("build.version")); message.put("timestamp", props.getProperty("build.time")); return message; } public static void main(String[] args) { SpringApplication.run(ApiApplication.class, args); } }
package edu.umd.cs.findbugs.ba; import java.util.HashSet; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.Repository; import org.apache.bcel.classfile.ExceptionTable; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.*; /** * Facade for class hierarchy queries. * These typically access the class hierarchy using * the {@link org.apache.bcel.Repository} class. Callers should generally * expect to handle ClassNotFoundException for when referenced * classes can't be found. * * @author David Hovemeyer */ public class Hierarchy { private static final boolean DEBUG_METHOD_LOOKUP = Boolean.getBoolean("hier.lookup.debug"); /** * Type of java.lang.Exception. */ public static final ObjectType EXCEPTION_TYPE = new ObjectType("java.lang.Exception"); /** * Type of java.lang.Error. */ public static final ObjectType ERROR_TYPE = new ObjectType("java.lang.Error"); /** * Type of java.lang.RuntimeException. */ public static final ObjectType RUNTIME_EXCEPTION_TYPE = new ObjectType("java.lang.RuntimeException"); /** * Determine whether one class (or reference type) is a subtype * of another. * * @param clsName the name of the class or reference type * @param possibleSupertypeClassName the name of the possible superclass * @return true if clsName is a subtype of possibleSupertypeClassName, * false if not */ public static boolean isSubtype(String clsName, String possibleSupertypeClassName) throws ClassNotFoundException { ObjectType cls = new ObjectType(clsName); ObjectType superCls = new ObjectType(possibleSupertypeClassName); return isSubtype(cls, superCls); } /** * Determine if one reference type is a subtype of another. * * @param t a reference type * @param possibleSupertype the possible supertype * @return true if t is a subtype of possibleSupertype, * false if not */ public static boolean isSubtype(ReferenceType t, ReferenceType possibleSupertype) throws ClassNotFoundException { return t.isAssignmentCompatibleWith(possibleSupertype); } /** * Determine if the given ObjectType reference represents * a <em>universal</em> exception handler. That is, * one that will catch any kind of exception. * * @param catchType the ObjectType of the exception handler * @return true if catchType is null, or if catchType is * java.lang.Throwable */ public static boolean isUniversalExceptionHandler(ObjectType catchType) { return catchType == null || catchType.equals(Type.THROWABLE); } /** * Determine if the given ObjectType refers to an unchecked * exception (RuntimeException or Error). */ public static boolean isUncheckedException(ObjectType type) throws ClassNotFoundException { return isSubtype(type, RUNTIME_EXCEPTION_TYPE) || isSubtype(type, ERROR_TYPE); } /** * Determine if method whose name and signature is specified * is a monitor wait operation. * * @param methodName name of the method * @param methodSig signature of the method * @return true if the method is a monitor wait, false if not */ public static boolean isMonitorWait(String methodName, String methodSig) { return methodName.equals("wait") && (methodSig.equals("()V") || methodSig.equals("(J)V") || methodSig.equals("(JI)V")); } /** * Determine if given Instruction is a monitor wait. * * @param ins the Instruction * @param cpg the ConstantPoolGen for the Instruction * * @return true if the instruction is a monitor wait, false if not */ public static boolean isMonitorWait(Instruction ins, ConstantPoolGen cpg) { if (!(ins instanceof InvokeInstruction)) return false; if (ins.getOpcode() == Constants.INVOKESTATIC) return false; InvokeInstruction inv = (InvokeInstruction) ins; String methodName = inv.getMethodName(cpg); String methodSig = inv.getSignature(cpg); return isMonitorWait(methodName, methodSig); } /** * Determine if method whose name and signature is specified * is a monitor notify operation. * * @param methodName name of the method * @param methodSig signature of the method * @return true if the method is a monitor notify, false if not */ public static boolean isMonitorNotify(String methodName, String methodSig) { return (methodName.equals("notify") || methodName.equals("notifyAll")) && methodSig.equals("()V"); } /** * Look up the method referenced by given InvokeInstruction. * This method does <em>not</em> look for implementations in * super or subclasses according to the virtual dispatch rules. * * @param inv the InvokeInstruction * @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to * @return the Method, or null if no such method is defined in the class */ public static Method findExactMethod(InvokeInstruction inv, ConstantPoolGen cpg) throws ClassNotFoundException { return findExactMethod(inv, cpg, ANY_METHOD); } /** * Look up the method referenced by given InvokeInstruction. * This method does <em>not</em> look for implementations in * super or subclasses according to the virtual dispatch rules. * * @param inv the InvokeInstruction * @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to * @param chooser MethodChooser to use to pick the method from among the candidates * @return the Method, or null if no such method is defined in the class */ public static Method findExactMethod( InvokeInstruction inv, ConstantPoolGen cpg, MethodChooser chooser) throws ClassNotFoundException { String className = inv.getClassName(cpg); String methodName = inv.getName(cpg); String methodSig = inv.getSignature(cpg); JavaClass jclass = Repository.lookupClass(className); return findMethod(jclass, methodName, methodSig, chooser); } /** * Get the method which serves as a "prototype" for the * given InvokeInstruction. The "prototype" is the method * which defines the contract for the invoked method, * in particular the declared list of exceptions that the * method can throw. * <p/> * <ul> * <li> For invokespecial, this is simply an * exact lookup. * <li> For invokestatic and invokevirtual, the named class is searched, * followed by superclasses up to the root of the object * hierarchy (java.lang.Object). Yes, invokestatic really is declared * to check superclasses. See VMSpec, 2nd ed, sec. 5.4.3.3. * <li> For invokeinterface, the named class is searched, * followed by all interfaces transitively declared by the class. * (Question: is the order important here? Maybe the VM spec * requires that the actual interface desired is given, * so the extended lookup will not be required. Should check.) * </ul> * * @param inv the InvokeInstruction * @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to * @return the Method, or null if no matching method can be found */ public static Method findPrototypeMethod(InvokeInstruction inv, ConstantPoolGen cpg) throws ClassNotFoundException { Method m = null; if (DEBUG_METHOD_LOOKUP) { System.out.println("Find prototype method for " + SignatureConverter.convertMethodSignature(inv,cpg)); } short opcode = inv.getOpcode(); // Find the method if (opcode == Constants.INVOKESPECIAL) { // Non-virtual dispatch m = findExactMethod(inv, cpg, INSTANCE_METHOD); } else { String className = inv.getClassName(cpg); String methodName = inv.getName(cpg); String methodSig = inv.getSignature(cpg); if (DEBUG_METHOD_LOOKUP) { System.out.println("[Class name is " + className + "]"); System.out.println("[Method name is " + methodName + "]"); System.out.println("[Method signature is " + methodSig + "]"); } if (opcode == Constants.INVOKEVIRTUAL || opcode == Constants.INVOKESTATIC) { if (DEBUG_METHOD_LOOKUP) { System.out.println("[invokevirtual or invokestatic]"); } // Dispatch where the class hierarchy is searched // Check superclasses MethodChooser methodChooser = (opcode == Constants.INVOKESTATIC) ? STATIC_METHOD : INSTANCE_METHOD; m = findMethod(Repository.lookupClass(className), methodName, methodSig, methodChooser); if (m == null) { if (DEBUG_METHOD_LOOKUP) { System.out.println("[not in class, checking superclasses...]"); } JavaClass[] superClassList = Repository.getSuperClasses(className); m = findMethod(superClassList, methodName, methodSig, methodChooser); } } else { // Check superinterfaces m = findMethod(Repository.lookupClass(className), methodName, methodSig, INSTANCE_METHOD); if (m == null) { JavaClass[] interfaceList = Repository.getInterfaces(className); m = findMethod(interfaceList, methodName, methodSig, INSTANCE_METHOD); } } } return m; } /** * Find the declared exceptions for the method called * by given instruction. * * @param inv the InvokeInstruction * @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to * @return array of ObjectTypes of thrown exceptions, or null * if we can't find the list of declared exceptions */ public static ObjectType[] findDeclaredExceptions(InvokeInstruction inv, ConstantPoolGen cpg) throws ClassNotFoundException { Method m = findPrototypeMethod(inv, cpg); if (m == null) return null; ExceptionTable exTable = m.getExceptionTable(); if (exTable == null) return new ObjectType[0]; String[] exNameList = exTable.getExceptionNames(); ObjectType[] result = new ObjectType[exNameList.length]; for (int i = 0; i < exNameList.length; ++i) { result[i] = new ObjectType(exNameList[i]); } return result; } /** * Find a method in given class. * * @param javaClass the class * @param methodName the name of the method * @param methodSig the signature of the method * @return the Method, or null if no such method exists in the class */ public static Method findMethod(JavaClass javaClass, String methodName, String methodSig) { return findMethod(javaClass, methodName, methodSig, ANY_METHOD); } /** * Find a method in given class. * * @param javaClass the class * @param methodName the name of the method * @param methodSig the signature of the method * @param chooser MethodChooser to use to select a matching method * (assuming class, name, and signature already match) * @return the Method, or null if no such method exists in the class */ public static Method findMethod( JavaClass javaClass, String methodName, String methodSig, MethodChooser chooser) { if (DEBUG_METHOD_LOOKUP) { System.out.println("XXX: Check " + javaClass.getClassName()); } Method[] methodList = javaClass.getMethods(); for (int i = 0; i < methodList.length; ++i) { Method method = methodList[i]; if (method.getName().equals(methodName) && method.getSignature().equals(methodSig) && chooser.choose(method)) { if (DEBUG_METHOD_LOOKUP) { System.out.println("\t==> FOUND: " + method); } return method; } } if (DEBUG_METHOD_LOOKUP) { System.out.println("\t==> NOT FOUND"); } return null; } /** * Find a method in given class. * * @param javaClass the class * @param methodName the name of the method * @param methodSig the signature of the method * @param chooser the MethodChooser to use to screen possible candidates * @return the XMethod, or null if no such method exists in the class */ public static XMethod findXMethod(JavaClass javaClass, String methodName, String methodSig, MethodChooser chooser) { Method m = findMethod(javaClass, methodName, methodSig, chooser); return m == null ? null : XMethodFactory.createXMethod(javaClass, m); } /** * MethodChooser which accepts any method. */ public static final MethodChooser ANY_METHOD = new MethodChooser() { public boolean choose(Method method) { return true; } }; /** * MethodChooser which accepts only concrete (not abstract or native) methods. * FIXME: perhaps native methods should be concrete. */ public static final MethodChooser CONCRETE_METHOD = new MethodChooser() { public boolean choose(Method method) { int accessFlags = method.getAccessFlags(); return (accessFlags & Constants.ACC_ABSTRACT) == 0 && (accessFlags & Constants.ACC_NATIVE) == 0; } }; /** * MethodChooser which accepts only static methods. */ public static final MethodChooser STATIC_METHOD = new MethodChooser() { public boolean choose(Method method) { return method.isStatic(); } }; /** * MethodChooser which accepts only instance methods. */ public static final MethodChooser INSTANCE_METHOD = new MethodChooser() { public boolean choose(Method method) { return !method.isStatic(); } }; /** * Find a method in given list of classes, * searching the classes in order. * * @param classList list of classes in which to search * @param methodName the name of the method * @param methodSig the signature of the method * @return the Method, or null if no such method exists in the class */ public static Method findMethod(JavaClass[] classList, String methodName, String methodSig) { return findMethod(classList, methodName, methodSig, ANY_METHOD); } /** * Find a method in given list of classes, * searching the classes in order. * * @param classList list of classes in which to search * @param methodName the name of the method * @param methodSig the signature of the method * @param chooser MethodChooser to select which methods are considered; * it must return true for a method to be returned * @return the Method, or null if no such method exists in the class */ public static Method findMethod(JavaClass[] classList, String methodName, String methodSig, MethodChooser chooser) { Method m = null; for (int i = 0; i < classList.length; ++i) { JavaClass cls = classList[i]; if ((m = findMethod(cls, methodName, methodSig, chooser)) != null) break; } return m; } /** * Find XMethod for method in given list of classes, * searching the classes in order. * * @param classList list of classes in which to search * @param methodName the name of the method * @param methodSig the signature of the method * @return the XMethod, or null if no such method exists in the class */ public static XMethod findXMethod(JavaClass[] classList, String methodName, String methodSig) { return findXMethod(classList, methodName, methodSig, ANY_METHOD); } /** * Find XMethod for method in given list of classes, * searching the classes in order. * * @param classList list of classes in which to search * @param methodName the name of the method * @param methodSig the signature of the method * @param chooser MethodChooser to select which methods are considered; * it must return true for a method to be returned * @return the XMethod, or null if no such method exists in the class */ public static XMethod findXMethod(JavaClass[] classList, String methodName, String methodSig, MethodChooser chooser) { for (int i = 0; i < classList.length; ++i) { JavaClass cls = classList[i]; Method m; if ((m = findMethod(cls, methodName, methodSig)) != null && chooser.choose(m)) { return XMethodFactory.createXMethod(cls, m); } } return null; } /** * Resolve possible method call targets. * This works for both static and instance method calls. * * @param invokeInstruction the InvokeInstruction * @param typeFrame the TypeFrame containing the types of stack values * @param cpg the ConstantPoolGen * @throws DataflowAnalysisException * @throws ClassNotFoundException */ public static Set<XMethod> resolveMethodCallTargets( InvokeInstruction invokeInstruction, TypeFrame typeFrame, ConstantPoolGen cpg) throws DataflowAnalysisException, ClassNotFoundException { if (invokeInstruction.getOpcode() == Constants.INVOKESTATIC) { HashSet<XMethod> result = new HashSet<XMethod>(); Method targetMethod = findPrototypeMethod(invokeInstruction, cpg); if (targetMethod != null) { JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass( invokeInstruction.getClassName(cpg)); result.add(XMethodFactory.createXMethod(targetClass, targetMethod)); } return result; } if (!typeFrame.isValid()) { return new HashSet<XMethod>(); } int instanceSlot = typeFrame.getInstanceSlot(invokeInstruction, cpg); Type receiverType = typeFrame.getValue(instanceSlot); if (!(receiverType instanceof ReferenceType)) { return new HashSet<XMethod>(); } boolean receiverTypeIsExact = typeFrame.isExact(instanceSlot); if (DEBUG_METHOD_LOOKUP) { System.out.println("[receiver type is " + receiverType + ", " + (receiverTypeIsExact ? "exact]" : " not exact]")); } return resolveMethodCallTargets((ReferenceType) receiverType, invokeInstruction, cpg, receiverTypeIsExact); } /** * Resolve possible instance method call targets. * Assumes that invokevirtual and invokeinterface methods may * call any subtype of the receiver class. * * @param receiverType type of the receiver object * @param invokeInstruction the InvokeInstruction * @param cpg the ConstantPoolGen * @return Set of methods which might be called * @throws ClassNotFoundException */ public static Set<XMethod> resolveMethodCallTargets( ReferenceType receiverType, InvokeInstruction invokeInstruction, ConstantPoolGen cpg ) throws ClassNotFoundException { return resolveMethodCallTargets(receiverType, invokeInstruction, cpg, false); } /** * Resolve possible instance method call targets. * * @param receiverType type of the receiver object * @param invokeInstruction the InvokeInstruction * @param cpg the ConstantPoolGen * @param receiverTypeIsExact if true, the receiver type is known exactly, * which should allow a precise result * @return Set of methods which might be called * @throws ClassNotFoundException */ public static Set<XMethod> resolveMethodCallTargets( ReferenceType receiverType, InvokeInstruction invokeInstruction, ConstantPoolGen cpg, boolean receiverTypeIsExact ) throws ClassNotFoundException { HashSet<XMethod> result = new HashSet<XMethod>(); if (invokeInstruction.getOpcode() == Constants.INVOKESTATIC) throw new IllegalArgumentException(); String className = invokeInstruction.getClassName(cpg); String methodName = invokeInstruction.getName(cpg); String methodSig = invokeInstruction.getSignature(cpg); // Array method calls aren't virtual. // They should just resolve to Object methods. if (receiverType instanceof ArrayType) { result.add(new InstanceMethod( className, methodName, methodSig, Constants.ACC_PUBLIC )); return result; } AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext(); // Get the receiver class. JavaClass receiverClass = analysisContext.lookupClass( ((ObjectType) receiverType).getClassName()); // Figure out the upper bound for the method. // This is what will be called if this is not a virtual call site. XMethod upperBound = findXMethod(receiverClass, methodName, methodSig, CONCRETE_METHOD); if (upperBound == null || !isConcrete(upperBound)) { // Try superclasses JavaClass[] superClassList = receiverClass.getSuperClasses(); upperBound = findXMethod(superClassList, methodName, methodSig, CONCRETE_METHOD); } if (upperBound != null) { if (DEBUG_METHOD_LOOKUP) { System.out.println("Adding upper bound: " + SignatureConverter.convertMethodSignature(upperBound)); } result.add(upperBound); } // Is this a virtual call site? boolean virtualCall = invokeInstruction.getOpcode() != Constants.INVOKESPECIAL && !receiverTypeIsExact; if (virtualCall) { // This is a true virtual call: assume that any concrete // subtype method may be called. Set<JavaClass> subTypeSet = analysisContext.getSubtypes().getTransitiveSubtypes(receiverClass); for (JavaClass subtype : subTypeSet) { XMethod concreteSubtypeMethod = findXMethod(subtype, methodName, methodSig, CONCRETE_METHOD); if (concreteSubtypeMethod != null) { result.add(concreteSubtypeMethod); } } } return result; } /** * Return whether or not the given method is concrete. * * @param xmethod the method * @return true if the method is concrete, false otherwise */ public static boolean isConcrete(XMethod xmethod) { int accessFlags = xmethod.getAccessFlags(); return (accessFlags & Constants.ACC_ABSTRACT) == 0 && (accessFlags & Constants.ACC_NATIVE) == 0; } /** * Find a field with given name defined in given class. * * @param className the name of the class * @param fieldName the name of the field * @return the Field, or null if no such field could be found */ public static Field findField(String className, String fieldName) throws ClassNotFoundException { JavaClass jclass = Repository.lookupClass(className); while (jclass != null) { Field[] fieldList = jclass.getFields(); for (int i = 0; i < fieldList.length; ++i) { Field field = fieldList[i]; if (field.getName().equals(fieldName)) { return field; } } jclass = jclass.getSuperClass(); } return null; } /* public static JavaClass findClassDefiningField(String className, String fieldName, String fieldSig) throws ClassNotFoundException { JavaClass jclass = Repository.lookupClass(className); while (jclass != null) { Field[] fieldList = jclass.getFields(); for (int i = 0; i < fieldList.length; ++i) { Field field = fieldList[i]; if (field.getName().equals(fieldName) && field.getSignature().equals(fieldSig)) { return jclass; } } jclass = jclass.getSuperClass(); } return null; } */ /** * Look up a field with given name and signature in given class, * returning it as an {@link XField XField} object. * If a field can't be found in the immediate class, * its superclass is search, and so forth. * * @param className name of the class through which the field * is referenced * @param fieldName name of the field * @param fieldSig signature of the field * @return an XField object representing the field, or null if no such field could be found */ public static XField findXField(String className, String fieldName, String fieldSig) throws ClassNotFoundException { JavaClass classDefiningField = Repository.lookupClass(className); Field field = null; loop: while (classDefiningField != null) { Field[] fieldList = classDefiningField.getFields(); for (int i = 0; i < fieldList.length; ++i) { field = fieldList[i]; if (field.getName().equals(fieldName) && field.getSignature().equals(fieldSig)) { break loop; } } classDefiningField = classDefiningField.getSuperClass(); } if (classDefiningField == null) return null; else { String realClassName = classDefiningField.getClassName(); int accessFlags = field.getAccessFlags(); return field.isStatic() ? (XField) new StaticField(realClassName, fieldName, fieldSig, accessFlags) : (XField) new InstanceField(realClassName, fieldName, fieldSig, accessFlags); } } /** * Look up the field referenced by given FieldInstruction, * returning it as an {@link XField XField} object. * * @param fins the FieldInstruction * @param cpg the ConstantPoolGen used by the class containing the instruction * @return an XField object representing the field, or null * if no such field could be found */ public static XField findXField(FieldInstruction fins, ConstantPoolGen cpg) throws ClassNotFoundException { String className = fins.getClassName(cpg); String fieldName = fins.getFieldName(cpg); String fieldSig = fins.getSignature(cpg); XField xfield = findXField(className, fieldName, fieldSig); short opcode = fins.getOpcode(); if (xfield != null && xfield.isStatic() == (opcode == Constants.GETSTATIC || opcode == Constants.PUTSTATIC)) return xfield; else return null; } /** * Determine whether the given INVOKESTATIC instruction * is an inner-class field accessor method. * @param inv the INVOKESTATIC instruction * @param cpg the ConstantPoolGen for the method * @return true if the instruction is an inner-class field accessor, false if not */ public static boolean isInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg) { String methodName = inv.getName(cpg); return methodName.startsWith("access$"); } /** * Get the InnerClassAccess for access method called * by given INVOKESTATIC. * @param inv the INVOKESTATIC instruction * @param cpg the ConstantPoolGen for the method * @return the InnerClassAccess, or null if the instruction is not * an inner-class access */ public static InnerClassAccess getInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg) throws ClassNotFoundException { String className = inv.getClassName(cpg); String methodName = inv.getName(cpg); String methodSig = inv.getSignature(cpg); InnerClassAccess access = InnerClassAccessMap.instance().getInnerClassAccess(className, methodName); return (access != null && access.getMethodSignature().equals(methodSig)) ? access : null; } } // vim:ts=4
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonNode; import org.junit.*; import play.mvc.*; import play.test.*; import play.data.DynamicForm; import play.data.validation.ValidationError; import play.data.validation.Constraints.RequiredValidator; import play.i18n.Lang; import play.libs.F; import play.libs.F.*; import static play.test.Helpers.*; import static org.fest.assertions.Assertions.*; /** * * Simple (JUnit) tests that can call all parts of a play app. * If you are interested in mocking a whole application, see the wiki for more details. * */ public class ApplicationTest { @Test public void simpleCheck() { int a = 1 + 1; assertThat(a).isEqualTo(2); } @Test public void renderTemplate() { Content html = views.html.index.render("Your new application is ready."); assertThat(contentType(html)).isEqualTo("text/html"); assertThat(contentAsString(html)).contains("Your new application is ready."); } }
package util; import static org.openqa.selenium.support.ui.ExpectedConditions.not; import com.gargoylesoftware.htmlunit.SilentCssErrorHandler; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; /** * @author fhaertig * @since 22.01.16 */ public class WebDriverPaypal extends HtmlUnitDriver { private static final Logger LOG = LoggerFactory.getLogger(WebDriverPaypal.class); private static final int DEFAULT_TIMEOUT = 10; public WebDriverPaypal() { this.manage().timeouts().implicitlyWait(DEFAULT_TIMEOUT, TimeUnit.SECONDS); this.manage().timeouts().pageLoadTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); this.manage().timeouts().setScriptTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); getWebClient().setCssErrorHandler(new SilentCssErrorHandler()); } private void doLogin(final String email, final String password) { WebElement loginEmailInput = this.findElement(By.id("login_email")); WebElement loginPwInput = this.findElement(By.id("login_password")); loginEmailInput.sendKeys(email); loginPwInput.sendKeys(password); WebElement submitButton = this.findElement(By.id("submitLogin")); submitButton.click(); } public String executePaypalPayment(final String url, final String email, final String password) { this.navigate().to(url); doLogin(email, password); final Wait<WebDriver> wait = new WebDriverWait(this, 10); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("continue"))); WebElement payButton = this.findElement(By.id("continue")); payButton.click(); wait.until(not(ExpectedConditions.urlContains("paypal"))); return this.getCurrentUrl(); } }
import java.io.FileNotFoundException; public class TesterCommandline { public static void main(String args[]) throws FileNotFoundException { String[] someArgs = {"-a", "hamlet.txt"}; //test if a proper error message is printed WordCount.main(someArgs); } }
package com.k3nx.speakeasy; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Speaker[] speakers = {new Human(), new Dog(), new Cat()}; saySomething(speakers); } private void saySomething(Speaker[] speakers) { for(Speaker speaker: speakers) { Log.d(TAG, speaker.speak()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package teammemes.tritonbudget; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Date; import teammemes.tritonbudget.Menus.Menu; import teammemes.tritonbudget.db.HistoryDataSource; import teammemes.tritonbudget.db.MenuDataSource; import teammemes.tritonbudget.db.TranHistory; public class Checkout extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { LinearLayout mainLayout; Toolbar mToolbar; ActionBarDrawerToggle mToggle; double total = 0; private DrawerLayout mDrawerLayout; private ArrayList<TranHistory> trans; private float dX; private float dY; private int lastAction; @Override protected void onCreate(Bundle savedInstanceState) { User usr = User.getInstance(this); super.onCreate(savedInstanceState); setContentView(R.layout.drawer_checkout); //Creates the toolbar to the one defined in nav_action mToolbar = (Toolbar) findViewById(R.id.nav_action); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Checkout"); //Create the Drawer layout and the toggle mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_checkout_layout); mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close); mDrawerLayout.addDrawerListener(mToggle); mToggle.syncState(); //Create the navigationView and add a listener to listen for menu selections NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); //Get the navigation drawer header and set's the name to user's name View navHeaderView = navigationView.getHeaderView(0); TextView usrName = (TextView) navHeaderView.findViewById(R.id.header_name); usrName.setText(usr.getName()); //Fetches the main empty layout mainLayout = (LinearLayout) findViewById(R.id.page); //Uses custom adapter to populate list view populateCOList(); TextView display_total = (TextView)findViewById(R.id.total_cost); display_total.setText("Total:\t\t\t$" + double_to_string(total)); FloatingActionButton button = (FloatingActionButton) findViewById(R.id.ConfirmPurchaseBtn); button.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: dX = view.getX() - event.getRawX(); dY = view.getY() - event.getRawY(); lastAction = MotionEvent.ACTION_DOWN; break; case MotionEvent.ACTION_MOVE: view.setY(event.getRawY() + dY); view.setX(event.getRawX() + dX); lastAction = MotionEvent.ACTION_MOVE; break; case MotionEvent.ACTION_UP: if (change_balance(total)) { Intent intent = new Intent(getApplicationContext(), HomeScreen.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Purchased!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "You broke though.", Toast.LENGTH_LONG).show(); } break; default: return false; } return true; } }); } private void populateCOList() { LinearLayout ll = (LinearLayout) findViewById(R.id.Checkout); ll.setBackgroundResource(R.drawable.border_set_top_bottom); Intent it = getIntent(); ArrayList<String> transtring = it.getStringArrayListExtra("Transactions"); trans = new ArrayList<>(); ArrayList<String> num = it.getStringArrayListExtra("number"); MenuDataSource data = new MenuDataSource(getApplicationContext()); for (int i = 0; i < transtring.size(); i++) { Menu men = data.getMenuById(Integer.parseInt(transtring.get(i))); trans.add(new TranHistory(men.getId(), men.getName(), Integer.parseInt(num.get(i)), new Date(), men.getCost())); String cost = "$" + double_to_string(trans.get(i).getCost()); String quantity = "x" + Integer.toString(trans.get(i).getQuantity()); total += (trans.get(i).getCost() * trans.get(i).getQuantity()); LinearLayout borderll = makeLL(); LinearLayout quantityll = makeLL(); quantityll.setBackgroundResource(0); quantityll.setGravity(Gravity.RIGHT); TextView item = new TextView(this); item.setPadding(8, 8, 8, 8); item.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); item.setTextSize(20); String itemName = trans.get(i).getName(); item.setText(itemName); TextView t = makeTV(cost, quantity); t.setPadding(8,8,8,8); ll.addView(borderll); borderll.addView(item); borderll.addView(quantityll); quantityll.addView(t); } } private LinearLayout makeLL() { LinearLayout nestedll = new LinearLayout(this); nestedll.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); nestedll.setOrientation(LinearLayout.HORIZONTAL); nestedll.setBackgroundResource(R.drawable.border_set_top_bottom); return nestedll; } private TextView makeTV(String cost, String quantity) { TextView tv = new TextView(this); tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv.setText(cost + " " + quantity); tv.setTextSize(20); return tv; } // add button then call this in listener private boolean change_balance(double bal) { User usr = User.getInstance(getApplicationContext()); if (usr.getBalance() < bal) { return false; } usr.setBalance(usr.getBalance() - bal); HistoryDataSource data = new HistoryDataSource(getApplicationContext()); for (int i = 0; i < trans.size(); i++) { data.createTransaction(trans.get(i)); } return true; } private String double_to_string(double number) { //Gets the balance from the user String str = "" + number; int decimalIdx = str.indexOf('.'); //Edge case, where balance == $XXX.00, it wrongly displays one instance of 0. This fixes it. if (decimalIdx + 1 == str.length() - 1) { str = str + "0"; } return str; } @Override public boolean onNavigationItemSelected(MenuItem item) { // Gets the id of the item that was selected int id = item.getItemId(); Intent nextScreen; //Reacts to the item selected depending on which was pressed //Creates a new Intent for the new page and starts that activity switch (id) { case R.id.nav_home: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, HomeScreen.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_history: mDrawerLayout.closeDrawer(GravityCompat.START); return false; case R.id.nav_statistics: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Statistics.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_menus: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, DiningHallSelection.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_settings: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Settings.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; case R.id.nav_help: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Help.class); nextScreen.putExtra("FROM", "Checkout"); startActivity(nextScreen); return true; default: mDrawerLayout.closeDrawer(GravityCompat.START); return false; } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } }
package com.mapswithme.maps; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.webkit.WebView; import android.widget.LinearLayout; import com.mapswithme.maps.location.LocationService; import com.nvidia.devtech.NvEventQueueActivity; public class MWMActivity extends NvEventQueueActivity implements LocationService.Listener { //VideoTimer m_timer; private static String TAG = "MWMActivity"; private MWMApplication mApplication = null; private BroadcastReceiver m_externalStorageReceiver = null; private AlertDialog m_storageDisconnectedDialog = null; private boolean m_shouldStartLocationService = false; private LocationService getLocationService() { return mApplication.getLocationService(); } private MapStorage getMapStorage() { return mApplication.getMapStorage(); } public void checkShouldStartLocationService() { if (m_shouldStartLocationService) { getLocationService().startUpdate(this); m_shouldStartLocationService = false; } } public void OnDownloadCountryClicked() { runOnUiThread(new Runnable() { @Override public void run() { nativeDownloadCountry(); } }); } @Override public void OnRenderingInitialized() { runOnUiThread(new Runnable() { @Override public void run() { // Run all checks in main thread after rendering is initialized. checkShouldStartLocationService(); checkMeasurementSystem(); checkProVersionAvailable(); checkUpdateMaps(); } }); } private Activity getActivity() { return this; } @Override public void ReportUnsupported() { runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setMessage(getString(R.string.unsupported_phone)) .setCancelable(false) .setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { getActivity().moveTaskToBack(true); dlg.dismiss(); } }) .create() .show(); } }); } private void setMeasurementSystem(int u) { nativeSetMS(u); } private void checkMeasurementSystem() { final int u = nativeGetMS(); if (u == UNITS_UNDEFINED) { // Checking system-default measurement system if (UnitLocale.getCurrent() == UnitLocale.Metric) { setMeasurementSystem(UNITS_METRIC); } else { // showing "select measurement system" dialog. new AlertDialog.Builder(this) .setCancelable(false) .setMessage(getString(R.string.which_measurement_system)) .setNegativeButton(getString(R.string.miles), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); setMeasurementSystem(UNITS_FOOT); } }) .setPositiveButton(getString(R.string.kilometres), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); setMeasurementSystem(UNITS_METRIC); } }) .create() .show(); } } else { setMeasurementSystem(u); } } /// This constants should be equal with Settings::Units in settings.hpp private final int UNITS_UNDEFINED = -1; private final int UNITS_METRIC = 0; private final int UNITS_YARD = 1; private final int UNITS_FOOT = 2; private native int nativeGetMS(); private native void nativeSetMS(int u); private native void nativeScale(double k); private static final String PREFERENCES_MYPOSITION = "isMyPositionEnabled"; public void onPlusClicked(View v) { nativeScale(3.0 / 2); } public void onMinusClicked(View v) { nativeScale(2.0 / 3); } public void onMyPositionClicked(View v) { v.setBackgroundResource(R.drawable.myposition_button_normal); final boolean isLocationActive = v.isSelected(); if (isLocationActive) getLocationService().stopUpdate(this); else getLocationService().startUpdate(this); v.setSelected(!isLocationActive); // Store active state of My Position SharedPreferences.Editor prefsEdit = getSharedPreferences(mApplication.getPackageName(), MODE_PRIVATE).edit(); prefsEdit.putBoolean(PREFERENCES_MYPOSITION, !isLocationActive); prefsEdit.commit(); } private void checkProVersionAvailable() { if (mApplication.isProVersion() || (nativeGetProVersionURL().length() != 0)) { findViewById(R.id.map_button_search).setVisibility(View.VISIBLE); } else nativeCheckForProVersion(mApplication.getProVersionCheckURL()); } private boolean m_needCheckUpdate = true; private void checkUpdateMaps() { // do it only once if (m_needCheckUpdate) { m_needCheckUpdate = false; getMapStorage().updateMaps(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor() { @Override public void doUpdate() { runDownloadActivity(); } @Override public void doCancel() { } }); } } /// Invoked from native code - asynchronous server check. public void onProVersionAvailable() { findViewById(R.id.map_button_search).setVisibility(View.VISIBLE); showProVersionBanner(getString(R.string.pro_version_available)); } private void showProVersionBanner(String message) { new AlertDialog.Builder(getActivity()) .setMessage(message) .setCancelable(false) .setPositiveButton(getString(R.string.get_it_now), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(nativeGetProVersionURL())); dlg.dismiss(); startActivity(i); } }) .setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }) .create() .show(); } private void runSearchActivity() { startActivity(new Intent(this, SearchActivity.class)); } public void onSearchClicked(View v) { if (!mApplication.isProVersion()) { showProVersionBanner(getString(R.string.search_available_in_pro_version)); } else { if (!getMapStorage().updateMaps(R.string.search_update_maps, this, new MapStorage.UpdateFunctor() { @Override public void doUpdate() { runDownloadActivity(); } @Override public void doCancel() { runSearchActivity(); } })) { runSearchActivity(); } } } @Override public boolean onSearchRequested() { onSearchClicked(null); return false; } private void runDownloadActivity() { startActivity(new Intent(this, DownloadUI.class)); } public void onDownloadClicked(View v) { runDownloadActivity(); } @Override public void onCreate(Bundle savedInstanceState) { // Use full-screen on Kindle Fire only if (android.os.Build.MODEL.equals("Kindle Fire")) { getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } super.onCreate(savedInstanceState); mApplication = (MWMApplication)getApplication(); nativeSetString("country_status_added_to_queue", getString(R.string.country_status_added_to_queue)); nativeSetString("country_status_downloading", getString(R.string.country_status_downloading)); nativeSetString("country_status_download", getString(R.string.country_status_download)); nativeSetString("country_status_download_failed", getString(R.string.country_status_download_failed)); nativeSetString("try_again", getString(R.string.try_again)); nativeSetString("not_enough_free_space_on_sdcard", getString(R.string.not_enough_free_space_on_sdcard)); nativeConnectDownloadButton(); // Get screen density and do layout for +/- buttons DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); final double k = metrics.density; final int offs = (int)(53 * k); // height of button + half space between buttons. final int margin = (int)(5 * k); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(margin, (metrics.heightPixels / 4) - offs, margin, margin); findViewById(R.id.map_button_plus).setLayoutParams(lp); //m_timer = new VideoTimer(); } /// @name From Location interface @Override public void onLocationStatusChanged(int newStatus) { if (newStatus == LocationService.FIRST_EVENT) findViewById(R.id.map_button_myposition).setBackgroundResource(R.drawable.myposition_button_found); nativeLocationStatusChanged(newStatus); } @Override public void onLocationUpdated(long time, double lat, double lon, float accuracy) { nativeLocationUpdated(time, lat, lon, accuracy); } @Override public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { final int orientation = getWindowManager().getDefaultDisplay().getOrientation(); final double correction = LocationService.getAngleCorrection(orientation); magneticNorth = LocationService.correctAngle(magneticNorth, correction); trueNorth = LocationService.correctAngle(trueNorth, correction); nativeCompassUpdated(time, magneticNorth, trueNorth, accuracy); } @Override protected void onStart() { super.onStart(); // Restore My Position state on startup/activity recreation SharedPreferences prefs = getSharedPreferences(mApplication.getPackageName(), MODE_PRIVATE); final boolean isMyPositionEnabled = prefs.getBoolean(PREFERENCES_MYPOSITION, false); findViewById(R.id.map_button_myposition).setSelected(isMyPositionEnabled); } @Override protected void onPause() { if (mApplication.nativeIsBenchmarking()) mApplication.enableAutomaticStandby(); getLocationService().stopUpdate(this); stopWatchingExternalStorage(); super.onPause(); } @Override protected void onResume() { if (mApplication.nativeIsBenchmarking()) mApplication.disableAutomaticStandby(); View button = findViewById(R.id.map_button_myposition); if (button.isSelected()) { // Change button appearance to "looking for position" button.setBackgroundResource(R.drawable.myposition_button_normal); // and remember to start locationService updates in OnRenderingInitialized m_shouldStartLocationService = true; } startWatchingExternalStorage(); super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menuitem_about_dialog) { onAboutDialogClicked(); return true; } else { return super.onOptionsItemSelected(item); } } private void onAboutDialogClicked() { LayoutInflater inflater = LayoutInflater.from(this); View alertDialogView = inflater.inflate(R.layout.about, null); WebView myWebView = (WebView) alertDialogView.findViewById(R.id.webview_about); myWebView.loadUrl("file:///android_asset/about.html"); new AlertDialog.Builder(this) .setView(alertDialogView) .setTitle(R.string.about) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); } // Initialized to invalid combination to force update on the first check private boolean m_storageAvailable = false; private boolean m_storageWriteable = true; private void updateExternalStorageState() { boolean available, writeable; final String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { available = writeable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { available = true; writeable = false; } else available = writeable = false; if (m_storageAvailable != available || m_storageWriteable != writeable) { m_storageAvailable = available; m_storageWriteable = writeable; handleExternalStorageState(available, writeable); } } private void handleExternalStorageState(boolean available, boolean writeable) { if (available && writeable) { // Add local maps to the model nativeStorageConnected(); // enable downloader button and dismiss blocking popup findViewById(R.id.map_button_download).setVisibility(View.VISIBLE); if (m_storageDisconnectedDialog != null) m_storageDisconnectedDialog.dismiss(); } else if (available) { // Add local maps to the model nativeStorageConnected(); // disable downloader button and dismiss blocking popup findViewById(R.id.map_button_download).setVisibility(View.INVISIBLE); if (m_storageDisconnectedDialog != null) m_storageDisconnectedDialog.dismiss(); } else { // Remove local maps from the model nativeStorageDisconnected(); // enable downloader button and show blocking popup findViewById(R.id.map_button_download).setVisibility(View.VISIBLE); if (m_storageDisconnectedDialog == null) { m_storageDisconnectedDialog = new AlertDialog.Builder(this) .setTitle(R.string.external_storage_is_not_available) .setMessage(getString(R.string.disconnect_usb_cable)) .setCancelable(false) .create(); } m_storageDisconnectedDialog.show(); } } private void startWatchingExternalStorage() { m_externalStorageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateExternalStorageState(); } }; IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_REMOVED); filter.addAction(Intent.ACTION_MEDIA_EJECT); filter.addAction(Intent.ACTION_MEDIA_SHARED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE); filter.addAction(Intent.ACTION_MEDIA_CHECKING); filter.addAction(Intent.ACTION_MEDIA_NOFS); filter.addDataScheme("file"); registerReceiver(m_externalStorageReceiver, filter); updateExternalStorageState(); } private void stopWatchingExternalStorage() { if (m_externalStorageReceiver != null) { unregisterReceiver(m_externalStorageReceiver); m_externalStorageReceiver = null; } } private native void nativeSetString(String name, String value); private native void nativeStorageConnected(); private native void nativeStorageDisconnected(); private native void nativeConnectDownloadButton(); private native void nativeDownloadCountry(); private native void nativeDestroy(); private native void nativeLocationStatusChanged(int newStatus); private native void nativeLocationUpdated(long time, double lat, double lon, float accuracy); private native void nativeCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy); private native String nativeGetProVersionURL(); private native void nativeCheckForProVersion(String serverURL); }
package com.twosheds.pi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.view.View; public class GraphView extends View { private Paint paintBackground; private Paint paintSquare; private Paint paintCircle; private Paint paintPointInside; private Paint paintPointOutside; private float radius; private Point center; private Bitmap bitmap; private Canvas canvas; public GraphView(Context context, AttributeSet attrs) { super(context, attrs); // TODO: move to style paintBackground = new Paint(); paintBackground.setColor(Color.BLACK); paintBackground.setStyle(Paint.Style.FILL); paintSquare = new Paint(); paintSquare.setColor(Color.BLUE); paintSquare.setStrokeWidth(3.0f); paintSquare.setStyle(Paint.Style.STROKE); paintCircle = new Paint(); paintCircle.setColor(Color.RED); paintCircle.setStrokeWidth(3.0f); paintCircle.setStyle(Paint.Style.STROKE); paintPointInside = new Paint(); paintPointInside.setColor(Color.RED); paintPointInside.setStyle(Paint.Style.FILL_AND_STROKE); paintPointOutside = new Paint(); paintPointOutside.setColor(Color.BLUE); paintPointOutside.setStyle(Paint.Style.FILL_AND_STROKE); } @Override public void onSizeChanged(int w, int h, int oldW, int oldH) { radius = Math.min(w, h)/2; center = new Point(w/2, h/2); // TODO: handle existing bitmap bitmap = Bitmap.createBitmap((int)radius*2, (int)radius*2, Bitmap.Config.RGB_565); canvas = new Canvas(bitmap); resetCanvas(); } @Override public void onDraw(Canvas canvas) { canvas.drawBitmap(bitmap, center.x - radius, center.y - radius, null); } void drawPoint(double x, double y, boolean isInside) { int drawX = (int) (radius * x + radius); int drawY = (int) (radius * y + radius); canvas.drawCircle(drawX, drawY, 2, isInside ? paintPointInside : paintPointOutside); postInvalidate(); } void clearPoints() { resetCanvas(); } private void resetCanvas() { canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paintBackground); canvas.drawRect(0, 0, radius*2, radius*2, paintSquare); canvas.drawCircle(radius, radius, radius, paintCircle); } }
package hello; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { static final Logger LOG = LoggerFactory.getLogger(WebSecurityConfig.class); @Override protected void configure(HttpSecurity http) throws Exception{
import com.codeminders.hidapi.HIDDevice; import com.codeminders.hidapi.HIDDeviceInfo; import com.codeminders.hidapi.HIDManager; import java.io.IOException; public class Main { public static HIDDevice slave = null; public static HIDDevice master = null; static final char start_msg = 'S'; static final char reset_msg = 'R'; static final char pause_msg = 'P'; //mora da postoji hidapi-jni.dll na putanji za nativne //biblioteke za hidapi-1.1.jar //desni klik na projekat -> properties -> //-> java build path -> libraries -> hidapi-1.1 -> //-> native libraries //na materijalima postoje hidapi-jni-32 i hidapi-jni-64 //iskoristiti odgovarajuci prema arhitekturi static { System.loadLibrary("hidapi-jni"); } private static final int BUF_SIZE = 64; public static void main(String[] args) throws IOException { HIDManager hidMgr = HIDManager.getInstance(); try { while (true) { for (HIDDeviceInfo info : hidMgr.listDevices()) { if (info.getProduct_string().compareTo("SLAVEID Library") == 0) { slave = info.open(); break; } if (info.getProduct_string().compareTo("HOST ID Library") == 0) { master = info.open(); break; } } if (slave != null && master != null) { break; } } while (true) { String slaveMsg = readSlave(); if (slaveMsg != null) { processSlaveMessage(slaveMsg); } else { String masterMsg = readMaster(); } Thread.sleep(20); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { if (slave != null) { slave.close(); } if (master != null) { master.close(); } hidMgr.release(); } } private static void processSlaveMessage(String slaveMsg) { char msg = slaveMsg.charAt(0); sendToMaster(msg); } private static void sendToMaster(char msg) { String possibleMasterMsg = readMaster(); writeToMaster(msg); } public static String readSlave() { String slaveMsg = readHID("slave"); if (slaveMsg != null) { System.out.println("RECEIVED FROM SLAVE: " + slaveMsg); } return slaveMsg; } public static String readMaster() { String masterMsg = readHID("master"); if (masterMsg != null) { System.out.println("RECEIVED FROM MASTER: " + masterMsg); } return masterMsg; } public static String readHID(String type) { try { byte[] data = new byte[64]; int read = 0; switch (type) { case "slave": slave.disableBlocking(); read = slave.read(data); break; case "master": master.disableBlocking(); read = master.read(data); break; } if (read > 0) { String str = ""; for (int i = 0; i < read; i++) { if (data[i] != 0) { str += data[i]; } } return str; } else { return null; } } catch (IOException ioe) { ioe.printStackTrace(); } return null; } public static void writeToMaster(char value) { byte[] data = new byte[64]; data[0] = (byte) 1; data[1] = (byte) value; try { System.out.println("SENT TO MASTER: " + master.write(data)); } catch (Exception e) { e.printStackTrace(); } } }
package com.health.visuals; import java.util.ArrayList; import java.util.HashMap; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import com.health.Chunk; import com.health.Column; import com.health.Record; import com.health.Table; import com.health.input.Input; import com.health.input.InputException; import com.xeiam.xchart.Chart; import com.xeiam.xchart.ChartBuilder; import com.xeiam.xchart.StyleManager.ChartType; import com.xeiam.xchart.StyleManager.LegendPosition; import com.xeiam.xchart.SwingWrapper; public class FreqBarDef{ public static void main(String[] args){ String filePath = "/home/bjorn/Documents/Context/Health/health/data/data_use/txtData.txt"; String configPath = "/home/bjorn/Documents/Context/Health/health/data/configXmls/admireTxtConfig.xml"; try { Table table = Input.readTable(filePath, configPath); frequencyBar(table, "date"); } catch (IOException | ParserConfigurationException | SAXException | InputException e) { System.out.println("Error FreqBar"); } } /** * Generates a Frequency Bar diagram. * @param table Table to use * @param column Column to display frequency of */ public static void frequencyBar(Table table, String column) { //Get the Column to calculate frequency of Column selectedColumn = table.getColumn(column); int columnIndex = selectedColumn.getIndex(); String columnName = selectedColumn.getName(); //Create map to save frequencies Map<String, Integer> freqMap = new HashMap<String, Integer>(); for(Chunk c : table) { for(Record r : c) { //Get value of record String value = r.getValue(columnName).toString(); if(!freqMap.containsKey(value)) { freqMap.put(value, 1); } else { int currentFrequency = freqMap.get(value); freqMap.replace(value, ++currentFrequency); } } } } public static void makeBarChart(HashMap<String, Integer> arIn){ // Convert input data for processing ArrayList<String> labels = new ArrayList<String>(arIn.keySet()); ArrayList<Integer> frequency = new ArrayList<Integer>(arIn.values()); // Create Chart Chart chart = new ChartBuilder().chartType(ChartType.Bar).width(800).height(600).title("Score Histogram").xAxisTitle("Event").yAxisTitle("Frequency").build(); chart.addSeries("Test 1", new ArrayList<String>(labels), new ArrayList<Integer>(frequency)); // Customize Chart chart.getStyleManager().setLegendPosition(LegendPosition.InsideNW); new SwingWrapper(chart).displayChart(); } }
package uk.ac.ox.oucs.vle; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Set; import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Expression; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.sql.JoinFragment; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import uk.ac.ox.oucs.vle.CourseSignupService.Range; import uk.ac.ox.oucs.vle.CourseSignupService.Status; public class CourseDAOImpl extends HibernateDaoSupport implements CourseDAO { public CourseGroupDAO findCourseGroupById(String courseId) { return (CourseGroupDAO) getHibernateTemplate().get(CourseGroupDAO.class, courseId); } public CourseGroupDAO findCourseGroupById(final String courseId, final Range range, final Date now) { return (CourseGroupDAO) getHibernateTemplate().execute(new HibernateCallback() { // Need the DISTINCT ROOT ENTITY filter. public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(CourseGroupDAO.class); criteria.add(Expression.eq("id", courseId)); switch (range) { case UPCOMING: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Expression.gt("closes", now)); break; case PREVIOUS: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Expression.le("closes", now)); break; } criteria.setResultTransformer(Criteria.ROOT_ENTITY); return criteria.uniqueResult(); } }); } @SuppressWarnings("unchecked") public CourseGroupDAO findUpcomingComponents(String courseId, Date available) { List<CourseGroupDAO> courseGroups = getHibernateTemplate().findByNamedParam( "select distinct cg from CourseGroupDAO cg left join fetch cg.components as component where cg.id = :courseId and component.closes > :closes", new String[]{"courseId", "closes"}, new Object[]{courseId, available}); int results = courseGroups.size(); if (results > 0) { if (results > 1) { throw new IllegalStateException("To many results ("+ results + ") found for "+ courseId ); } return courseGroups.get(0); } return null; } public List<CourseComponentDAO> findOpenComponents(String id, Date at) { // TODO Auto-generated method stub return null; } public CourseGroupDAO findAvailableCourseGroupById(String courseId) { // TODO Auto-generated method stub return null; } @SuppressWarnings("unchecked") public List<CourseGroupDAO> findCourseGroupByDept(final String deptId, final Range range, final Date now, final boolean external) { return getHibernateTemplate().executeFind(new HibernateCallback() { // Need the DISTINCT ROOT ENTITY filter. public Object doInHibernate(Session session) throws HibernateException, SQLException { StringBuffer querySQL = new StringBuffer(); querySQL.append("SELECT DISTINCT "); querySQL.append("cg.id, cg.title, cg.dept, cg.departmentName, "); querySQL.append("cg.subunit, cg.subunitName, cg.description, cg.publicView, "); querySQL.append("cg.supervisorApproval, cg.administratorApproval, cg.homeApproval, cg.contactEmail "); querySQL.append("FROM course_group cg "); querySQL.append("LEFT JOIN course_group_otherDepartment cgd on cgd.course_group = cg.id "); querySQL.append("LEFT JOIN course_group_component cgc on cgc.course_group = cg.id "); querySQL.append("LEFT JOIN course_component cc on cgc.component = cc.id "); querySQL.append("WHERE "); if (external) { querySQL.append("publicView = true AND "); } switch (range) { case UPCOMING: querySQL.append("closes > NOW() AND "); break; case PREVIOUS: querySQL.append("closes < NOW() AND "); break; } querySQL.append("(otherDepartment = :deptId "); querySQL.append("OR (dept = :deptId and (subunit is NULL or subunit = ''))) "); querySQL.append("ORDER BY cg.title "); Query query = session.createSQLQuery(querySQL.toString()).addEntity(CourseGroupDAO.class); query.setString("deptId", deptId); return query.list(); //you can't use Criteria to query against a collection of value types /* Criteria criteria = session.createCriteria(CourseGroupDAO.class); criteria.add( Restrictions.or( Restrictions.and( Restrictions.eq("dept", deptId), Restrictions.or(Restrictions.isNull("subunit"),Restrictions.eq("subunit", ""))), Restrictions.eq("otherDepartment", deptId))); if (external) { criteria.add(Restrictions.eq("publicView", true)); } switch (range) { case UPCOMING: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Restrictions.gt("closes", now)); break; case PREVIOUS: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Restrictions.le("closes", now)); break; } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.addOrder(Order.asc("title")); return criteria.list(); */ } }); } @SuppressWarnings("unchecked") public List<CourseGroupDAO> findCourseGroupBySubUnit(final String subunitId, final Range range, final Date now, final boolean external) { return getHibernateTemplate().executeFind(new HibernateCallback() { // Need the DISTINCT ROOT ENTITY filter. public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(CourseGroupDAO.class); criteria.add(Restrictions.eq("subunit", subunitId)); if (external) { criteria.add(Restrictions.eq("publicView", true)); } switch (range) { case UPCOMING: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Expression.gt("closes", now)); break; case PREVIOUS: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Expression.le("closes", now)); break; } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.addOrder(Order.asc("title")); return criteria.list(); } }); } @SuppressWarnings("unchecked") public List<Object[]> findSubUnitByDept(final String deptId) { return getHibernateTemplate().executeFind(new HibernateCallback() { // Need the DISTINCT ROOT ENTITY filter. public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery("select distinct subunit, subunitName from CourseGroupDAO cg where cg.dept = :deptId and cg.subunit <> '' order by 2"); query.setString("deptId", deptId); return query.list(); } }); } @SuppressWarnings("unchecked") public List<DepartmentDAO> findAllDepartments() { return getHibernateTemplate().executeFind(new HibernateCallback() { // Need the DISTINCT ROOT ENTITY filter. public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createSQLQuery("select * from department").addEntity(DepartmentDAO.class); return query.list(); } }); } public CourseComponentDAO findCourseComponent(String id) { return (CourseComponentDAO) getHibernateTemplate().get(CourseComponentDAO.class, id); } public CourseSignupDAO newSignup(String userId, String supervisorId) { CourseSignupDAO signupDao = new CourseSignupDAO(); signupDao.setUserId(userId); signupDao.setSupervisorId(supervisorId); return signupDao; } public String save(CourseSignupDAO signupDao) { return getHibernateTemplate().save(signupDao).toString(); } public String save(CourseComponentDAO componentDao) { return getHibernateTemplate().save(componentDao).toString(); } public CourseSignupDAO findSignupById(String signupId) { return (CourseSignupDAO) getHibernateTemplate().get(CourseSignupDAO.class, signupId); } @SuppressWarnings("unchecked") public List<CourseSignupDAO> findSignupForUser(final String userId, final Set<Status> statuses) { return (List<CourseSignupDAO>)getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(CourseSignupDAO.class); criteria.add(Expression.eq("userId", userId)); if (!statuses.isEmpty()) { criteria.add(Expression.in("status", statuses.toArray())); } criteria.setFetchMode("components", FetchMode.JOIN); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } }); } public CourseGroupDAO newCourseGroup(String id, String title, String dept, String subunit) { CourseGroupDAO groupDao = new CourseGroupDAO(); groupDao.setId(id); groupDao.setTitle(title); groupDao.setDept(dept); groupDao.setSubunit(subunit); return groupDao; } public void save(CourseGroupDAO groupDao) { getHibernateTemplate().save(groupDao); } @SuppressWarnings("unchecked") public List<CourseGroupDAO> findAdminCourseGroups(final String userId) { // Finds all the coursegroups this user can admin. return getHibernateTemplate().executeFind(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createSQLQuery("select * from course_group, (select course_group from course_group_administrator where administrator = :userId union select course_group from course_group_superuser where superuser = :userId) admins where course_group.id = admins.course_group").addEntity(CourseGroupDAO.class); query.setString("userId", userId); return query.list(); } }); } @SuppressWarnings("unchecked") public List<CourseSignupDAO> findSignupByCourse(final String userId, final String courseId, final Set<Status> statuses) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query; if (null != statuses && !statuses.isEmpty()) { query = session.createSQLQuery("select * from course_signup, (select course_group from course_group_administrator where administrator = :userId union select course_group from course_group_superuser where superuser = :userId) admins where course_signup.groupId = admins.course_group and course_signup.groupId = :courseId and cs.status in (:statuses)").addEntity(CourseSignupDAO.class); query.setParameterList("statuses", statuses); } else { query = session.createSQLQuery("select * from course_signup, (select course_group from course_group_administrator where administrator = :userId union select course_group from course_group_superuser where superuser = :userId) admins where course_signup.groupId = admins.course_group and course_signup.groupId = :courseId").addEntity(CourseSignupDAO.class); } query.setString("userId", userId); query.setString("courseId", courseId); return query.list(); } }); } public Integer countSignupByCourse(final String courseId, final Set<Status> statuses) { List results = getHibernateTemplate().findByNamedParam( "select count(*) from CourseSignupDAO where groupId = :courseId and status in (:statuses)", new String[]{"courseId", "statuses"}, new Object[]{courseId, statuses}); int count = results.size(); if (count > 0) { if (count > 1) { throw new IllegalStateException("To many results ("+ results + ") found for "+ courseId ); } return (Integer)results.get(0); } return null; } @SuppressWarnings("unchecked") public List<CourseSignupDAO> findSignupByComponent(final String componentId, final Set<Status> statuses) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query; if (null != statuses && !statuses.isEmpty()) { query = session.createQuery("select cs from CourseSignupDAO cs inner join fetch cs.components cc where cc.id = :componentId and cs.status in (:statuses)"); query.setParameterList("statuses", statuses); } else { query = session.createQuery("select cs from CourseSignupDAO cs inner join fetch cs.components cc where cc.id = :componentId"); } query.setString("componentId", componentId); return query.list(); } }); } @SuppressWarnings("unchecked") public List<CourseSignupDAO> findSignupPending(final String userId) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) { Query query = session.createSQLQuery("select * from course_signup cs left join course_group_administrator ca on cs.groupId = ca.course_group inner join course_component_signup cp on cs.id = cp.signup inner join course_component cc on cp.component = cc.id where (ca.administrator = :userId and cs.status = :adminStatus) or (cs.supervisorId = :userId and cs.status = :supervisorStatus)").addEntity(CourseSignupDAO.class); query.setString("userId", userId); query.setParameter("adminStatus", Status.PENDING.name()); query.setParameter("supervisorStatus", Status.ACCEPTED.name()); return query.list(); } }); } public CourseComponentDAO newCourseComponent(String id) { CourseComponentDAO componentDao = new CourseComponentDAO(); componentDao.setId(id); return componentDao; } @SuppressWarnings("unchecked") public List<CourseGroupDAO> findCourseGroupByWords(final String[] words, final Range range, final Date date, final boolean external) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(CourseGroupDAO.class); for(String word: words) { criteria.add(Expression.ilike("title", word, MatchMode.ANYWHERE)); } if (external) { criteria.add(Expression.eq("publicView", true)); } switch(range) { case UPCOMING: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Expression.gt("closes", date)); break; case PREVIOUS: criteria = criteria.createCriteria("components", JoinFragment.LEFT_OUTER_JOIN).add(Expression.le("closes", date)); break; } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } }); } public DepartmentDAO findDepartmentByCode(String code) { return (DepartmentDAO) getHibernateTemplate().get(DepartmentDAO.class, code); } public void save(DepartmentDAO departmentDao) { getHibernateTemplate().save(departmentDao).toString(); } public void remove(CourseSignupDAO existingSignup) { getHibernateTemplate().delete(existingSignup); } /** * Used by tests to simulate another request being made. */ public void flush() { getHibernateTemplate().flush(); } }
package it.polimi.ingsw.game; import it.polimi.ingsw.exception.DebugException; import it.polimi.ingsw.exception.DefenseException; import it.polimi.ingsw.exception.GameException; import it.polimi.ingsw.exception.IllegalStateOperationException; import it.polimi.ingsw.game.card.object.ObjectCard; import it.polimi.ingsw.game.card.object.ObjectCardBuilder; import it.polimi.ingsw.game.common.GameCommand; import it.polimi.ingsw.game.common.GameInfo; import it.polimi.ingsw.game.common.GameOpcode; import it.polimi.ingsw.game.common.InfoOpcode; import it.polimi.ingsw.game.common.PlayerInfo; import it.polimi.ingsw.game.config.Config; import it.polimi.ingsw.game.player.GamePlayer; import it.polimi.ingsw.game.player.Human; import it.polimi.ingsw.game.player.Role; import it.polimi.ingsw.game.player.RoleBuilder; import it.polimi.ingsw.game.state.AwayState; import it.polimi.ingsw.game.state.DiscardingObjectCardState; import it.polimi.ingsw.game.state.EndingTurnState; import it.polimi.ingsw.game.state.LoserState; import it.polimi.ingsw.game.state.NotMyTurnState; import it.polimi.ingsw.game.state.PlayerState; import it.polimi.ingsw.game.state.StartTurnState; import it.polimi.ingsw.game.state.WinnerState; import it.polimi.ingsw.server.GameManager; import java.awt.Point; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** Class representing the current state of the game. * It is the beating heart of the game: it holds a list of all players, * the mGameManager and an event queue of messages coming from the clients. * * @author Alain Carlucci (alain.carlucci@mail.polimi.it) * @author Michele Albanese (michele.albanese@mail.polimi.it) * @since May 21, 2015 */ public class GameState { /** Logger */ private static final Logger LOG = Logger.getLogger(GameState.class.getName()); /** Debug error */ private static final String DEBUG_ERROR = "Cannot use this method in normal mode"; /** Game Manager */ private final GameManager mManager; /** Input queue */ private final Queue<GameCommand> mInputQueue; /** Output queue */ private final Queue<Map.Entry<Integer,GameCommand>> mOutputQueue; /** Game map */ private final GameMap mMap; /** Players in game */ private List<GamePlayer> mPlayers; /** Current turn id */ private int mCurPlayerId = 0; /** Number of rounds played */ private int mRoundsPlayed = 0; /** Current turn start time*/ private long mCurTurnStartTime = 0; /** Last actions in game */ public static enum LastThings { NEVERMIND, KILLED_HUMAN, GONE_OFFLINE, HUMAN_USED_HATCH } /** Last action */ private LastThings mLastThing = LastThings.NEVERMIND; /** Debug mode */ private final boolean dDebugMode; /** [DEBUG] Game over */ private boolean dGameOver = false; /** [DEBUG] If != -1, set this player as next */ private int dForceNextTurn = -1; /** Constructs a new game. * * @param gameManager The GameManager that created this game. * @param mapId Id of the map */ public GameState(GameManager gameManager, int mapId) { GameMap tmpMap = null; try { tmpMap = GameMap.createFromId(mapId); } catch(IOException e) { LOG.log(Level.SEVERE, "Missing map files: " + e.toString(), e); } mMap = tmpMap; dDebugMode = false; mManager = gameManager; mInputQueue = new LinkedList<>(); mOutputQueue = new LinkedList<>(); mPlayers = new ArrayList<>(); List<Role> roles = RoleBuilder.generateRoles(gameManager.getNumberOfClients(), true); int numberOfPlayers = gameManager.getNumberOfClients(); buildPlayersList(roles, numberOfPlayers); if(mMap == null) gameManager.shutdown(); mCurTurnStartTime = System.currentTimeMillis()/1000; } /** DEBUG MODE CONSTRUCTOR * Constructs a new game. * * @param areYouSureToEnableDebugMode YES or NO * @param mapId map id * @param numberOfPlayers number of players * @param startPlayerId start player id * @param randomizePlayers True if you want to use the random generator */ public GameState(String areYouSureToEnableDebugMode, int mapId, int numberOfPlayers, int startPlayerId, boolean randomizePlayers) { GameMap tmpMap = null; try { tmpMap = GameMap.createFromId(mapId); } catch(IOException e) { LOG.log(Level.SEVERE, "Missing map files: " + e.toString(), e); } if(!("YES".equalsIgnoreCase(areYouSureToEnableDebugMode))) throw new DebugException("Cannot enable debug mode."); mMap = tmpMap; dDebugMode = true; mManager = null; mInputQueue = new LinkedList<>(); mOutputQueue = new LinkedList<>(); mPlayers = new ArrayList<>(); mCurPlayerId = startPlayerId; List<Role> roles = RoleBuilder.generateRoles(numberOfPlayers, randomizePlayers); buildPlayersList(roles, numberOfPlayers); if(mMap == null) throw new DebugException("Invalid map file"); mCurTurnStartTime = System.currentTimeMillis()/1000; } /** Build the player list * * @param roles Array of roles * @param numberOfPlayers Number of players */ private void buildPlayersList(List<Role> roles, int numberOfPlayers) { for(int i = 0;i<numberOfPlayers; i++) { Role role = roles.get(i); GamePlayer player = new GamePlayer(i, role, getMap().getStartingPoint(role instanceof Human)); mPlayers.add(player); /** Is this my turn? */ if(i == mCurPlayerId) player.setCurrentState(new StartTurnState(this)); else player.setCurrentState(new NotMyTurnState(this)); } } /** Method called by the server hosting the games. * According to the current player's state, it lets the game flow. */ public void update() { if( !dDebugMode && !mManager.isRunning() ) return; if(dDebugMode && dGameOver) throw new DebugException("Game over"); GamePlayer player = getCurrentPlayer(); PlayerState nextState = null; /** Check for timeout */ long curTime = System.currentTimeMillis() / 1000; /** Timeout elapsed */ if(curTime > mCurTurnStartTime + Config.GAME_MAX_SECONDS_PER_TURN) { nextState = new AwayState(this); player.setCurrentState(nextState); } else { try { nextState = player.getCurrentState().update(); player.setCurrentState(nextState); } catch( IllegalStateOperationException e) { LOG.log(Level.INFO, e.toString()); LOG.log(Level.FINEST, "", e); } } /** broadcast messages at the end of the turn */ flushOutputQueue(); if(nextState != null && (nextState instanceof NotMyTurnState || !nextState.stillInGame())) moveToNextPlayer(); } /** Flush the output queue */ public void clearOutputQueue() { if(dDebugMode) return; mOutputQueue.clear(); } /** Flush the output queue */ public void flushOutputQueue() { if(dDebugMode) return; if( !mOutputQueue.isEmpty() ) { for( Map.Entry<Integer, GameCommand> pkt : mOutputQueue ) // broadcast message if(pkt.getKey().equals(-1)) mManager.broadcastPacket(pkt.getValue()); else // unicast message mManager.sendDirectPacket(pkt.getKey(), pkt.getValue()); mOutputQueue.clear(); } } /** Method invoked when a player draws an object card. * @return Next PlayerState for current player */ public PlayerState getObjectCard( ) { GamePlayer player = getCurrentPlayer(); ObjectCard newCard = ObjectCardBuilder.getRandomCard( this ); PlayerState nextState; player.addObjectCard(newCard); broadcastPacket( new GameCommand(InfoOpcode.INFO_CHANGED_NUMBER_OF_CARDS, player.getId(), player.getNumberOfCards() ) ); sendPacketToCurrentPlayer( new GameCommand(GameOpcode.CMD_SC_OBJECT_CARD_OBTAINED, (Integer)newCard.getId()) ); /** We're ok, proceed */ if( player.getNumberOfCards() <= Config.MAX_NUMBER_OF_OBJ_CARDS ) { nextState = new EndingTurnState(this); } else { /** tell the user he has to drop or use a card */ nextState = new DiscardingObjectCardState(this); } return nextState; } /** Method invoked when someone sends a CMD_CS_USE_OBJ_CARD command. * Invoke the correct underlying method * (attack() for Attack card..., moveTo() for Teleport card...) * @param objectCardPos The card the user wants to use * @return Next PlayerState for current player */ public PlayerState startUsingObjectCard(Integer objectCardPos) { GamePlayer player = getCurrentPlayer(); PlayerState nextState = player.getCurrentState(); if(player.isHuman() && !player.isObjectCardUsed() && player.getNumberOfUsableCards() > objectCardPos && objectCardPos >= 0) { Integer idInMainArr = player.findObjectCardId(objectCardPos); ObjectCard objectCard = player.useObjectCard(objectCardPos); if(objectCard != null && idInMainArr != null) { broadcastPacket( new GameCommand(InfoOpcode.INFO_OBJ_CARD_USED, objectCard.getId(), objectCard.getName()) ); player.setObjectCardUsed(true); sendPacketToCurrentPlayer( new GameCommand(GameOpcode.CMD_SC_DROP_CARD, idInMainArr) ); broadcastPacket( new GameCommand(InfoOpcode.INFO_CHANGED_NUMBER_OF_CARDS, player.getId(), player.getNumberOfCards() ) ); nextState = objectCard.doAction(); return nextState; } } return nextState; } /** Kills all players in a position. * It is used when an alien sends an attack command or * when a human player draws an Attack object card. * @param currentPosition The point where the players wants to attack */ public void attack(Point currentPosition) { ArrayList<Integer> killedPlayers = new ArrayList<>(); ArrayList<Integer> defendedPlayers = new ArrayList<>(); for(int i = 0; i < mPlayers.size(); i++) { GamePlayer player = mPlayers.get(i); if( player != getCurrentPlayer() && player.getCurrentPosition().equals(currentPosition) && player.stillInGame()) { if( player.isDefenseEnabled() ) { try { int indexCard = player.dropDefense(); broadcastPacket( new GameCommand(InfoOpcode.INFO_CHANGED_NUMBER_OF_CARDS, i, player.getNumberOfCards() ) ); sendPacketToPlayer( i, new GameCommand(GameOpcode.CMD_SC_DROP_CARD, indexCard) ); defendedPlayers.add(i); } catch( DefenseException e ) { LOG.log(Level.INFO, e.toString()); LOG.log(Level.FINEST, "", e); } } else { if(player.isHuman()) setLastThingDid(LastThings.KILLED_HUMAN); player.setCurrentState( new LoserState(this, i) ); killedPlayers.add(i); } } } /** set the player as full if he has an alien role */ if( !killedPlayers.isEmpty() ) { GamePlayer player = getCurrentPlayer(); if( player.isAlien() && mLastThing == LastThings.KILLED_HUMAN) { player.setFull(true); broadcastPacket(new GameCommand(InfoOpcode.INFO_ALIEN_FULL)); } } broadcastPacket( new GameCommand(InfoOpcode.INFO_PLAYER_ATTACKED, currentPosition, killedPlayers, defendedPlayers) ); checkEndGame(); } /** Check if the game is over and, if so, remove it and notify players * * End game conditions: [<who win?>] * * (1) [ALIENS] No humans in game (general case of "If aliens eliminate last living human") * (2) [ALIENS] No spaceships left && some humans are still in game * (3) [ALIENS] 39 rounds have been played before any human escape. * (4) [?ALIVE] Players connected <= 2 * * @param justKilledHumans True if this function is called after an attack and there are killed humans */ private void checkEndGame() { /** set to true if inGamePlayers < MIN PLAYERS */ boolean allWinnersMode = false; /** Number of alive humans */ int aliveHumans = 0; /** Number of player still playing */ int inGamePlayers = 0; /** Number of remaining hatches */ int remainingHatches = mMap.getRemainingHatches(); /** Check how many players and humans are still playing */ for(GamePlayer p : mPlayers) if(p.stillInGame()) { inGamePlayers++; if(p.isHuman()) aliveHumans++; } if(inGamePlayers < Config.GAME_MIN_PLAYERS && (mLastThing == LastThings.GONE_OFFLINE || mLastThing == LastThings.NEVERMIND)) allWinnersMode = true; if((aliveHumans == 0) || (aliveHumans > 0 && remainingHatches == 0) || (mRoundsPlayed > Config.MAX_NUMBER_OF_TURNS) || (inGamePlayers < Config.GAME_MIN_PLAYERS)) { rawEndGame(allWinnersMode); } } /** The game will end * Let's gather some stats * * @param allWinnersMode True if all connected players are winner */ private void rawEndGame(boolean allWinnersMode) { /** Move all players either into WinnerState or LoserState */ for(int i = 0; i < mPlayers.size(); i++) { GamePlayer p = mPlayers.get(i); if(p.stillInGame() && ((p.isAlien() && mLastThing != LastThings.HUMAN_USED_HATCH)|| allWinnersMode)) p.setCurrentState(new WinnerState(this, i)); else if(!(p.getCurrentState() instanceof WinnerState)) p.setCurrentState(new LoserState(this, i)); } clearOutputQueue(); /** Fill this two arrays */ ArrayList<Integer> winnersList = new ArrayList<>(); ArrayList<Integer> loserList = new ArrayList<>(); for(int i = 0; i < mPlayers.size(); i++) { GamePlayer p = mPlayers.get(i); PlayerState s = p.getCurrentState(); if(s instanceof WinnerState) winnersList.add(i); else if(s instanceof LoserState) loserList.add(i); else throw new GameException("There are players who are neither winner nor loser. What's happening?"); } broadcastPacket( new GameCommand(InfoOpcode.INFO_END_GAME, winnersList, loserList)); flushOutputQueue(); if(!dDebugMode) mManager.shutdown(); else dGameOver = true; } /** Moves current player in a position. * It is used by the Teleport card and when moving during * the normal flow of the game. * * @param player Player * @param dest Where to move */ public void rawMoveTo(GamePlayer player, Point dest) { if( getMap().isWithinBounds(dest) && !player.getCurrentPosition().equals(dest) ) { player.setCurrentPosition(dest); broadcastPacket( InfoOpcode.INFO_HAS_MOVED ); } } /** Invoked in SpotLightCardState. * It lists all people in the set position and in the 6 surrounding it. * @param point The position where the card takes effect. */ public void spotlightAction(Point point) { List<Point> sectors = getMap().getNeighbourAccessibleSectors(point, getCurrentPlayer().isHuman(), true); sectors.add(point); Point[] caughtPlayers = new Point[mPlayers.size()]; for(int i = 0; i < mPlayers.size(); i++) { GamePlayer player = mPlayers.get(i); caughtPlayers[i] = null; if(sectors.contains( player.getCurrentPosition())) caughtPlayers[i] = player.getCurrentPosition(); } broadcastPacket( new GameCommand( InfoOpcode.INFO_SPOTLIGHT, point, caughtPlayers) ); } /** Read a packet from the input queue * * @return The read packet */ public GameCommand getPacketFromQueue( ) { synchronized(mInputQueue) { return mInputQueue.poll(); } } /** Get the current player * * @return The current player */ public synchronized GamePlayer getCurrentPlayer() { if(mCurPlayerId == -1) throw new GameException("CurrentPlayer == -1. What's happening?"); return mPlayers.get( mCurPlayerId ); } /** Get the game map * * @return The game map */ public GameMap getMap() { return mMap; } /** Enqueue a command * * @param gameCommand The command */ public void enqueuePacket(GameCommand gameCommand) { synchronized(mInputQueue) { mInputQueue.add(gameCommand); } } /** Build the info container used to send info to the client * * @param userList Username list * @param i Player id (to send this packet) * @return Game infos */ public GameInfo buildInfoContainer(PlayerInfo[] userList, int i) { return new GameInfo(userList, i, mPlayers.get(i).isHuman(), mMap); } /** Get the cells the current player can go into * * @return The cells */ public Set<Point> getCellsWithMaxDistance() { GamePlayer player = getCurrentPlayer(); return getMap().getCellsWithMaxDistance( player.getCurrentPosition(), player.getMaxMoves(), player.isHuman() ); } /** Switch to the next player */ public void moveToNextPlayer() { int newTurnId = -1; int lastTurnId = mCurPlayerId; if(dDebugMode && dForceNextTurn != -1) { checkEndGame(); mCurPlayerId = dForceNextTurn; dForceNextTurn = -1; } else { for( int currId = mCurPlayerId + 1; currId < mCurPlayerId + mPlayers.size(); ++currId ) { if( mPlayers.get(currId % mPlayers.size()).getCurrentState() instanceof NotMyTurnState ) { newTurnId = currId % mPlayers.size(); break; } } if(newTurnId <= lastTurnId) mRoundsPlayed ++; checkEndGame(); if(newTurnId == -1) return; mCurPlayerId = newTurnId; } getCurrentPlayer().setCurrentState( new StartTurnState( this ) ); mCurTurnStartTime = System.currentTimeMillis()/1000; } /** Broadcast a packet * * @param pkt The packet */ public void broadcastPacket( GameCommand pkt ) { synchronized(mOutputQueue) { mOutputQueue.add( new AbstractMap.SimpleEntry<Integer,GameCommand>(-1,pkt) ); } } /** Broadcast a packet * * @param command Packet opcode */ public void broadcastPacket( InfoOpcode command ) { broadcastPacket( new GameCommand( command ) ); } /** Send a packet to the current player * * @param command The packet command */ public void sendPacketToCurrentPlayer(GameOpcode command) { sendPacketToCurrentPlayer(new GameCommand(command)); } /** Send a packet to the current player * * @param command The packet command */ public void sendPacketToCurrentPlayer(GameCommand command) { synchronized(mOutputQueue) { mOutputQueue.add( new AbstractMap.SimpleEntry<Integer,GameCommand>(mCurPlayerId, command)); } } /** Get the number of player in this sector * * @param point Sector * @return Number of players */ public int getNumberOfPlayersInSector( Point point ) { int counter = 0; for( GamePlayer player : mPlayers ) if( player.stillInGame() && player.getCurrentPosition().equals(point) ) counter++; return counter; } /** Get the current turn id * * @return The current turn */ public int getTurnId() { return mCurPlayerId; } /** Called when a client disconnects * @param id Id */ public void onPlayerDisconnect(int id) { GamePlayer player = mPlayers.get(id); if(player != null) { if(mCurPlayerId == id) moveToNextPlayer(); player.setCurrentState(new AwayState(this)); setLastThingDid(LastThings.GONE_OFFLINE); } checkEndGame(); } /** Send a packet to the specified player * @param player The player * @param pkt The packet */ public void sendPacketToPlayer(Integer player, GameCommand pkt) { synchronized(mOutputQueue) { mOutputQueue.add( new AbstractMap.SimpleEntry<Integer,GameCommand>(player, pkt)); } } public synchronized void setLastThingDid(LastThings ltd) { mLastThing = ltd; } /** [DEBUG] Get the output queue * * @return The output packet queue */ public Queue<Map.Entry<Integer,GameCommand>> debugGetOutputQueue() { if(!dDebugMode) throw new DebugException(DEBUG_ERROR); Queue<Map.Entry<Integer,GameCommand>> q = new LinkedList<>(); for( Map.Entry<Integer, GameCommand> pkt : mOutputQueue ) q.add(pkt); mOutputQueue.clear(); return q; } /** [DEBUG] Change next player * * @param id Who's the next? */ public void debugSetNextTurnId(int id) { if(!dDebugMode) throw new DebugException(DEBUG_ERROR); dForceNextTurn = id; } /** [DEBUG] Get the player object. Useful to add card or change values * * @param playerId The player id [0-7] * @return The player object */ public GamePlayer debugGetPlayer(int playerId) { if(!dDebugMode) throw new DebugException(DEBUG_ERROR); return mPlayers.get(playerId); } /** [DEBUG] Check if the game is end * * @return True if the game is end */ public boolean debugGameEnded() { if(!dDebugMode) throw new DebugException(DEBUG_ERROR); return dGameOver; } /** Check if debug mode is enabled * * @return True if game is in debug mode */ public boolean isDebugModeEnabled() { return dDebugMode; } /** Get last thing did * * @return Last thing did */ public LastThings debugGetLastThingDid() { if(!dDebugMode) throw new DebugException(DEBUG_ERROR); return mLastThing; } }
package com.getirkit; import android.app.backup.BackupManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import com.getirkit.net.IRAPICallback; import com.getirkit.net.IRAPIError; import com.getirkit.net.IRAPIResult; import com.getirkit.net.IRHTTPClient; import com.getirkit.net.IRInternetAPIService; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.math.BigInteger; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteOrder; import java.util.ArrayDeque; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import retrofit.RetrofitError; import retrofit.client.Response; /** * IRKit library main class */ public class IRKit { public String TAG; public static final String SERVICE_TYPE = "_irkit._tcp.local."; public static final String PREF_KEY_BONJOUR_HOSTNAME = "debuginfo.bonjour.hostname"; public static final String PREF_KEY_BONJOUR_RESOLVED_AT = "debuginfo.bonjour.resolved_at"; private static final int SEND_SIGNAL_LOCAL_TIMEOUT_MS = 3000; /** * IRPeripherals instance which holds existing IRPeripheral instances. * IRPeripheralIRPeripherals */ public IRPeripherals peripherals; /** * IRSignals instance which holds existing IRSignal instances. * IRSignalIRSignals */ public IRSignals signals; private Context context; private IRKitEventListener irkitEventListener; private IRHTTPClient httpClient; private boolean isDataLoaded = false; private WifiManager wifiManager; private ScanResultReceiver scanResultReceiver; private WifiEnableEventReceiver wifiEnableEventReceiver; private boolean isDiscovering = false; private LinkedList<Boolean> discoveryQueue; private boolean isProcessingBonjour = false; private boolean isInitialized = false; private IRKitSetupManager setupManager; private NetworkStateChangeReceiver networkStateChangeReceiver; // For JmDNS private WifiManager.MulticastLock multicastLock; private JmDNS jmdns; private BonjourServiceListener bonjourServiceListener; // singleton private static IRKit ourInstance = new IRKit(); /** * Returns a singleton instance. * singleton * * @return */ public static IRKit sharedInstance() { return ourInstance; } public IRHTTPClient getHTTPClient() { return httpClient; } private ArrayDeque<SendSignalItem> sendSignalQueue = new ArrayDeque<>(); private IRKit() { httpClient = IRHTTPClient.sharedInstance(); TAG = IRKit.class.getSimpleName() + ":" + this.hashCode(); } /** * Load data from shared preferences */ public void loadData() { if (!isDataLoaded) { peripherals = new IRPeripherals(); peripherals.load(); signals = new IRSignals(); signals.load(); signals.updateImageResourceIdFromName(context.getResources()); if (!signals.checkIdOverlap()) { Log.e(TAG, "there are some signals that share the same id"); // TODO: reassign ids? } signals.removeInvalidSignals(); isDataLoaded = true; } } public void cancelIRKitSetup() { if (setupManager != null) { setupManager.cancel(); setupManager = null; } stopWifiStateListener(); stopWifiScan(); getHTTPClient().cancelPostDoor(); httpClient.clearDeviceKeyCache(); } public void setupIRKit(String apiKey, IRWifiInfo connectDestination, String irkitWifiPassword, IRKitConnectWifiListener listener) { if (setupManager != null && setupManager.isActive()) { // There is an active setup setupManager.setIrKitConnectWifiListener(listener); return; } // cancelIRKitSetup(); // TODO: Do we need this? setupManager = new IRKitSetupManager(context); setupManager.setIrKitConnectWifiListener(listener); setupManager.start(apiKey, connectDestination, irkitWifiPassword); } /** * Watch Wi-Fi state change. When Wi-Fi is enabled, Bonjour discovery * will automatically start. When Wi-Fi is disabled, Bonjour discovery * will automatically stop. * Wi-FiWi-FiBonjour * Wi-FiBonjour */ public void registerWifiStateChangeListener() { if (networkStateChangeReceiver == null) { networkStateChangeReceiver = new NetworkStateChangeReceiver(); } context.registerReceiver(networkStateChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } /** * Unwatch Wi-Fi state change. * Wi-Fi */ public void unregisterWifiStateChangeListener() { if (networkStateChangeReceiver != null) { context.unregisterReceiver(networkStateChangeReceiver); networkStateChangeReceiver = null; } } /** * Start Bonjour discovery for IRKit. * IRKitBonjour */ public void startServiceDiscovery() { if (!isWifiConnected()) { // Wi-Fi is not connected. We don't initiate service discovery. return; } synchronized (this) { if (isDiscovering) { return; } isDiscovering = true; } startBonjourDiscovery(); } /** * Stop Bonjour discovery for IRKit. * IRKitBonjour */ public void stopServiceDiscovery() { synchronized (this) { if (!isDiscovering) { return; } isDiscovering = false; } stopBonjourDiscovery(); } public boolean isInitialized() { return isInitialized; } public void addExampleDataIfEmpty() { if (peripherals.isEmpty()) { addExamplePeripheral(); } if (signals.isEmpty()) { addExampleSignal(); } } public void addExamplePeripheral() { IRPeripheral peripheral = new IRPeripheral(); peripheral.setHostname("IRKit1234"); peripheral.setCustomizedName("IRKit1234"); peripheral.setFoundDate(new Date()); peripheral.setDeviceId("testdeviceid"); peripheral.setModelName("IRKit"); peripheral.setFirmwareVersion("2.0.2.0.g838e0ea"); peripherals.add(peripheral); peripherals.save(); } public void addExampleSignal() { // debug (add signal) IRSignal testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); // testSignal.setName("Warm"); testSignal.setName(""); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_aircon); testSignal.onUpdateImageResourceId(context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(0); signals.add(testSignal); testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); // testSignal.setName("Cool"); testSignal.setName(""); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_aircon); testSignal.onUpdateImageResourceId(context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(1); signals.add(testSignal); testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); testSignal.setName("\uD83D\uDCA4"); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_aircon); testSignal.onUpdateImageResourceId(context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(2); signals.add(testSignal); testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); // testSignal.setName("\uD83C\uDFE0"); // house building // testSignal.setName("Living Room"); testSignal.setName(""); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_light); testSignal.onUpdateImageResourceId(context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(3); signals.add(testSignal); signals.save(); } /** * Set context, and initialize IRKit instance if it is not initialized yet. * contextIRKit * * @param context Application context */ public void init(Context context) { setContext(context); if (!isInitialized) { isInitialized = true; discoveryQueue = new LinkedList<>(); loadData(); } } public void savePreference(String key, String value) { SharedPreferences sharedPrefs = context.getSharedPreferences( context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE ); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString(key, value); editor.apply(); this.requestBackup(); } public String getPreference(String key) { SharedPreferences sharedPrefs = context.getSharedPreferences( context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE ); return sharedPrefs.getString(key, null); } public void requestBackup() { BackupManager bm = new BackupManager(context); bm.dataChanged(); } /** * Returns the global IRKit API key. * * @return */ public String getIRKitAPIKey() { // Fetch IRKit api key in whatever way you want ApplicationInfo ai = null; try { ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); Log.e(TAG, "Failed to get apikey. Have you add com.getirkit.IRKIT_API_KEY to AndroidManifest.xml?"); return null; } Bundle metaData = ai.metaData; if (metaData == null) { Log.e(TAG, "Failed to get apikey. Have you add com.getirkit.IRKIT_API_KEY to AndroidManifest.xml?"); return null; } return metaData.getString("com.getirkit.IRKIT_API_KEY"); } /** * If we have not received clientkey yet, fetch it using apikey. * If apikey is null, it is read from AndroidManifest.xml. * clientkeyapikeyapikeynull * AndroidManifest.xmlapikey */ public void registerClient(String apikey) { if (apikey == null) { apikey = getIRKitAPIKey(); } if (apikey != null) { IRHTTPClient.sharedInstance().ensureRegisteredAndCall(apikey, new IRAPICallback<IRInternetAPIService.GetClientsResponse>() { @Override public void success(IRInternetAPIService.GetClientsResponse getClientsResponse, Response response) { // Client has been registered or already registered } @Override public void failure(RetrofitError error) { Log.e(TAG, "Failed to register client: " + error.getMessage()); } }); } } /** * Fetch clientkey if we have not received it yet. * clientkey */ public void registerClient() { registerClient(null); } public void removeWifiConfiguration(int networkId) { if (networkId != -1) { fetchWifiManager(); wifiManager.removeNetwork(networkId); } } public void disconnectFromCurrentWifi() { fetchWifiManager(); wifiManager.disconnect(); } public WifiConfiguration getCurrentWifiConfiguration() { fetchWifiManager(); WifiInfo currentWifiInfo = getCurrentWifiInfo(); if (currentWifiInfo == null) { return null; } List<WifiConfiguration> networks = wifiManager.getConfiguredNetworks(); if (networks == null) { return null; } for (WifiConfiguration config : networks) { if (config.networkId == currentWifiInfo.getNetworkId()) { return config; } } return null; } public WifiInfo getCurrentWifiInfo() { if (context == null) { Log.e(TAG, "getCurrentWifiInfo: context is null"); return null; } ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.getConnectionInfo(); // returns WifiInfo instance } else { // No internet connection WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.getConnectionInfo(); // returns WifiInfo instance } } private void fetchWifiManager() { if (wifiManager == null) { wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); } } public void stopWifiStateListener() { if (wifiEnableEventReceiver != null) { wifiEnableEventReceiver.stop(); context.getApplicationContext().unregisterReceiver(wifiEnableEventReceiver); wifiEnableEventReceiver = null; } } public void setWifiEnabled(boolean set) { fetchWifiManager(); wifiManager.setWifiEnabled(set); } public boolean isWifiEnabled() { fetchWifiManager(); return wifiManager.isWifiEnabled(); } public void scanIRKitWifi(final IRKitWifiScanResultListener listener) { fetchWifiManager(); if (scanResultReceiver == null) { scanResultReceiver = new ScanResultReceiver(wifiManager); scanResultReceiver.setIRKitWifiScanResultListener(new IRKitWifiScanResultListener() { @Override public void onIRKitWifiFound(ScanResult result) { stopWifiScan(); listener.onIRKitWifiFound(result); } }); context.getApplicationContext().registerReceiver(scanResultReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); } if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); wifiEnableEventReceiver = new WifiEnableEventReceiver(); wifiEnableEventReceiver.setListener(new WifiEnableEventReceiver.WifiEnableEventReceiverListener() { @Override public void onWifiEnabled() { stopWifiStateListener(); wifiManager.startScan(); final Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { if (scanResultReceiver == null) { // cancel timer t.cancel(); } else { // perform another scan wifiManager.startScan(); } } }, 10000, 10000); } }); context.getApplicationContext().registerReceiver(wifiEnableEventReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); } else { wifiManager.startScan(); } } public interface WifiConnectionChangeListener { public void onTargetWifiConnected(WifiInfo wifiInfo, NetworkInfo networkInfo); public void onError(String reason); public void onTimeout(); } public interface IRKitWifiScanResultListener { public void onIRKitWifiFound(ScanResult result); } public void stopWifiScan() { if (scanResultReceiver != null) { scanResultReceiver.stopScan(); context.getApplicationContext().unregisterReceiver(scanResultReceiver); scanResultReceiver = null; } } // Delete IRKit Wi-Fi configuration from Android public void clearIRKitWifiConfigurations() { fetchWifiManager(); List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) { if (IRWifiInfo.isIRKitWifi(config)) { wifiManager.removeNetwork(config.networkId); } } } public WifiConfiguration getWifiConfigurationBySSID(String ssid) { List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) { if (config.SSID.equals(ssid)) { return config; } } return null; } public void connectToNormalWifi(WifiConfiguration wifiConfig, final WifiConnectionChangeListener listener) { fetchWifiManager(); final WifiConnectionChangeReceiver wifiConnectionChangeReceiver = new WifiConnectionChangeReceiver(wifiManager, wifiConfig); wifiConnectionChangeReceiver.setWifiConnectionChangeListener(new WifiConnectionChangeListener() { @Override public void onTargetWifiConnected(WifiInfo wifiInfo, NetworkInfo networkInfo) { wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onTargetWifiConnected(wifiInfo, networkInfo); } @Override public void onError(String reason) { Log.e(TAG, "connectToNormalWifi error: " + reason); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onError(reason); } @Override public void onTimeout() { Log.e(TAG, "connectToNormalWifi timeout"); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onTimeout(); } }); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); context.getApplicationContext().registerReceiver(wifiConnectionChangeReceiver, intentFilter); wifiManager.enableNetwork(wifiConfig.networkId, true); } public int connectToIRKitWifi(IRWifiInfo irWifiInfo, final WifiConnectionChangeListener listener) { final String irkitSSID = "\"" + irWifiInfo.getSSID() + "\""; WifiConfiguration wifiConfig = getWifiConfigurationBySSID(irkitSSID); int irkitWifiNetworkId; if (wifiConfig != null) { // Update existing IRKit Wi-Fi configuration wifiConfig.preSharedKey = "\"" + irWifiInfo.getPassword() + "\""; irkitWifiNetworkId = wifiManager.updateNetwork(wifiConfig); if (irkitWifiNetworkId == -1) { Log.e(TAG, "Failed to update network configuration"); listener.onError("Failed to update network configuration"); return irkitWifiNetworkId; } } else { // Add IRKit Wi-Fi configuration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = irkitSSID; wifiConfig.preSharedKey = "\"" + irWifiInfo.getPassword() + "\""; irkitWifiNetworkId = wifiManager.addNetwork(wifiConfig); if (irkitWifiNetworkId == -1) { Log.e(TAG, "Failed to add network configuration"); listener.onError("Failed to add network configuration"); return irkitWifiNetworkId; } } long irkitWifiConnectionTimeout = 30000; fetchWifiManager(); final WifiConnectionChangeReceiver wifiConnectionChangeReceiver = new WifiConnectionChangeReceiver( wifiManager, wifiConfig, WifiConnectionChangeReceiver.FLAG_FULL_MATCH, irkitWifiConnectionTimeout); wifiConnectionChangeReceiver.setWifiConnectionChangeListener(new WifiConnectionChangeListener() { @Override public void onTargetWifiConnected(WifiInfo wifiInfo, NetworkInfo networkInfo) { wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); getHTTPClient().setDeviceAPIEndpoint(IRHTTPClient.DEVICE_API_ENDPOINT_IRKITWIFI); listener.onTargetWifiConnected(wifiInfo, networkInfo); } @Override public void onError(String reason) { Log.e(TAG, "connectToIRKitWifi error: " + reason); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onError(reason); } @Override public void onTimeout() { Log.e(TAG, "connectToIRKitWifi timeout"); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onTimeout(); } }); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); context.getApplicationContext().registerReceiver(wifiConnectionChangeReceiver, intentFilter); if (irkitWifiNetworkId != -1) { if (!wifiManager.enableNetwork(irkitWifiNetworkId, true)) { Log.e(TAG, "enableNetwork failed"); } } else { Log.e(TAG, "Invalid network id: " + irkitWifiNetworkId); } return irkitWifiNetworkId; } public String getDebugInfo() { WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(metrics); try { JSONObject debugInfo = new JSONObject(); JSONObject os = new JSONObject(); os.put("manufacturer", Build.MANUFACTURER); os.put("model", Build.MODEL); os.put("version", Build.VERSION.RELEASE); os.put("sdk_int", Build.VERSION.SDK_INT); os.put("fingerprint", Build.FINGERPRINT); // BRAND/PRODUCT/DEVICE:VERSION.RELEASE/ID/VERSION.INCREMENTAL:TYPE/TAGS JSONObject screen = new JSONObject(); screen.put("width", metrics.widthPixels); screen.put("height", metrics.heightPixels); os.put("screen", screen); debugInfo.put("system", os); debugInfo.put("peripherals", peripherals.toJSONArray()); JSONObject bonjour = new JSONObject(); bonjour.put("hostname", getPreference(PREF_KEY_BONJOUR_HOSTNAME)); bonjour.put("resolved_at", getPreference(PREF_KEY_BONJOUR_RESOLVED_AT)); debugInfo.put("bonjour", bonjour); debugInfo.put("version", BuildConfig.VERSION_NAME); debugInfo.put("platform", "android"); return debugInfo.toString(); } catch (JSONException e) { e.printStackTrace(); return null; } // String osCodename = Build.VERSION.CODENAME; // String osIncremental = Build.VERSION.INCREMENTAL; // String osRelease = Build.VERSION.RELEASE; // int sdkVersion = Build.VERSION.SDK_INT; // Log.d(TAG, "VERSION.CODENAME: " + osCodename); // Log.d(TAG, "VERSION.INCREMENTAL: " + osIncremental); // Log.d(TAG, "VERSION.RELEASE: " + osRelease); // Log.d(TAG, "VERSION.SDK_INT: " + sdkVersion); // String deviceManufacturer = Build.MANUFACTURER; // String deviceModel = Build.MODEL; // Log.d(TAG, "MANUFACTURER: " + deviceManufacturer); // Log.d(TAG, "MODEL: " + deviceModel); // String buildId = Build.DISPLAY; // Log.d(TAG, "DISPLAY (build ID): " + buildId); // Log.d(TAG, "FINGERPRINT: " + Build.FINGERPRINT); // Log.d(TAG, "HARDWARE: " + Build.HARDWARE); // Log.d(TAG, "ID (changelist number or label): " + Build.ID); // Log.d(TAG, "PRODUCT: " + Build.PRODUCT); // Log.d(TAG, "SERIAL: " + Build.SERIAL); // Log.d(TAG, "TAGS: " + Build.TAGS); // Log.d(TAG, "TYPE: " + Build.TYPE); // Log.d(TAG, "DEVICE: " + Build.DEVICE); // Log.d(TAG, "BRAND: " + Build.BRAND); // Log.d(TAG, "BOOTLOADER: " + Build.BOOTLOADER); // Log.d(TAG, "BOARD: " + Build.BOARD); } public static int getRegDomainForDefaultLocale() { return getRegDomainForLocale(Locale.getDefault()); } public static int getRegDomainForLocale(Locale locale) { String countryCode = locale.getCountry(); int regdomain; String fccPattern = "^(?:CA|MX|US|AU|HK|IN|MY|NZ|PH|TW|RU|AR|BR|CL|CO|CR|DO|DM|EC|PA|PY|PE|PR|VE)$"; if (countryCode.equals("JP")) { regdomain = 2; // TELEC } else if (countryCode.matches(fccPattern)) { regdomain = 0; // FCC } else { regdomain = 1; // ETSI } return regdomain; } public InetAddress getWifiIPv4Address() { fetchWifiManager(); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); // Convert little-endian to big-endian if needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); } byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(ipByteArray); } catch (UnknownHostException ex) { Log.e(TAG, "Failed to get Wi-Fi IP address"); } return inetAddress; } class BonjourServiceListener implements ServiceListener { @Override public void serviceAdded(ServiceEvent serviceEvent) { jmdns.requestServiceInfo(serviceEvent.getType(), serviceEvent.getName()); } @Override public void serviceRemoved(ServiceEvent serviceEvent) { String serviceName = serviceEvent.getName(); IRPeripheral peripheral = peripherals.getPeripheral(serviceName); if (peripheral != null) { peripheral.lostLocalAddress(); } } @Override public void serviceResolved(ServiceEvent serviceEvent) { ServiceInfo serviceInfo = serviceEvent.getInfo(); if (serviceInfo == null) { Log.e(TAG, "serviceResolved: service info is null"); return; } Inet4Address[] addresses = serviceInfo.getInet4Addresses(); if (addresses.length == 0) { Log.e(TAG, "serviceResolved: no address"); return; } Inet4Address host = addresses[0]; int port = serviceInfo.getPort(); String serviceName = serviceEvent.getName(); // Log.d(TAG, "resolve success: name=" + serviceName + " host=" + host + " port=" + port); savePreference(PREF_KEY_BONJOUR_HOSTNAME, serviceEvent.getInfo().getQualifiedName()); savePreference(PREF_KEY_BONJOUR_RESOLVED_AT, String.valueOf(new Date().getTime() / 1000)); IRPeripheral peripheral = peripherals.getPeripheral(serviceName); if (peripheral == null) { // Found new IRKit peripheral = peripherals.addPeripheral(serviceName); if (irkitEventListener != null) { irkitEventListener.onNewIRKitFound(peripheral); } } else { if (irkitEventListener != null) { irkitEventListener.onExistingIRKitFound(peripheral); } } peripheral.setHost(host); peripheral.setPort(port); final IRPeripheral p = peripheral; if (!peripheral.hasDeviceId()) { // Wait 2000 ms to settle. // We can't use Handler nor AsyncTask because we aren't on the UI thread. Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { p.fetchDeviceId(); } }, 2000); } else if (!peripheral.hasModelInfo()) { // Wait 500 ms to settle. // We can't use Handler nor AsyncTask because we aren't on the UI thread. Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { p.fetchModelInfo(); } }, 500); } } } private void pushDiscoveryQueue(boolean startDiscovery) { int originalSize; synchronized (discoveryQueue) { originalSize = discoveryQueue.size(); while (discoveryQueue.size() >= 1) { boolean set = discoveryQueue.peekLast(); if (set == startDiscovery) { return; } else { if (discoveryQueue.size() >= 2) { discoveryQueue.removeLast(); continue; } } break; } discoveryQueue.add(startDiscovery); } if (originalSize == 0 && !isProcessingBonjour) { nextDiscoveryQueue(); } } private void nextDiscoveryQueue() { boolean startDiscovery; synchronized (discoveryQueue) { if (discoveryQueue.isEmpty()) { return; } startDiscovery = discoveryQueue.pop(); } if (startDiscovery) { _startBonjourDiscovery(); } else { _stopBonjourDiscovery(); } } private void _startBonjourDiscovery() { if (isProcessingBonjour) { Log.e(TAG, "isProcessingBonjour is true"); return; } isProcessingBonjour = true; // Do network tasks in background. We can't use Handler here. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { fetchWifiManager(); WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); multicastLock = wifi.createMulticastLock(getClass().getName()); multicastLock.setReferenceCounted(true); multicastLock.acquire(); InetAddress deviceIPAddress = getWifiIPv4Address(); try { // Do not use default constructor i.e. JmDNS.create() jmdns = JmDNS.create(deviceIPAddress); } catch (IOException e) { e.printStackTrace(); } if (jmdns != null) { // Started zeroconf probe bonjourServiceListener = new BonjourServiceListener(); jmdns.addServiceListener(SERVICE_TYPE, bonjourServiceListener); } isProcessingBonjour = false; nextDiscoveryQueue(); return null; } }.execute(); } public void startBonjourDiscovery() { pushDiscoveryQueue(true); } public void stopBonjourDiscovery() { pushDiscoveryQueue(false); } private void _stopBonjourDiscovery() { if (isProcessingBonjour) { Log.e(TAG, "isProcessingBonjour is true"); return; } isProcessingBonjour = true; // Do network tasks in another thread new Thread(new Runnable() { @Override public void run() { if (jmdns != null) { if (bonjourServiceListener != null) { jmdns.removeServiceListener(SERVICE_TYPE, bonjourServiceListener); bonjourServiceListener = null; } try { jmdns.close(); } catch (IOException e) { e.printStackTrace(); } jmdns = null; } if (multicastLock != null) { multicastLock.release(); multicastLock = null; } // Stopped zeroconf probe isProcessingBonjour = false; nextDiscoveryQueue(); } }).start(); } /** * Call _sendSignal() one by one using queue * * IRKit panics when received parallel requests from local network. * * @param signal * @param callback */ public void sendSignal(IRSignal signal, IRAPIResult callback) { synchronized (sendSignalQueue) { sendSignalQueue.add(new SendSignalItem(signal, callback)); if (sendSignalQueue.size() == 1) { // Do it now _sendSignal(signal, callback); } } } private void consumeNextSendSignal() { synchronized (sendSignalQueue) { sendSignalQueue.removeFirst(); SendSignalItem sendSignalItem = sendSignalQueue.peek(); if (sendSignalItem != null) { // Consume the next signal _sendSignal(sendSignalItem.signal, sendSignalItem.callback); } } } private void _sendSignal(final IRSignal signal, final IRAPIResult callback) { String deviceId = signal.getDeviceId(); if (deviceId == null) { // This shouldn't happen under normal circumstances Log.e(TAG, "sendSignal: deviceId is null"); if (callback != null) { callback.onError(new IRAPIError("deviceId is null")); } consumeNextSendSignal(); return; } final IRPeripheral peripheral = peripherals.getPeripheralByDeviceId(deviceId); // If a peripheral is registered twice, its deviceId is overwritten. // But we still try to send those signals over Internet API. final IRAPICallback<IRInternetAPIService.PostMessagesResponse> internetAPICallback = new IRAPICallback<IRInternetAPIService.PostMessagesResponse>() { @Override public void success(IRInternetAPIService.PostMessagesResponse postMessagesResponse, Response response) { if (callback != null) { callback.onSuccess(); } consumeNextSendSignal(); } @Override public void failure(RetrofitError error) { if (callback != null) { callback.onError(new IRAPIError(error.getLocalizedMessage())); } consumeNextSendSignal(); } }; if ( peripheral != null && peripheral.isLocalAddressResolved() ) { httpClient.setDeviceAPIEndpoint(peripheral.getDeviceAPIEndpoint()); httpClient.sendSignalOverLocalNetwork(signal, new IRAPIResult() { @Override public void onSuccess() { if (callback != null) { callback.onSuccess(); } consumeNextSendSignal(); } @Override public void onError(IRAPIError error) { // Try to send signal over Internet httpClient.sendSignalOverInternet(signal, internetAPICallback); } @Override public void onTimeout() { peripheral.lostLocalAddress(); // Try to send signal over Internet httpClient.sendSignalOverInternet(signal, internetAPICallback); } }, SEND_SIGNAL_LOCAL_TIMEOUT_MS); } else { // Local address isn't resolved httpClient.sendSignalOverInternet(signal, internetAPICallback); } } public boolean isWifiConnected() { ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return mWifi.isConnected(); } // Getters and setters public IRKitEventListener getIRKitEventListener() { return irkitEventListener; } /** * Set an IRKitEventListener to this instance. * IRKitEventListenernull * * @param listener IRKitEventListener instance. Pass null to unset listener. */ public void setIRKitEventListener(IRKitEventListener listener) { this.irkitEventListener = listener; } public void setContext(Context c) { context = c; if (!httpClient.hasClientKey()) { httpClient.setClientKey(this.getPreference("clientkey")); } } public Context getContext() { return context; } public boolean isDataLoaded() { return isDataLoaded; } // Interfaces public interface IRKitConnectWifiListener { public void onStatus(String status); public void onError(String message); public void onComplete(); } // Inner classes private static class SendSignalItem { public IRSignal signal; public IRAPIResult callback; public SendSignalItem(IRSignal signal, IRAPIResult callback) { this.signal = signal; this.callback = callback; } } private static class NetworkStateChangeReceiver extends BroadcastReceiver { public static final String TAG = NetworkStateChangeReceiver.class.getName(); /** * Called when connectivity has been changed * * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = conMan.getActiveNetworkInfo(); IRKit irkit = IRKit.sharedInstance(); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Wi-Fi connection is available irkit.startServiceDiscovery(); } else { // No Wi-Fi connection irkit.stopServiceDiscovery(); } } } private static class WifiConnectionChangeReceiver extends BroadcastReceiver { public static final String TAG = WifiConnectionChangeReceiver.class.getSimpleName(); public static final int FLAG_FULL_MATCH = 1; public static final int FLAG_STARTS_WITH = 2; private WifiConnectionChangeListener wifiConnectionChangeListener; private String targetSSID; private int flag; private WifiConfiguration targetWifiConfiguration; private String lastSeenSSID; private long startTime; private static final int ERROR_TIME_THRESHOLD = 3000; // milliseconds private boolean isFinished = false; private int authFailedCount = 0; private WifiManager wifiManager; private boolean isCanceled = false; private Handler timeoutHandler; private Runnable timeoutRunnable; public WifiConnectionChangeReceiver(WifiManager wifiManager, WifiConfiguration wifiConfig, int flag, long timeoutMs) { super(); this.wifiManager = wifiManager; targetWifiConfiguration = wifiConfig; targetSSID = targetWifiConfiguration.SSID; this.flag = flag; startTime = System.currentTimeMillis(); if (timeoutMs != 0) { timeoutHandler = new Handler(); timeoutRunnable = new Runnable() { @Override public void run() { synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onTimeout(); } } timeoutRunnable = null; timeoutHandler = null; } } }; timeoutHandler.postDelayed(timeoutRunnable, timeoutMs); } } public WifiConnectionChangeReceiver(WifiManager wifiManager, WifiConfiguration wifiConfig) { this(wifiManager, wifiConfig, FLAG_FULL_MATCH, 0); } public void cancel() { synchronized (this) { isCanceled = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } } } private boolean matchesSSID(String currentSSID, String targetSSID) { if (currentSSID == null || targetSSID == null) { return false; } Pattern pattern = Pattern.compile("^\"(.*)\"$"); Matcher matcher = pattern.matcher(currentSSID); if ( matcher.matches() ) { currentSSID = matcher.group(1); } matcher = pattern.matcher(targetSSID); if ( matcher.matches() ) { targetSSID = matcher.group(1); } if (flag == FLAG_FULL_MATCH) { return currentSSID.equals(targetSSID); } else if (flag == FLAG_STARTS_WITH) { return currentSSID.startsWith(targetSSID); } else { throw new IllegalStateException("unknown flag: " + flag); } } @Override public void onReceive(Context context, Intent intent) { if (isCanceled) { return; } final String action = intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); // WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // NetworkInfo.DetailedState state = info.getDetailedState(); // String extraInfo = info.getExtraInfo(); // Log.d(TAG, "state changed: isConnected=" + info.isConnected() + " detailedState=" + state + " extra=" + extraInfo + " wifiInfo=" + wifiInfo + " networkInfo=" + info); lastSeenSSID = info.getExtraInfo(); if (info.isConnected()) { if (wifiInfo != null) { int ipaddr = wifiInfo.getIpAddress(); // String ipaddrString = String.format("%d.%d.%d.%d", // (ipaddr & 0xff), (ipaddr >> 8 & 0xff), (ipaddr >> 16 & 0xff), (ipaddr >> 24 & 0xff)); // Log.d(TAG, "ip address: " + ipaddrString); if (ipaddr == 0) { // Empty IP address. Still wait. return; } } if (wifiInfo != null) { String currentSSID = wifiInfo.getSSID(); if (matchesSSID(currentSSID, targetSSID)) { // Connected to target Wi-Fi synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onTargetWifiConnected(wifiInfo, info); } } } } } } } else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { int errorCode = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0); // NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); // WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); // Log.d(TAG, "Supplicant state change: errorCode=" + errorCode + " ERROR_AUTHENTICATING=" + WifiManager.ERROR_AUTHENTICATING); if (errorCode == WifiManager.ERROR_AUTHENTICATING) { if (matchesSSID(lastSeenSSID, targetSSID)) { long diff = System.currentTimeMillis() - startTime; Log.e(TAG, "Wifi authentication failed (count=" + authFailedCount + " diff=" + diff + "ms)"); if (++authFailedCount >= 2) { synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onError("Authentication failed"); } } } } if (diff >= ERROR_TIME_THRESHOLD) { synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onError("Authentication failed"); } } } } } } } } public WifiConnectionChangeListener getWifiConnectionChangeListener() { return wifiConnectionChangeListener; } public void setWifiConnectionChangeListener(WifiConnectionChangeListener wifiConnectionChangeListener) { this.wifiConnectionChangeListener = wifiConnectionChangeListener; } } private static class WifiEnableEventReceiver extends BroadcastReceiver { public static final String TAG = WifiEnableEventReceiver.class.getSimpleName(); private interface WifiEnableEventReceiverListener { public void onWifiEnabled(); } private WifiEnableEventReceiverListener listener; private boolean isStopped = false; public WifiEnableEventReceiverListener getListener() { return listener; } public void setListener(WifiEnableEventReceiverListener listener) { this.listener = listener; } public void stop() { isStopped = true; } @Override public void onReceive(Context context, Intent intent) { if (isStopped) { return; } int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1); if (wifiState == WifiManager.WIFI_STATE_ENABLED) { if (listener != null) { listener.onWifiEnabled(); } } } } private static class ScanResultReceiver extends BroadcastReceiver { public static final String TAG = ScanResultReceiver.class.getSimpleName(); private boolean isStopped; private WifiManager wifiManager; private IRKitWifiScanResultListener irkitWifiScanResultListener; public ScanResultReceiver(WifiManager wifiManager) { this.wifiManager = wifiManager; isStopped = false; } @Override public void onReceive(Context context, Intent intent) { if (isStopped) { return; } List<ScanResult> results = wifiManager.getScanResults(); if (results != null) { for (ScanResult result : results) { if (IRWifiInfo.isIRKitWifi(result)) { if (irkitWifiScanResultListener != null) { irkitWifiScanResultListener.onIRKitWifiFound(result); return; } } } } if (!isStopped) { wifiManager.startScan(); } } public void stopScan() { isStopped = true; } public IRKitWifiScanResultListener getIRKitWifiScanResultListener() { return irkitWifiScanResultListener; } public void setIRKitWifiScanResultListener(IRKitWifiScanResultListener irKitWifiScanResultListener) { this.irkitWifiScanResultListener = irKitWifiScanResultListener; } } }
package uk.org.opentrv.ETV.parse; import java.io.IOException; import java.io.LineNumberReader; import java.io.Reader; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.SortedMap; import java.util.TimeZone; import java.util.TreeMap; import uk.org.opentrv.ETV.ETVPerHouseholdComputation.ETVPerHouseholdComputationInputKWh; /**Get heating fuel energy consumption (kWh) by whole local days (local midnight-to-midnight) from bulk data. * Days may not be contiguous. * <p> * Extracts from bulk data from the secondary meter provider. * <p> * The ID to extract data for has to be supplied to the constructor. * <p> * Format sample, initial few lines: <pre> house_id,received_timestamp,device_timestamp,energy,temperature 1002,1456790560,1456790400,306.48,-3 1002,1456791348,1456791300,306.48,-3 1002,1456792442,1456792200,306.48,-3 </pre> * <p> * No assumption is made about ordering by house_id, * but values for a given house ID must be in rising order by device_timestamp. * <p> * <ul> * <li>energy is assumed to be in kWh (cumulative)</li> * <li>device_timestamp is assumed to be in UTC seconds</li> * </ul> */ public final class NBulkKWHParseByID implements ETVPerHouseholdComputationInputKWh { /**Default time zone assumed for this data for UK based homes. */ public static final TimeZone DEFAULT_NB_TIMEZONE = TimeZone.getTimeZone("Europe/London"); /**Maximum number of minutes tolerance (before local midnight) to accept reading; range [1,59]. * Note that even reading mid-evening once per day or once per week is probably OK too! * But given the nature of this data we can insist on a better fit to HDD data. */ public static final int EPSILON_MIN = 30; /**Extract set of all distinct (non-negative integer) IDs in the supplied data. * @param r bulk input data, close()d by by this routine on completion; never null * @return set of distinct non-negative house IDs; may be empty but never null */ public static final Set<Integer> extractIDs(final Reader r) throws IOException { if(null == r) { throw new IllegalArgumentException(); } final Set<Integer> result = new HashSet<>(); // Wrap with a by-line reader and arrange to close() when done... try(final LineNumberReader l = new LineNumberReader(r)) { final String header = l.readLine(); if(null == header) { throw new IOException("missing header row"); } final String hf[] = header.split(","); if(hf.length < 5) { throw new IOException("too few fields in header row"); } if((hf[0].length() > 0) && (Character.isDigit(hf[0].charAt(0)))) { throw new IOException("leading numeric not text in header row"); } // Read data rows just to extract the house ID [0]. String row; while(null != (row = l.readLine())) { final String rf[] = row.split(","); if(rf.length < 4) { throw new IOException("too few fields in row " + l.getLineNumber()); } result.add(Integer.parseInt(rf[0], 10)); } }; return(result); } /**House/meter ID to filter for; +ve. */ private final int meterID; /**Reader for CSV; never null but may be closed. */ private final Reader r; /**Time zone of house; never null. */ private final TimeZone tz; /**Create instance with the house/meter ID to filter for and CSV input Reader. * Reader will be closed by getKWHByLocalDay() * so this is one shot and a new instance of this class * is needed if the data is to be read again. */ public NBulkKWHParseByID(final int meterID, final Reader r, final TimeZone tz) { if(meterID < 0) { throw new IllegalArgumentException(); } if(null == r) { throw new IllegalArgumentException(); } if(null == tz) { throw new IllegalArgumentException(); } this.meterID = meterID; this.r = r; this.tz = tz; } /**Create instance with the house/meter ID to filter for and CSV input Reader and default UK time zone. * Reader will be closed by getKWHByLocalDay() * so this is one shot and a new instance of this class * is needed if the data is to be read again. */ public NBulkKWHParseByID(final int meterID, final Reader r) { this(meterID, r, DEFAULT_NB_TIMEZONE); } /**Interval heating fuel consumption (kWh) by whole local days; never null. * @return never null though may be empty * @throws IOException in case of failure, eg parse problems */ @Override public SortedMap<Integer, Float> getKWhByLocalDay() throws IOException { // Read first line, usually: // house_id,received_timestamp,device_timestamp,energy,temperature // Simply check that the header exists, has (at least) 5 fields, and does not start with a digit. // An empty file is not acceptable (ie indicates a problem). final SortedMap<Integer, Float> result = new TreeMap<>(); // Wrap with a by-line reader and arrange to close() when done... try(final LineNumberReader l = new LineNumberReader(r)) { final String header = l.readLine(); if(null == header) { throw new IOException("missing header row"); } final String hf[] = header.split(","); if(hf.length < 5) { throw new IOException("too few fields in header row"); } if((hf[0].length() > 0) && (Character.isDigit(hf[0].charAt(0)))) { throw new IOException("leading numeric not text in header row"); } // Avoid multiple parses of ID; check with a String comparison. final String sID = Integer.toString(meterID); // Read data rows... // Filter by house ID [0], use device_timestamp [2] and energy [3]. // This will need to accumulate energy for an entire day in the local time zone, // taking the last value from the previous day from the last value for the current day, // both values needing to be acceptably close to (ie possibly just after) midnight. String row; int currentDayYYYYMMDD = -1; Float kWhAtStartOfCurrentDay = null; final Calendar latestDeviceTimestamp = Calendar.getInstance(tz); latestDeviceTimestamp.setTime(new Date(0)); while(null != (row = l.readLine())) { // Explicitly skip repeats of the header line (at least starting with the correct field). if("house_id,".startsWith(row)) { continue; } // Now split into columns. final String rf[] = row.split(","); if(rf.length < 4) { throw new IOException("too few fields in row " + l.getLineNumber()); } if(!sID.equals(rf[0])) { continue; } final long device_timestamp = Long.parseLong(rf[2], 10); final float energy = Float.parseFloat(rf[3]); final long dtsms = 1000L * device_timestamp; // Verify that device time moves monotonically forwards... if((-1 != currentDayYYYYMMDD) && (dtsms <= latestDeviceTimestamp.getTimeInMillis())) { throw new IOException("device time not increased at row " + l.getLineNumber() + ": " + row + " vs " + latestDeviceTimestamp); } // Now convert to local date (and time) allowing for time zone. // Measurement days are local midnight to local midnight. latestDeviceTimestamp.setTimeInMillis(dtsms); final int todayYYYYMMDD = (latestDeviceTimestamp.get(Calendar.YEAR)*10000) + ((latestDeviceTimestamp.get(Calendar.MONTH)+1)*100) + (latestDeviceTimestamp.get(Calendar.DAY_OF_MONTH)); final boolean newDay = (todayYYYYMMDD != currentDayYYYYMMDD); if(newDay) { // Rolled directly to following day with no gap? // final boolean followingDay = ((-1 != currentDayYYYYMMDD) && // (((currentDayYYYYMMDD+1) == todayYYYYMMDD) || // (1 == Util.daysBetweenDateKeys(currentDayYYYYMMDD, todayYYYYMMDD)))); // Sufficiently close to start of day to treat as midnight // for computing a day interval energy consumption? final boolean closeEnoughToStartOfDay = ((0 == latestDeviceTimestamp.get(Calendar.HOUR_OF_DAY)) && (EPSILON_MIN >= latestDeviceTimestamp.get(Calendar.MINUTE))); if(!closeEnoughToStartOfDay) { // If not close enough to use, just null the 'start of day' reading. kWhAtStartOfCurrentDay = null; } else { // If the start-of-day value is present then compute the interval. if(null != kWhAtStartOfCurrentDay) { final float dayUse = energy - kWhAtStartOfCurrentDay; result.put(currentDayYYYYMMDD, dayUse); } kWhAtStartOfCurrentDay = energy; } // In any case, note the new day. currentDayYYYYMMDD = todayYYYYMMDD; } // final SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd-HH:mm"); // fmt.setCalendar(latestDeviceTimestamp); // final String dateFormatted = fmt.format(latestDeviceTimestamp.getTime()); //System.out.println(dateFormatted); } } return(result); } }
package ru.job4j.lists; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * SortUserTest. * @author Sergey Artemov * @since 16.12.2017 * @version 1 */ public class SortUser { Set<User> sort(List<User> listUsers) { TreeSet setList = new TreeSet<User>(); Iterator<User> iter = listUsers.iterator(); while (iter.hasNext()) { setList.add(iter.next()); } return setList; } List<User> sortByNameLength(List<User> userList) { userList.sort(new Comparator<User>() { @Override public int compare(User u1, User u2) { int len1 = u1.getName().length(); int len2 = u2.getName().length(); return (len1 > len2 ? 1 : (len1 < len2 ? -1 : u2.getId() - u1.getId())); } }); return userList; } List<User> sortByAllFields(List<User> userList) { userList.sort(new Comparator<User>() { @Override public int compare(User u1, User u2) { int ordName = u1.getName().compareTo(u2.getName()); int ordAge = (u1.getAge() - u2.getAge()) / Math.abs(u1.getAge() - u2.getAge()); int ord = (ordName != 0 ? ordName : (ordAge != 0 ? ordAge : u2.getId() - u1.getId())); return ord; } }); return userList; } }
package ru.job4j; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.ThreadSafe; /** * Class Count. * * @author Alexander Mezgin * @version 1.0 * @since 06.08.2017 */ @ThreadSafe public class Count { /** * The value. */ @GuardedBy("this") private int value; /** * This method increment the value. */ public void increment() { synchronized (this) { this.value++; } } /** * This method return value. * * @return value. */ public int getValue() { synchronized (this) { return this.value; } } }
package interface_objects; import java.util.List; public class AnalysisResult { private String[] assignedEpoch; private String[] timePointPath; private int timePointPathSize; private List<OutputElement> elementList; public String[] getAssignedEpoch() { return assignedEpoch; } public String[] getTimePointPath() { return timePointPath; } public int getTimePointPathSize() { return timePointPathSize; } public List<OutputElement> getElementList() { return elementList; } }
package de.bitbrain.braingdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.utils.Pool; import java.util.ArrayList; import java.util.List; import de.bitbrain.braingdx.graphics.CameraTracker; import de.bitbrain.braingdx.graphics.RenderManager; /** * Game world which contains all game objects and managed them. * * @since 1.0.0 * @version 1.0.0 * @author Miguel Gonzalez <miguel-gonzalez@gmx.de> */ public class GameWorld { /** the default cache size this world uses */ public static final int DEFAULT_CACHE_SIZE = 100; public static interface WorldBounds { boolean isInBounds(GameObject object, OrthographicCamera camera); } private final List<GameObject> removals = new ArrayList<GameObject>(); private final List<GameObject> objects = new ArrayList<GameObject>(); private final Pool<GameObject> pool; private WorldBounds bounds = new WorldBounds() { @Override public boolean isInBounds(GameObject object, OrthographicCamera camera) { return true; } }; private OrthographicCamera camera; private RenderManager renderManager; private CameraTracker tracker; public GameWorld(OrthographicCamera camera) { this(camera, DEFAULT_CACHE_SIZE); } public GameWorld(OrthographicCamera camera, int cacheSize) { this.camera = camera; renderManager = new RenderManager(); tracker = new CameraTracker(camera); pool = new Pool<GameObject>(cacheSize) { @Override protected GameObject newObject() { return new GameObject(); } }; } /** * Sets the bounds of the world. By default, everything is in bounds. * * @param bounds the new bounds implementation */ public void setBounds(WorldBounds bounds) { this.bounds = bounds; } /** * Adds a new game object to the game world and provides it. * * @return newly created game object */ public GameObject addObject() { GameObject object = pool.obtain(); objects.add(object); return object; } /** * Registers a renderer for an existing game object of the given type (id) * * @param gameObjectId type/id of the game object * @param renderer instance of the renderer */ public void registerRenderer(Integer gameObjectId, RenderManager.Renderer renderer) { renderManager.register(gameObjectId, renderer); } /** * Enables camera tracking for the given object. Tracking can be disabled by providing null. * * @param object game object shich should be tracked. */ public void setCameraTracking(GameObject object) { tracker.setTarget(object); } /** * Focuses the camera on its target (if available) */ public void focusCamera() { tracker.focus(); } /** * Sets the speed the camera should follow its target * * @param speed camera tracking speed */ public void setTrackingSpeed(float speed) { tracker.setSpeed(speed); } /** * Sets the zoom scale the camera should have while following its target * * @param scale scale factor of the camera while tracking a target */ public void setTrackingZoomScale(float scale) { tracker.setZoomScale(scale); } /** * Updates and renders this world * * @param batch the batch * @param delta frame delta */ public void updateAndRender(Batch batch, float delta) { for (GameObject object : objects) { if (!bounds.isInBounds(object, camera)) { removals.add(object); continue; } renderManager.render(object, batch, delta); } tracker.update(delta); for (GameObject removal : removals) { remove(removal); } removals.clear(); } /** * Number of active objects in the world * * @return */ public int size() { return objects.size(); } /** * Resets this world object */ public void reset() { pool.clear(); objects.clear(); removals.clear(); } /** * Removes the given game objects from this world * * @param objects */ public void remove(GameObject... objects) { for (GameObject object : objects) { removals.add(object); } } private void remove(GameObject object) { pool.free(object); objects.remove(object); } }
import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.io.*; import java.util.*; import java.util.regex.*; public class Factoid { public Factoid() { } public Factoid(String subject, boolean fact, String info, String nick) { this.subject = subject; this.fact = fact; this.info = info; this.nick = nick; this.reads = 0; this.date = System.currentTimeMillis(); } public int id; public String subject; public boolean fact; public String info; public String nick; public int reads; public long date; } public class FactoidEnumerator { public FactoidEnumerator() { } public FactoidEnumerator(String enumSource, int index, int count) { this.enumSource = enumSource; this.index = index; this.count = count; this.lastUsed = System.currentTimeMillis(); } public int getNext() { index++; if (index >= count) { index = 0; } lastUsed = System.currentTimeMillis(); return index; } public int id; public String enumSource; public int index; public int count; public long lastUsed; } class FactoidParsed { public FactoidParsed(String subject, String definition) { this.subject = subject; this.definition = definition; } public String subject; public String definition; } class FactoidSearch { public FactoidSearch(String subject) { this.subject = subject; this.search = ""; } public FactoidSearch(String subject, String search) { this.subject = subject; this.search = search; if (this.search == null) this.search = ""; } public String subject; public String search; } class FactoidSearchData { public FactoidSearch search; public List<Factoid> definitions; } public class Factoids2 { public String[] info() { return new String[] { "Stores, recalls and collects facts and rumours.", "The Choob Team", "choob@uwcs.co.uk", "$Rev$$Date$" }; } private static long ENUM_TIMEOUT = 5 * 60 * 1000; // 5 minutes // Subjects to not auto-learn from. private final static Set<String> subjectExclusions = new HashSet<String>(); static { subjectExclusions.add("also"); subjectExclusions.add("cant"); subjectExclusions.add("could"); subjectExclusions.add("dont"); subjectExclusions.add("just"); subjectExclusions.add("might"); subjectExclusions.add("must"); subjectExclusions.add("should"); subjectExclusions.add("something"); subjectExclusions.add("someone"); subjectExclusions.add("that"); subjectExclusions.add("there"); subjectExclusions.add("they"); subjectExclusions.add("this"); subjectExclusions.add("thing"); subjectExclusions.add("what"); subjectExclusions.add("where"); subjectExclusions.add("when"); subjectExclusions.add("which"); subjectExclusions.add("will"); subjectExclusions.add("would"); } private final static String splitWords = "is|was|am|be|can|can't|cant|cannot"; private Modules mods; private IRCInterface irc; private Pattern filterFactoidsPattern; private Pattern filterQuestionPatter; private Pattern addDefinitionPattern; private Pattern quotedSearchPattern; private Pattern regexpSearchPattern; public Factoids2(Modules mods, IRCInterface irc) { this.mods = mods; this.irc = irc; filterFactoidsPattern = Pattern.compile(filterFactoidsRegex); filterQuestionPatter = Pattern.compile(".*\\?\\s*"); addDefinitionPattern = Pattern.compile("\\s*(?i:that\\s+)?(.+?)\\s+((?i:" + splitWords + ")\\s+.+)\\s*"); quotedSearchPattern = Pattern.compile("\\s*\"([^\"]+)\"(?:\\s+(.*))?\\s*"); regexpSearchPattern = Pattern.compile("\\s*(.+?)\\s+(/([^/]+|\\/)+/)\\s*"); mods.interval.callBack(null, 60000, 1); } private int countFacts(List<Factoid> definitions) { int factCount = 0; for (int i = 0; i < definitions.size(); i++) { Factoid defn = definitions.get(i); if (defn.fact) { factCount++; } } return factCount; } private int countRumours(List<Factoid> definitions) { int rumourCount = 0; for (int i = 0; i < definitions.size(); i++) { Factoid defn = definitions.get(i); if (!defn.fact) { rumourCount++; } } return rumourCount; } private Factoid pickDefinition(List<Factoid> definitions, String enumSource) { if (countFacts(definitions) > 0) return pickFact(definitions, enumSource); return pickRumour(definitions, enumSource); } private Factoid pickFact(List<Factoid> definitions, String enumSource) { return pickDefinition(definitions, true, countFacts(definitions), enumSource); } private Factoid pickRumour(List<Factoid> definitions, String enumSource) { return pickDefinition(definitions, false, countRumours(definitions), enumSource); } private Factoid pickDefinition(List<Factoid> definitions, boolean fact, int count, String enumSource) { int index = -1; enumSource = enumSource.toLowerCase(); List<FactoidEnumerator> enums = mods.odb.retrieve(FactoidEnumerator.class, "WHERE enumSource = '" + mods.odb.escapeString(enumSource) + "'"); FactoidEnumerator fEnum = null; if (enums.size() >= 1) { fEnum = enums.get(0); if (fEnum.count != count) { // Count has changed: invalidated! mods.odb.delete(fEnum); fEnum = null; } else { // Alright, step to the next one. index = fEnum.getNext(); mods.odb.update(fEnum); } } if (fEnum == null) { // No enumerator, pick random start and create one. index = (int)Math.floor(Math.random() * count); fEnum = new FactoidEnumerator(enumSource, index, count); mods.odb.save(fEnum); } Factoid rvDefn = null; for (int i = 0; i < definitions.size(); i++) { Factoid defn = definitions.get(i); if (defn.fact == fact) { if (index == 0) { rvDefn = defn; break; } index } } return rvDefn; } private List<Factoid> getDefinitions(FactoidSearch factoidSearch) { String subject = factoidSearch.subject.toLowerCase(); String search = factoidSearch.search; String odbQuery = "WHERE subject = '" + mods.odb.escapeString(subject) + "'"; if (search.length() > 0) { if (search.startsWith("/") && search.endsWith("/")) { // Regexp odbQuery += " AND info RLIKE \"" + mods.odb.escapeString(search.substring(1, search.length() - 1)) + "\""; } else { // Substring odbQuery += " AND info LIKE \"%" + mods.odb.escapeString(search) + "%\""; } } return mods.odb.retrieve(Factoid.class, odbQuery); } // Get a subject + definition from the message params. private FactoidParsed getParsedFactoid(Message mes) { String[] params1 = mods.util.getParamArray(mes, 2); if (params1.length <= 2) { return null; } String[] params2 = mods.util.getParamArray(mes, 1); // If they have used is/are, split on that. Matcher mIsAre = addDefinitionPattern.matcher(params2[1]); if (mIsAre.matches()) { return new FactoidParsed(mIsAre.group(1), mIsAre.group(2)); } // Default to first word + rest split. return new FactoidParsed(params1[1], params1[2]); } // Get a subject + optional search from the message params. private FactoidSearch getFactoidSearch(Message mes) { String[] params1 = mods.util.getParamArray(mes, 2); if (params1.length == 2) { return new FactoidSearch(params1[1]); } if (params1.length <= 1) { return null; } String[] params2 = mods.util.getParamArray(mes, 1); // If they have used quotes, split on that. Matcher mQuoted = quotedSearchPattern.matcher(params2[1]); if (mQuoted.matches()) { return new FactoidSearch(mQuoted.group(1), mQuoted.group(2)); } // If there's a regexp search, split on that. Matcher mRegExp = regexpSearchPattern.matcher(params2[1]); if (mRegExp.matches()) { return new FactoidSearch(mRegExp.group(1), mRegExp.group(2)); } // If they have used is/are, split on that. Matcher mIsAre = addDefinitionPattern.matcher(params2[1]); if (mIsAre.matches()) { return new FactoidSearch(mIsAre.group(1), mIsAre.group(2)); } // Default to first word + rest split. return new FactoidSearch(params1[1], params1[2]); } private FactoidSearchData getFactoidSearchDefinitions(Message mes) { FactoidSearchData data = new FactoidSearchData(); // Try to parse the params into search data. data.search = getFactoidSearch(mes); if (data.search == null) { // Gah, didn't parse at all! return null; } // Get matching definitions while we're here. data.definitions = getDefinitions(data.search); if (data.definitions.size() == 0) { // Nothing with the normal parser, try the entire thing quoted just in case. String[] params = mods.util.getParamArray(mes, 1); FactoidSearch search = new FactoidSearch(params[1]); List<Factoid> definitions = getDefinitions(search); // Something did match when quoted - pretend that's what the user asked for originally. if (definitions.size() > 0) { data.search = search; data.definitions = definitions; } } return data; } // Interval public void interval(Object param) { // Clean up dead enumerators. long lastUsedCutoff = System.currentTimeMillis() - ENUM_TIMEOUT; List<FactoidEnumerator> deadEnums = mods.odb.retrieve(FactoidEnumerator.class, "WHERE lastUsed < " + lastUsedCutoff); for (int i = 0; i < deadEnums.size(); i++) { mods.odb.delete(deadEnums.get(i)); } mods.interval.callBack(null, 60000, 1); } // Collect and store rumours for things. public String filterFactoidsRegex = "(\\w{4,})\\s+((?i:" + splitWords + ")\\s+.{4,})"; public void filterFactoids(Message mes) throws ChoobException { // Only capture channel messages. if (!(mes instanceof ChannelMessage)) { return; } Matcher rMatcher = filterFactoidsPattern.matcher(mes.getMessage()); if (rMatcher.matches()) { String subject = rMatcher.group(1).toLowerCase(); String defn = rMatcher.group(2); // Exclude questions from the data. Matcher questionMatcher = filterQuestionPatter.matcher(defn); if (questionMatcher.matches()) { return; } // We don't auto-learn about some things. if (subjectExclusions.contains(subject)) return; Factoid rumour = new Factoid(subject, false, defn, mes.getNick()); mods.odb.save(rumour); // Remove oldest so we only have the 5 most recent. List<Factoid> results = mods.odb.retrieve(Factoid.class, "WHERE fact = 0 AND subject = '" + mods.odb.escapeString(subject) + "' SORT DESC date"); for (int i = 5; i < results.size(); i++) { Factoid oldRumour = (Factoid)results.get(i); mods.odb.delete(oldRumour); } } } // Get some simple stats. public String[] helpCommandStats = { "Returns some (maybe) interesting statistics from the factoids system.", "[<term> [" + splitWords + "] [<search>]]", "<term> is the term to get stats for", "<search> limits the removal to only matching defintions, if multiple ones exist (substring or regexp allowed)" }; public void commandStats(Message mes) { FactoidSearchData data = getFactoidSearchDefinitions(mes); if (data == null) { data = new FactoidSearchData(); data.definitions = mods.odb.retrieve(Factoid.class, ""); } if ((data.search != null) && (data.definitions.size() == 1)) { Factoid defn = data.definitions.get(0); irc.sendContextReply(mes, "Factoid for '" + data.search.subject + "' is a " + (defn.fact ? "fact" : "rumour") + (defn.fact ? " added by " : " collected from ") + defn.nick + " and displayed " + defn.reads + " time" + (defn.reads != 1 ? "s":"") + "."); } else { int factCount = countFacts(data.definitions); int rumourCount = countRumours(data.definitions); if (data.search != null) { irc.sendContextReply(mes, data.definitions.size() + " factoid" + (data.definitions.size() != 1 ? "s":"") + " matched, containing " + factCount + " fact" + (factCount != 1 ? "s":"") + " and " + rumourCount + " rumour" + (rumourCount != 1 ? "s":"") + "."); } else { irc.sendContextReply(mes, "Factoids database contains " + factCount + " fact" + (factCount != 1 ? "s":"") + " and " + rumourCount + " rumour" + (rumourCount != 1 ? "s":"") + "."); } } } // Manually add facts to the system. public String[] helpCommandAdd = { "Add a new factual definition for a term.", "<term> [" + splitWords + "] <defn>", "<term> is the term to which the definition applies", "<defn> is the definition itself" }; public void commandAdd(Message mes) { FactoidParsed factoid = getParsedFactoid(mes); if (factoid == null) { irc.sendContextReply(mes, "Syntax: 'Factoids2.Add " + helpCommandAdd[1] + "'"); return; } Factoid fact = new Factoid(factoid.subject, true, factoid.definition, mes.getNick()); mods.odb.save(fact); irc.sendContextReply(mes, "Added definition for '" + factoid.subject + "'."); } // Remove facts from the system. public String[] helpCommandRemove = { "Remove factual definitions for a term.", "<term> [" + splitWords + "] [<search>]", "<term> is the term to remove", "<search> limits the removal to only matching defintions, if multiple ones exist (substring or regexp allowed)" }; public void commandRemove(Message mes) { FactoidSearchData data = getFactoidSearchDefinitions(mes); if (data == null) { irc.sendContextReply(mes, "Syntax: 'Factoids2.Remove " + helpCommandRemove[1] + "'"); return; } int count = 0; for (int i = 0; i < data.definitions.size(); i++) { Factoid defn = data.definitions.get(i); if (defn.fact) { mods.odb.delete(defn); count++; } } if (count > 1) { irc.sendContextReply(mes, count + " factual definitions for '" + data.search.subject + "' removed."); } else if (count == 1) { irc.sendContextReply(mes, "1 factual definition for '" + data.search.subject + "' removed."); } else { irc.sendContextReply(mes, "No factual definitions for '" + data.search.subject + "' found."); } } // Retrieve definitions from the system. public String[] helpCommandGet = { "Returns a definition for a term.", "<term> [" + splitWords + "] [<search>]", "<term> is the term to define", "<search> limits the definition(s) given, if multiple ones exist (substring or regexp allowed)" }; public void commandGet(Message mes) throws ChoobException { FactoidSearchData data = getFactoidSearchDefinitions(mes); if (data == null) { irc.sendContextReply(mes, "Syntax: 'Factoids2.Get " + helpCommandGet[1] + "'"); return; } if (data.definitions.size() == 0) { irc.sendContextReply(mes, "Sorry, I don't know anything about '" + data.search.subject + "'!"); } else { int factCount = countFacts(data.definitions); int rumourCount = countRumours(data.definitions); if (factCount > 0) { Factoid fact = pickFact(data.definitions, mes.getContext() + ":" + data.search.subject); fact.reads++; mods.odb.update(fact); if (factCount > 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (" + (factCount - 1) + " other defns)"); } else if (factCount == 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (1 other defn)"); } else { irc.sendContextReply(mes, fact.subject + " " + fact.info); } } else { Factoid rumour = pickRumour(data.definitions, mes.getContext() + ":" + data.search.subject); rumour.reads++; mods.odb.update(rumour); if (rumourCount > 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (" + (rumourCount - 1) + " other rumours)"); } else if (rumourCount == 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (1 other rumour)"); } else { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info); } } } } public String[] helpCommandGetFact = { "Returns a factual definition for a term.", "<term> [" + splitWords + "] [<search>]", "<term> is the term to define", "<search> limits the definition(s) given, if multiple ones exist (substring or regexp allowed)" }; public void commandGetFact(Message mes) throws ChoobException { FactoidSearchData data = getFactoidSearchDefinitions(mes); if (data == null) { irc.sendContextReply(mes, "Syntax: 'Factoids2.GetFact " + helpCommandGetFact[1] + "'"); return; } if (data.definitions.size() == 0) { irc.sendContextReply(mes, "Sorry, I don't know anything about '" + data.search.subject + "'!"); } else { int factCount = countFacts(data.definitions); if (factCount > 0) { Factoid fact = pickFact(data.definitions, mes.getContext() + ":" + data.search.subject); fact.reads++; mods.odb.update(fact); if (factCount > 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (" + (factCount - 1) + " other defns)"); } else if (factCount == 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (1 other defn)"); } else { irc.sendContextReply(mes, fact.subject + " " + fact.info); } } else { irc.sendContextReply(mes, "Sorry, I don't have any facts about '" + data.search.subject + "'."); } } } public String[] helpCommandGetRumour = { "Returns a rumour for a term.", "<term> [" + splitWords + "] [<search>]", "<term> is the term to define", "<search> limits the definition(s) given, if multiple ones exist (substring or regexp allowed)" }; public void commandGetRumour(Message mes) throws ChoobException { FactoidSearchData data = getFactoidSearchDefinitions(mes); if (data == null) { irc.sendContextReply(mes, "Syntax: 'Factoids2.GetRumour " + helpCommandGetRumour[1] + "'"); return; } if (data.definitions.size() == 0) { irc.sendContextReply(mes, "Sorry, I don't know anything about '" + data.search.subject + "'!"); } else { int rumourCount = countRumours(data.definitions); if (rumourCount > 0) { Factoid rumour = pickRumour(data.definitions, mes.getContext() + ":" + data.search.subject); rumour.reads++; mods.odb.update(rumour); if (rumourCount > 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (" + (rumourCount - 1) + " other rumours)"); } else if (rumourCount == 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (1 other rumour)"); } else { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info); } } else { irc.sendContextReply(mes, "Sorry, I don't have any rumours about '" + data.search.subject + "'."); } } } public String[] helpCommandRandomRumour = { "Returns a completely random rumour.", "" }; public void commandRandomRumour(Message mes) throws ChoobException { List<Factoid> list = mods.odb.retrieve(Factoid.class, "WHERE fact = 0 ORDER BY RAND() LIMIT 1"); if (list.size() == 0) { irc.sendContextReply(mes, "Oh dear, I don't have any rumours!"); } else { Factoid rumour = list.get(0); irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info); } } public void webStats(PrintWriter out, String args, String[] from) { try { out.println("HTTP/1.0 200 OK"); out.println("Content-Type: text/html"); out.println(); if (args.length() > 0) { out.println("<H1>Factoid &quot;" + args + "&quot;</H1>"); } else { out.println("<H1>Factoid Summary</H1>"); } FactoidSearchData data = new FactoidSearchData(); if (args.length() > 0) { data.search = new FactoidSearch(args); data.definitions = getDefinitions(data.search); } else { data.definitions = mods.odb.retrieve(Factoid.class, ""); } int factCount = countFacts(data.definitions); int rumourCount = countRumours(data.definitions); if (data.search != null) { out.println(data.definitions.size() + " factoid" + (data.definitions.size() != 1 ? "s":"") + " matched, containing " + factCount + " fact" + (factCount != 1 ? "s":"") + " and " + rumourCount + " rumour" + (rumourCount != 1 ? "s":"") + "."); } else { out.println("Factoids database contains " + factCount + " fact" + (factCount != 1 ? "s":"") + " and " + rumourCount + " rumour" + (rumourCount != 1 ? "s":"") + "."); } if (data.search != null) { out.println(" <STYLE>"); out.println(" dd { font-size: smaller; font-style: italic; }"); out.println(" </STYLE>"); out.println(" <DL>"); for (int i = 0; i < data.definitions.size(); i++) { Factoid defn = data.definitions.get(i); out.println(" <DT>&quot;" + defn.subject + " " + defn.info + "&quot;</DT>"); out.println(" <DD>" + (defn.fact ? "Fact" : "Rumour") + (defn.fact ? " added by " : " collected from ") + defn.nick + " and displayed " + defn.reads + " time" + (defn.reads != 1 ? "s":"") + ".</DD>"); } out.println(" </DL>"); } } catch (Exception e) { out.println("ERROR!"); e.printStackTrace(); } } }
package org.spine3.protobuf; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.TextFormat; import com.google.protobuf.util.JsonFormat; import org.spine3.protobuf.error.MissingDescriptorException; import org.spine3.protobuf.error.UnknownTypeException; import org.spine3.type.ClassName; import org.spine3.type.TypeName; import org.spine3.util.Exceptions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.propagate; import static com.google.protobuf.Descriptors.Descriptor; import static com.google.protobuf.Descriptors.GenericDescriptor; /** * Utility class for working with {@link Message} objects. * * @author Mikhail Melnik * @author Mikhail Mikhaylov * @author Alexander Yevsyukov */ public class Messages { @SuppressWarnings("DuplicateStringLiteralInspection") // This constant is used in generated classes. private static final String METHOD_GET_DESCRIPTOR = "getDescriptor"; private Messages() {} /** * Wraps {@link Message} object inside of {@link Any} instance. * * @param message message that should be put inside the {@link Any} instance. * @return the instance of {@link Any} object that wraps given message. */ public static Any toAny(Message message) { return Any.pack(message); } /** * Creates a new instance of {@link Any} with the message represented by its byte * content and the passed type. * * @param type the type of the message to be wrapped into {@code Any} * @param value the byte content of the message * @return new {@code Any} instance */ public static Any toAny(TypeName type, ByteString value) { final String typeUrl = type.toTypeUrl(); final Any result = Any.newBuilder() .setValue(value) .setTypeUrl(typeUrl) .build(); return result; } /** * Unwraps {@link Any} value into an instance of type specified by value * returned by {@link Any#getTypeUrl()}. * * <p>If there is no Java class for the type, {@link UnknownTypeException} * will be thrown. * * @param any instance of {@link Any} that should be unwrapped * @param <T> the type enclosed into {@code Any} * @return unwrapped message instance * @throws UnknownTypeException if there is no Java class in the classpath for the enclosed type */ public static <T extends Message> T fromAny(Any any) { checkNotNull(any); T result = null; String typeStr = ""; try { final TypeName typeName = TypeName.ofEnclosed(any); typeStr = typeName.value(); final Class<T> messageClass = toMessageClass(typeName); result = any.unpack(messageClass); } catch (ClassNotFoundException ignored) { throw new UnknownTypeException(typeStr); } catch (InvalidProtocolBufferException e) { propagate(e); } return result; } /** * Returns message {@link Class} for the given Protobuf message type. * * <p>This method is temporary until full support of {@link Any} is provided. * * @param messageType full type name defined in the proto files * @return message class * @throws ClassNotFoundException in case there is no corresponding class for the given Protobuf message type * @see #fromAny(Any) that uses the same convention */ public static <T extends Message> Class<T> toMessageClass(TypeName messageType) throws ClassNotFoundException { final ClassName className = TypeToClassMap.get(messageType); @SuppressWarnings("unchecked") final Class<T> result = (Class<T>) Class.forName(className.value()); return result; } /** * Prints the passed message into well formatted text. * * @param message the message object * @return text representation of the passed message */ public static String toText(Message message) { checkNotNull(message); final String result = TextFormat.printToString(message); return result; } /** * Converts passed message into Json representation. * * @param message the message object * @return Json string */ public static String toJson(Message message) { checkNotNull(message); String result = null; try { result = JsonPrinter.instance().print(message); } catch (InvalidProtocolBufferException e) { propagate(e); } checkState(result != null); return result; } /** * Builds and returns the registry of types known in the application. * * @return {@code JsonFormat.TypeRegistry} instance * @see TypeToClassMap#knownTypes() */ public static JsonFormat.TypeRegistry forKnownTypes() { final JsonFormat.TypeRegistry.Builder builder = JsonFormat.TypeRegistry.newBuilder(); for (TypeName typeName : TypeToClassMap.knownTypes()) { try { final Class<? extends Message> clazz = toMessageClass(typeName); final GenericDescriptor descriptor = getClassDescriptor(clazz); // Skip outer class descriptors. if (descriptor instanceof Descriptor) { final Descriptor typeDescriptor = (Descriptor) descriptor; builder.add(typeDescriptor); } } catch (ClassNotFoundException e) { propagate(e); } } return builder.build(); } private enum JsonPrinter { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final JsonFormat.Printer value = JsonFormat.printer().usingTypeRegistry(forKnownTypes()); private static com.google.protobuf.util.JsonFormat.Printer instance() { return INSTANCE.value; } } /** * Returns descriptor for the passed message class. */ public static GenericDescriptor getClassDescriptor(Class<? extends Message> clazz) { try { final Method method = clazz.getMethod(METHOD_GET_DESCRIPTOR); final GenericDescriptor result = (GenericDescriptor) method.invoke(null); return result; } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { //noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException throw new MissingDescriptorException(clazz, e.getCause()); } } public static Class<?> getFieldClass(FieldDescriptor fieldDescriptor) { final FieldDescriptor.JavaType javaType = fieldDescriptor.getJavaType(); Object defaultObject = null; switch (javaType) { case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: case BYTE_STRING: defaultObject = fieldDescriptor.getDefaultValue(); return defaultObject.getClass(); case ENUM: //TODO:2016-06-17:alexander.yevsyukov: Figure out how to treat enums. throw Exceptions.unsupported( "Enums in mapping are not yet supported. Discovered: " + fieldDescriptor.getFullName()); case MESSAGE: final Descriptor messageType = fieldDescriptor.getMessageType(); final TypeName typeName = TypeName.of(messageType); try { final Class<? extends Message> result = toMessageClass(typeName); return result; } catch (ClassNotFoundException e) { propagate(e); } break; } throw new IllegalStateException("Unknown field type discovered: " + fieldDescriptor.getFullName()); } }
package xyz.elmot.oscill; import com.sun.javafx.collections.ObservableListWrapper; import com.sun.javafx.webkit.WebConsoleListener; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.image.Image; import javafx.scene.input.KeyCombination; import javafx.scene.layout.BorderPane; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Stage; import netscape.javascript.JSObject; import java.io.BufferedReader; import java.io.StringReader; import java.util.Arrays; import static xyz.elmot.oscill.Main.PORT_NAME; public class BrowserMain extends Application { private final static CommFacility<FrameData> commFacility = new CommFacility<>(FrameData::newFrameData); private final long[] frameTimes = new long[20]; private int frameTimeIndex = 0; private boolean arrayFilled = false; private WebEngine webEngine; private Oscilloscope oscilloscope; private JSObject jsDataToDraw; private JSObject jsWindow; @Override public void start(Stage stage) throws Exception { stage.getIcons().add(new Image(BrowserMain.class.getResourceAsStream("icon_128.png"))); AnimationTimer frameRateMeter = new AnimationTimer() { @Override public void handle(long now) { long oldFrameTime = frameTimes[frameTimeIndex]; frameTimes[frameTimeIndex] = now; frameTimeIndex = (frameTimeIndex + 1) % frameTimes.length; if (frameTimeIndex == 0) { arrayFilled = true; } if (arrayFilled) { long elapsedNanos = now - oldFrameTime; long elapsedNanosPerFrame = elapsedNanos / frameTimes.length; double frameRate = 1_000_000_000.0 / elapsedNanosPerFrame; stage.setTitle(String.format("Oscilloscope. FPS: %.3f", frameRate)); } } }; frameRateMeter.start(); stage.setOnCloseRequest(event -> { try { commFacility.giveUp(); stop(); } catch (Exception e) { e.printStackTrace(); } }); stage.setTitle("Oscilloscope"); stage.setFullScreenExitKeyCombination(KeyCombination.keyCombination("F11")); WebView webView = createWebView(); ChoiceBox<String> ports = new ChoiceBox<>(); listPortsToChoiceBox(ports); ports.setValue(PORT_NAME); ports.onShowingProperty().set(e -> listPortsToChoiceBox(ports)); BorderPane root = new BorderPane(webView, ports, null, null, null); Scene scene = new Scene(root); decorateStage(stage, scene); stage.setScene(scene); stage.setOnCloseRequest(event -> Platform.exit()); stage.show(); } private void listPortsToChoiceBox(ChoiceBox<String> ports) { ports.setItems( new ObservableListWrapper<>(Arrays.asList(CommFacility.ports()) )); } private WebView createWebView() { WebConsoleListener.setDefaultListener( (webView1, message, lineNumber, sourceId) -> System.err.printf("%s[%d]: %s\n\r", sourceId, lineNumber, message)); WebView webView = new WebView(); webView.setContextMenuEnabled(false); webEngine = webView.getEngine(); webEngine.setOnAlert(event -> System.out.println("Alert: " + event.getData())); webEngine.setJavaScriptEnabled(true); webEngine.getLoadWorker().stateProperty().addListener((ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState) -> { if (newState == Worker.State.SUCCEEDED) { jsWindow = (JSObject) webEngine.executeScript("window"); oscilloscope = new Oscilloscope(); jsWindow.setMember("osc", oscilloscope); jsDataToDraw = (JSObject) webEngine.executeScript("[]"); commFacility.setPortStatusConsumer(this::showStatus); commFacility.setPortName(PORT_NAME); new FxUpdate().start(); } }); webEngine.load(BrowserMain.class.getResource("content.html").toExternalForm()); return webView; } private void showStatus(String text, Boolean connected) { printStatus(text, connected); Platform.runLater(() -> jsWindow.call("showStatus", connected ? "" : text) ); } @SuppressWarnings("unused") private void decorateStage(Stage stage, Scene scene) { // stage.initStyle(StageStyle.TRANSPARENT); // stage.setFullScreen(true); scene.setFill(null); // scene.getStylesheets().add("root.css"); } public static void main(String[] args) { try { launch(args); } finally { commFacility.giveUp(); } } private static void printStatus(String text, boolean connected) { System.err.println((connected ? "CONNECTED: " : "DISCONNECTED: ") + text); } private class FxUpdate extends AnimationTimer{ private int configDelayCounter = 0; @Override public void handle(long now) { try { if (configDelayCounter++ == 10) { configDelayCounter = 0; String conf = commFacility.getCommandResponse("CONF"); try (BufferedReader reader = new BufferedReader(new StringReader(conf))) { for (String s; (s = reader.readLine()) != null; ) { int eqPos = s.indexOf('='); if (eqPos < 1) continue; String name = s.substring(0, eqPos); String value = s.substring(eqPos + 1); jsWindow.call("updateGuiControl", name, value); } } } FrameData frame = commFacility.getDataResponse(); if (frame != null) { int serieIndex = frame.type == FrameData.TYPE.TRIGGERED ? 1 : 0; for (int i = 0; i < frame.data.length; i++) { int index = i * 2 + serieIndex; jsDataToDraw.setSlot(index, frame.data[i]); } jsWindow.call("drawData", jsDataToDraw); } } catch (Exception e) { e.printStackTrace(); } } } public class Oscilloscope { @SuppressWarnings("unused") public void sendCommand(String cmd) { commFacility.getCommandResponse(cmd); } } }
package replicant; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import replicant.spy.DataLoadStatus; import static org.testng.Assert.*; @SuppressWarnings( "ResultOfMethodCallIgnored" ) public class DataLoadActionTest extends AbstractReplicantTest { @Test public void construct() { final String rawJsonData = ""; final boolean oob = false; final DataLoadAction action = new DataLoadAction( rawJsonData, oob ); assertEquals( action.getRawJsonData(), rawJsonData ); assertEquals( action.isOob(), oob ); assertEquals( action.areEntityLinksCalculated(), false ); assertEquals( action.areEntityLinksPending(), false ); assertEquals( action.areChangesPending(), false ); assertEquals( action.hasWorldBeenNotified(), false ); assertEquals( action.getChannelAddCount(), 0 ); assertEquals( action.getChannelUpdateCount(), 0 ); assertEquals( action.getChannelRemoveCount(), 0 ); assertEquals( action.getEntityUpdateCount(), 0 ); assertEquals( action.getEntityRemoveCount(), 0 ); assertEquals( action.getEntityLinkCount(), 0 ); } @SuppressWarnings( "EqualsWithItself" ) @Test public void compareTo() { final DataLoadAction action1 = new DataLoadAction( "", false ); final DataLoadAction action2 = new DataLoadAction( "", false ); final DataLoadAction action3 = new DataLoadAction( "", true ); final DataLoadAction action4 = new DataLoadAction( "", true ); final ChangeSet changeSet1 = ChangeSet.create( 1, null, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] ); final ChangeSet changeSet2 = ChangeSet.create( 2, null, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] ); final ChangeSet changeSet3 = ChangeSet.create( 3, null, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] ); final ChangeSet changeSet4 = ChangeSet.create( 4, null, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] ); action1.setChangeSet( changeSet1, null ); action2.setChangeSet( changeSet2, null ); action3.setChangeSet( changeSet3, null ); action4.setChangeSet( changeSet4, null ); assertEquals( action1.compareTo( action1 ), 0 ); assertEquals( action1.compareTo( action2 ), -1 ); assertEquals( action1.compareTo( action3 ), 1 ); assertEquals( action1.compareTo( action4 ), 1 ); assertEquals( action2.compareTo( action1 ), 1 ); assertEquals( action2.compareTo( action2 ), 0 ); assertEquals( action2.compareTo( action3 ), 1 ); assertEquals( action2.compareTo( action4 ), 1 ); assertEquals( action3.compareTo( action1 ), -1 ); assertEquals( action3.compareTo( action2 ), -1 ); assertEquals( action3.compareTo( action3 ), 0 ); assertEquals( action3.compareTo( action4 ), 0 ); assertEquals( action4.compareTo( action1 ), -1 ); assertEquals( action4.compareTo( action2 ), -1 ); assertEquals( action4.compareTo( action3 ), 0 ); assertEquals( action4.compareTo( action4 ), 0 ); } @Test public void toStatus() { final int sequence = ValueUtil.randomInt(); final String requestId = ValueUtil.randomString(); final ChangeSet changeSet = ChangeSet.create( sequence, requestId, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] ); final DataLoadAction action = new DataLoadAction( ValueUtil.randomString(), ValueUtil.randomBoolean() ); action.setChangeSet( changeSet, null ); action.incChannelAddCount(); action.incChannelAddCount(); action.incChannelRemoveCount(); action.incChannelRemoveCount(); action.incChannelRemoveCount(); action.incChannelUpdateCount(); action.incEntityUpdateCount(); action.incEntityRemoveCount(); action.incEntityRemoveCount(); action.incEntityLinkCount(); final DataLoadStatus status = action.toStatus(); assertEquals( status.getSequence(), sequence ); assertEquals( status.getRequestId(), requestId ); assertEquals( status.getChannelAddCount(), 2 ); assertEquals( status.getChannelUpdateCount(), 1 ); assertEquals( status.getChannelRemoveCount(), 3 ); assertEquals( status.getEntityUpdateCount(), 1 ); assertEquals( status.getEntityRemoveCount(), 2 ); assertEquals( status.getEntityLinkCount(), 1 ); } @Test public void incIgnoredUnlessSpyEnabled() { ReplicantTestUtil.disableSpies(); final DataLoadAction action = new DataLoadAction( ValueUtil.randomString(), ValueUtil.randomBoolean() ); assertEquals( action.getChannelAddCount(), 0 ); assertEquals( action.getChannelUpdateCount(), 0 ); assertEquals( action.getChannelRemoveCount(), 0 ); assertEquals( action.getEntityUpdateCount(), 0 ); assertEquals( action.getEntityRemoveCount(), 0 ); assertEquals( action.getEntityLinkCount(), 0 ); // We enforce this to make it easier for DCE action.incChannelAddCount(); action.incChannelRemoveCount(); action.incChannelUpdateCount(); action.incEntityUpdateCount(); action.incEntityRemoveCount(); action.incEntityLinkCount(); assertEquals( action.getChannelAddCount(), 0 ); assertEquals( action.getChannelUpdateCount(), 0 ); assertEquals( action.getChannelRemoveCount(), 0 ); assertEquals( action.getEntityUpdateCount(), 0 ); assertEquals( action.getEntityRemoveCount(), 0 ); assertEquals( action.getEntityLinkCount(), 0 ); } @Test public void testToString() { final DataLoadAction action = new DataLoadAction( ValueUtil.randomString(), ValueUtil.randomBoolean() ); assertEquals( action.toString(), "DataLoad[,RawJson.null?=false,ChangeSet.null?=true,ChangeIndex=0,Runnable.null?=true,UpdatedEntities.size=0,RemovedEntities.size=0,EntitiesToLink.size=null,EntityLinksCalculated=false]" ); final int sequence = 33; final String requestId = "XXX"; final ChangeSet changeSet = ChangeSet.create( sequence, requestId, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] ); action.setChangeSet( changeSet, null ); assertEquals( action.toString(), "DataLoad[,RawJson.null?=true,ChangeSet.null?=false,ChangeIndex=0,Runnable.null?=true,UpdatedEntities.size=0,RemovedEntities.size=0,EntitiesToLink.size=null,EntityLinksCalculated=false]" ); action.calculateEntitiesToLink(); assertEquals( action.toString(), "DataLoad[,RawJson.null?=true,ChangeSet.null?=false,ChangeIndex=0,Runnable.null?=true,UpdatedEntities.size=null,RemovedEntities.size=null,EntitiesToLink.size=0,EntityLinksCalculated=true]" ); ReplicantTestUtil.disableNames(); assertEquals( action.toString(), "replicant.DataLoadAction@" + Integer.toHexString( System.identityHashCode( action ) ) ); } /* @DataProvider( name = "actionDescriptions" ) public Object[][] actionDescriptions() { final List<Boolean> flags = Arrays.asList( Boolean.TRUE, Boolean.FALSE ); final ArrayList<Object[]> objects = new ArrayList<>(); for ( final boolean normalCompletion : flags ) { for ( final boolean useRunnable : flags ) { for ( final boolean isLinkableEntity : flags ) { for ( final boolean oob : flags ) { for ( final boolean update : flags ) { final boolean expectLink = isLinkableEntity && update; final EntityChange changeUpdate = EntityChange.create( ValueUtil.randomInt(), ValueUtil.randomInt(), new EntityChannel[ 0 ], update ? JsPropertyMap.of() : null ); final TestChangeSet changeSet = new TestChangeSet( ChangeSet.create( ValueUtil.randomInt(), null, null, new ChannelChange[ 0 ], new EntityChange[]{ changeUpdate } ), useRunnable ? new MockRunner() : null ); final Object entity = isLinkableEntity ? new MockLinkable() : new Object(); objects.add( new Object[]{ normalCompletion, oob, changeSet, entity, expectLink } ); } final boolean expectLink = false; final EntityChange changeUpdate = EntityChange.create( ValueUtil.randomInt(), ValueUtil.randomInt(), new EntityChannel[ 0 ], JsPropertyMap.of() ); final EntityChange changeRemove = EntityChange.create( ValueUtil.randomInt(), ValueUtil.randomInt(), new EntityChannel[ 0 ], null ); final ChangeSet cs = ChangeSet.create( ValueUtil.randomInt(), ValueUtil.randomString(), null, new ChannelChange[ 0 ], new EntityChange[]{ changeUpdate, changeRemove } ); final TestChangeSet changeSet = new TestChangeSet( cs, useRunnable ? new MockRunner() : null ); final Object entity = isLinkableEntity ? new MockLinkable() : new Object(); objects.add( new Object[]{ normalCompletion, oob, changeSet, entity, expectLink } ); } } } } return objects.toArray( new Object[ objects.size() ][] ); } @Test( dataProvider = "actionDescriptions" ) public void verifyActionLifecycle( final boolean normalCompletion, final boolean oob, final TestChangeSet changeSet, final Object entity, final boolean expectedLink ) { final MockRunner runnable = (MockRunner) changeSet.getRunnable(); final DataLoadAction action = new DataLoadAction( "BLAH", oob ); //Ensure the initial state is as expected assertEquals( action.getRawJsonData(), "BLAH" ); assertEquals( action.getChangeSet(), null ); if ( null != runnable ) { assertEquals( runnable.getRunCount(), 0 ); } assertEquals( action.areEntityLinksCalculated(), false ); assertEquals( action.areEntityLinksPending(), false ); assertEquals( action.areChangesPending(), false ); assertEquals( action.hasWorldBeenNotified(), false ); if ( oob ) { action.setRunnable( changeSet.getRunnable() ); action.setChangeSet( changeSet.getChangeSet(), null ); } else { final String requestID = changeSet.getChangeSet().getRequestID(); assertNotNull( requestID ); final RequestEntry request = new RequestEntry( requestID, "MyOperation", null ); if ( normalCompletion ) { request.setNormalCompletionAction( runnable ); } else { request.setNonNormalCompletionAction( runnable ); } action.setChangeSet( changeSet.getChangeSet(), request ); } assertEquals( action.getRunnable(), runnable ); assertEquals( action.getChangeSet(), changeSet.getChangeSet() ); assertEquals( action.getRawJsonData(), null ); assertEquals( action.areChangesPending(), true ); final EntityChange change = action.nextChange(); assertNotNull( change ); assertEquals( change, changeSet.getChangeSet().getChange( 0 ) ); action.changeProcessed( change.isUpdate(), entity ); if ( 1 == changeSet.getChangeSet().getChangeCount() ) { assertEquals( action.areChangesPending(), false ); } else { while ( action.areChangesPending() ) { final EntityChange nextChange = action.nextChange(); assertNotNull( nextChange ); action.changeProcessed( nextChange.isUpdate(), entity ); } } assertEquals( action.areEntityLinksCalculated(), false ); action.calculateEntitiesToLink(); assertEquals( action.areEntityLinksCalculated(), true ); if ( expectedLink ) { assertEquals( action.areEntityLinksPending(), true ); assertEquals( action.nextEntityToLink(), entity ); assertEquals( action.areEntityLinksPending(), false ); } else { assertEquals( action.areEntityLinksPending(), false ); } assertEquals( action.hasWorldBeenNotified(), false ); action.markWorldAsNotified(); assertEquals( action.hasWorldBeenNotified(), true ); } static final class MockRunner implements Runnable { private int _runCount; int getRunCount() { return _runCount; } @Override public void run() { _runCount++; } @Override public String toString() { return "Listener:" + System.identityHashCode( this ); } } static final class MockLinkable implements Linkable { @Override public void link() { } @Override public String toString() { return "Entity:" + System.identityHashCode( this ); } } */ }
package org.jetel.util; import org.jetel.enums.EdgeTypeEnum; import org.jetel.graph.Edge; public class SubgraphUtils { /** Type of SubgraphInput component. */ public static final String SUBGRAPH_INPUT_TYPE = "SUBGRAPH_INPUT"; /** Type of SubgraphOutput component. */ public static final String SUBGRAPH_OUTPUT_TYPE = "SUBGRAPH_OUTPUT"; /** Type of SubjobflowInput component. */ public static final String SUBJOBFLOW_INPUT_TYPE = "SUBJOBFLOW_INPUT"; /** Type of SubjobflowOutput component. */ public static final String SUBJOBFLOW_OUTPUT_TYPE = "SUBJOBFLOW_OUTPUT"; /** Type of Subgraph component. */ public static final String SUBGRAPH_TYPE = "SUBGRAPH"; /** Type of Subjobflow component. */ public static final String SUBJOBFLOW_TYPE = "SUBJOBFLOW"; /** the name of an XML attribute used to pass a URL specified the executed subgraph */ public static final String XML_JOB_URL_ATTRIBUTE = "jobURL"; /** * Name of single type of component property (and graph parameters) for fileURL. * Graph parameters with this type is handled in special way in Subgraph component. * Relative paths are converted to absolute, see Subgraph.applySubgraphParameter(). */ public static final String FILE_URL_SINGLE_TYPE = "file"; /** * Prefix of custom attributes of Subgraph component. */ public static final String CUSTOM_SUBGRAPH_ATTRIBUTE_PREFIX = "__"; /** * @return true if and only if the given component type is SubgraphInput or SubjobflowInput component. */ public static boolean isSubJobInputComponent(String componentType) { return SUBGRAPH_INPUT_TYPE.equals(componentType) || SUBJOBFLOW_INPUT_TYPE.equals(componentType); } /** * @return true if and only if the given component type is SubgraphOutput or SubjobflowOutput component. */ public static boolean isSubJobOutputComponent(String componentType) { return SUBGRAPH_OUTPUT_TYPE.equals(componentType) || SUBJOBFLOW_OUTPUT_TYPE.equals(componentType); } /** * @return true if and only if the given component type is {@link #isSubJobInputComponent(String)} or {@link #isSubJobOutputComponent(String)} */ public static boolean isSubJobInputOutputComponent(String componentType) { return isSubJobInputComponent(componentType) || isSubJobOutputComponent(componentType); } /** * @return true if and only if the given component type is Subgraph or Subjobflow component. */ public static boolean isSubJobComponent(String componentType) { return SUBGRAPH_TYPE.equals(componentType) || SUBJOBFLOW_TYPE.equals(componentType); } /** * Checks whether output edge of SubgraphInput component can share EdgeBase * with corresponding edge in parent graph. In regular cases, it is possible and * highly recommended due performance gain. But in case edge debugging is turned on, * sharing is not possible. Remote and phase edges cannot be shared as well. * @param subgraphEdge an output edge from SubgraphInput component * @param parentGraphEdge corresponding edge from parent graph * @return true if and only if the edge base from parentEdge can be shared with localEdge */ public static boolean isSubgraphInputEdgeShared(Edge subgraphEdge, Edge parentGraphEdge) { return subgraphEdge.getGraph().getRuntimeJobType().isSubJob() && subgraphEdge.getGraph().getRuntimeJobType().isGraph() //jobflows do not share edges to avoid distorted logging of token tracked && !subgraphEdge.isDebugMode() && subgraphEdge.getEdgeType() != EdgeTypeEnum.L_REMOTE; } /** * Checks whether input edge of SubgraphOutput component can share EdgeBase * with corresponding edge in parent graph. In regular cases, it is possible and * highly recommended due performance gain. But in case edge debugging is turned on, * sharing is not possible. Phase edges cannot be shared as well. * @param subgraphEdge an input edge from SubgraphOutput component * @param parentEdge corresponding edge from parent graph * @return true if and only if the edge base from parentEdge can be shared with localEdge */ public static boolean isSubgraphOutputEdgeShared(Edge subgraphEdge, Edge parentGraphEdge) { return subgraphEdge.getGraph().getRuntimeJobType().isSubJob() && subgraphEdge.getGraph().getRuntimeJobType().isGraph() //jobflows do not share edges to avoid distorted logging of token tracked && !parentGraphEdge.isDebugMode() && !SubgraphUtils.isSubJobInputComponent(subgraphEdge.getWriter().getType()); //edges directly interconnect SubgraphInput and SubgraphOutput cannot be share from both sides } /** * Checks whether the given attribute name has "__foo" format, * which is indication of custom subgraph attribute * @return true if the given name of an attribute is custom subgraph attribute (prefixed with double underscores) */ public static boolean isCustomSubgraphAttribute(String attributeName) { return attributeName.startsWith(CUSTOM_SUBGRAPH_ATTRIBUTE_PREFIX); } /** * Converts the given name of custom subgraph attribute to name of respective * public graph parameter. */ public static String getPublicGraphParameterName(String customSubgraphAttribute) { return customSubgraphAttribute.substring(CUSTOM_SUBGRAPH_ATTRIBUTE_PREFIX.length()); } /** * Converts the given name of public graph parameter to respective * name of custom subgraph attribute. */ public static String getCustomSubgraphAttribute(String publicGraphParameterName) { return CUSTOM_SUBGRAPH_ATTRIBUTE_PREFIX + publicGraphParameterName; } }
package utilities; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import resources.network.BaselineBuilder.Encodable; public class Encoder { public static byte[] encode(Object object) { return encode(object, StringType.UNSPECIFIED); } public static byte[] encode(Object object, StringType strType) { if (strType != StringType.UNSPECIFIED) { switch (strType) { case ASCII: return encodeAscii((String) object); case UNICODE: return encodeUnicode((String) object); default: break; } } else { if (object instanceof Encodable) { return encodeObject((Encodable) object); } else if (object instanceof Integer) { return encodeInteger((Integer) object); } else if (object instanceof Long) { return encodeLong((Long) object); } else if (object instanceof Short) { return encodeShort((Short) object); } else if (object instanceof Byte) { return encodeByte((Byte) object); } else if (object instanceof Boolean) { return encodeBoolean((boolean) object); } else if (object instanceof Float || object instanceof Double) { return encodeFloat(object); } else if (object instanceof String){ throw new UnsupportedOperationException("You must specify a String type!"); } else { System.err.println("[Encoder] Do not know how to encode instance type " + object.getClass().getName()); } } return null; } public static byte[] encodeObject(Encodable encodable) { return encodable.encode(); } private static byte[] encodeFloat(Object object) { ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); buffer.putFloat((object instanceof Float ? (Float) object : ((Double) object).floatValue())); return buffer.array(); } private static byte[] encodeByte(Byte object) { return new byte[]{(object.byteValue())}; } private static byte[] encodeBoolean(boolean object) { return encodeByte((byte) (object ? 1 : 0)); } public static byte[] encodeShort(Short object) { ByteBuffer buffer = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN); buffer.putShort(object); return buffer.array(); } public static byte[] encodeInteger(int integer) { ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(integer); return buffer.array(); } public static byte[] encodeLong(long l) { ByteBuffer buffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(l); return buffer.array(); } public static byte[] encodeAscii(String string) { ByteBuffer buffer = ByteBuffer.allocate(2 + string.length()).order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) string.length()); buffer.put(string.getBytes(Charset.forName("UTF-8"))); return buffer.array(); } public static byte[] encodeUnicode(String string) { ByteBuffer buffer = ByteBuffer.allocate(4 + (string.length() * 2)).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(string.length()); buffer.put(string.getBytes(Charset.forName("UTF-16LE"))); return buffer.array(); } public enum StringType { UNSPECIFIED, ASCII, UNICODE } }