answer
stringlengths
17
10.2M
package com.xtremelabs.droidsugar.fakes; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import com.xtremelabs.droidsugar.util.Implements; import java.lang.reflect.Method; @SuppressWarnings({"UnusedDeclaration"}) @Implements(Dialog.class) public class FakeDialog { public static FakeDialog latestDialog; private Dialog realDialog; private boolean isShowing; public Context context; public int layoutId; public int themeId; private View inflatedView; public boolean hasBeenDismissed; private DialogInterface.OnDismissListener onDismissListener; public static void reset() { latestDialog = null; } public FakeDialog(Dialog dialog) { realDialog = dialog; } public void __constructor__(Context context, int themeId) { this.context = context; this.themeId = themeId; latestDialog = this; } public void setContentView(int layoutResID) { layoutId = layoutResID; } public void show() { isShowing = true; try { Method onCreateMethod = Dialog.class.getDeclaredMethod("onCreate", Bundle.class); onCreateMethod.setAccessible(true); onCreateMethod.invoke(realDialog, (Bundle) null); } catch (Exception e) { throw new RuntimeException(e); } } public void hide() { isShowing = false; } public boolean isShowing() { return isShowing; } public void dismiss() { isShowing = false; hasBeenDismissed = true; if (onDismissListener != null) { onDismissListener.onDismiss(realDialog); } } public View findViewById(int viewId) { if (layoutId > 0 && context != null) { if (inflatedView == null) { inflatedView = FakeContextWrapper.resourceLoader.viewLoader.inflateView(context, layoutId); } return inflatedView.findViewById(viewId); } return null; } public void clickOn(int viewId) { findViewById(viewId).performClick(); } public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) { this.onDismissListener = onDismissListener; } }
package org.commcare.suite.model; import org.commcare.core.parse.UserXmlParser; import org.commcare.data.xml.DataModelPullParser; import org.commcare.data.xml.TransactionParser; import org.commcare.data.xml.TransactionParserFactory; import org.commcare.xml.CommCareElementParser; import org.javarosa.core.io.StreamsUtil; import org.javarosa.core.model.User; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.Reference; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.PropertyUtils; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * User restore xml file sometimes present in apps. * Used for offline (demo user) logins. * * @author Phillip Mates (pmates@dimagi.com) * @author Aliza Stone (astone@dimagi.com) */ public class OfflineUserRestore implements Persistable { public static final String STORAGE_KEY = "OfflineUserRestore"; private int recordId = -1; private String restore; private String reference; private String username; private String password; public OfflineUserRestore() { } public OfflineUserRestore(String reference) throws UnfullfilledRequirementsException, IOException, InvalidStructureException, XmlPullParserException, InvalidReferenceException { this.reference = reference; checkThatRestoreIsValid(); this.password = PropertyUtils.genUUID(); } public static OfflineUserRestore buildInMemoryUserRestore(InputStream restoreStream) throws UnfullfilledRequirementsException, IOException, InvalidStructureException, XmlPullParserException { OfflineUserRestore offlineUserRestore = new OfflineUserRestore(); byte[] restoreBytes = StreamsUtil.inputStreamToByteArray(restoreStream); offlineUserRestore.restore = new String(restoreBytes); offlineUserRestore.checkThatRestoreIsValid(); offlineUserRestore.password = PropertyUtils.genUUID(); return offlineUserRestore; } public InputStream getRestoreStream() { if (reference != null) { // user restore xml was installed to a file return getStreamFromReference(); } else { // user restore xml was installed in memory (CLI) return getInMemoryStream(); } } private InputStream getInMemoryStream() { try { return new ByteArrayInputStream(restore.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private InputStream getStreamFromReference() { try { Reference local = ReferenceManager._().DeriveReference(reference); return local.getStream(); } catch (IOException | InvalidReferenceException e) { throw new RuntimeException(e); } } public String getReference() { return reference; } public String getUsername() { return username; } public String getPassword() { return password; } @Override public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { this.recordId = ExtUtil.readInt(in); this.reference = ExtUtil.nullIfEmpty(ExtUtil.readString(in)); this.restore = ExtUtil.nullIfEmpty(ExtUtil.readString(in)); this.username = ExtUtil.nullIfEmpty(ExtUtil.readString(in)); this.password = ExtUtil.nullIfEmpty(ExtUtil.readString(in)); } @Override public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeNumeric(out, recordId); ExtUtil.writeString(out, ExtUtil.emptyIfNull(reference)); ExtUtil.writeString(out, ExtUtil.emptyIfNull(restore)); ExtUtil.writeString(out, ExtUtil.emptyIfNull(username)); ExtUtil.writeString(out, ExtUtil.emptyIfNull(password)); } @Override public void setID(int ID) { recordId = ID; } @Override public int getID() { return recordId; } private void checkThatRestoreIsValid() throws UnfullfilledRequirementsException, IOException, InvalidStructureException, XmlPullParserException { TransactionParserFactory factory = new TransactionParserFactory() { @Override public TransactionParser getParser(KXmlParser parser) { String name = parser.getName(); if ("registration".equals(name.toLowerCase())) { return buildUserParser(parser); } return null; } }; DataModelPullParser parser = new DataModelPullParser(getRestoreStream(), factory, true, false); parser.parse(); } private TransactionParser buildUserParser(KXmlParser parser) { return new UserXmlParser(parser) { @Override protected void commit(User parsed) throws IOException, UnfullfilledRequirementsException { if (!parsed.getUserType().equals(User.TYPE_DEMO)) { throw new UnfullfilledRequirementsException( "Demo user restore file must be for a user with user_type set to demo", CommCareElementParser.SEVERITY_PROMPT); } if ("".equals(parsed.getUsername()) || parsed.getUsername() == null) { throw new UnfullfilledRequirementsException( "Demo user restore file must specify a username in the Registration block", CommCareElementParser.SEVERITY_PROMPT); } else { OfflineUserRestore.this.username = parsed.getUsername(); } } @Override public User retrieve(String entityId) { return null; } }; } }
package dashteacup.pman; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; /** * Class for making sure that I have my encryption library set up properly for * my application. These tests should not cover any of my code, they ensure the * java encryption functionality works as expected. These tests should be run * when checking for portability on other platforms. The tests also serve as a * helpful reminder of how to use the JCA. */ public class JavaEncryptionSettingsTest { /** * Size of the key used by the encryption algorithm. */ private static final int KEY_SIZE = 256; /** * Algorithm used to generate the keys for my encryption algorithm. */ private static final String KEYGEN_ALG = "PBKDF2WithHmacSHA1"; /** * Transformation used by my ciphers to encrypt/decrypt data. */ private static final String CIPHER_TRANSFORM = "AES/CBC/PKCS5PADDING"; /** * My application will be using 256 bit AES keys, so I need to verify that the * java installation supports this. If you don't have the JCE Unlimited Strength * Jurisdiction Policy Files installed then you will be limited to 128 bit * AES because of US export restrictions. */ @Test public void aesKeyLengthIs256BitsOrMore() { int keyLength = 0; try { keyLength = Cipher.getMaxAllowedKeyLength("AES"); } catch (NoSuchAlgorithmException e) { fail(e.getMessage()); } assertTrue(keyLength >= KEY_SIZE); } /** * Encrypt and then decrypt a message with AES. The result should be the * same as what you started with. This test only exists to verify that basic * AES functionality exists and does not reflect the way it will be used in * the program. */ @Test public void basicAesEncryptAndDecrypt() { final String keyText = "1234567890123456"; // 16 bits final byte[] key = keyText.getBytes(); // convert to bytes final String messageText = "The cat in the hat"; final byte[] message = messageText.getBytes(); try { // Create the encrypted message Cipher encrypt = Cipher.getInstance("AES"); // I use SecretKeySpec to generate a SecretKey without worrying // about what provider to use. SecretKeySpec encryptKey = new SecretKeySpec(key, "AES"); encrypt.init(Cipher.ENCRYPT_MODE, encryptKey); byte[] encryptedData = encrypt.doFinal(message); // Let's use another instance of all these things to simulate // doing this on another run of the application Cipher decrypt = Cipher.getInstance("AES"); SecretKeySpec decryptKey = new SecretKeySpec(key, "AES"); decrypt.init(Cipher.DECRYPT_MODE, decryptKey); byte[] decryptedData = decrypt.doFinal(encryptedData); String decryptedMessage = new String(decryptedData); assertEquals(messageText, decryptedMessage); } catch (Exception e) { fail(e.getMessage()); } } /** * Check Java's support for the Password-Based Key Derivation Function 2 * (PBKDF2). More simply, check if I can generate a key from a password, use * that key to encrypt some text with 256-bit AES, and decrypt the message * with the same password. */ @Test public void passwordEncryptionUsingPBKDF2() { final String messageText = "Hello, world!"; final byte[] message = messageText.getBytes(); // Note it's a char[] since PBEKey expects it. Also, although it doesn't // matter here, passwords shouldn't be stored as strings because strings // are immutable. final char[] password = "alpha1".toCharArray(); // Salt is fixed in this test, but should not be so in the app final byte[] salt = "12345".getBytes(); final int iterations = 60000; // number of times the password will be hashed try { SecretKeySpec encryptKey = PBESecretKeySpec(password, salt, iterations, KEY_SIZE); Cipher encryptor = Cipher.getInstance(CIPHER_TRANSFORM); encryptor.init(Cipher.ENCRYPT_MODE, encryptKey); byte[] cypherText = encryptor.doFinal(message); byte[] IV = encryptor.getIV(); // I don't reuse keys to simulate separate invocations of the App. SecretKeySpec decryptKey = PBESecretKeySpec(password, salt, iterations, KEY_SIZE); Cipher decryptor = Cipher.getInstance(CIPHER_TRANSFORM); decryptor.init(Cipher.DECRYPT_MODE, decryptKey, new IvParameterSpec(IV)); byte[] plainText = decryptor.doFinal(cypherText); String decryptedMessage = new String(plainText); assertEquals(messageText, decryptedMessage); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * Confirm that the generated IV (Initialization Vector) is the appropriate * size for my chosen algorithm. It should be 128 bits, the same as the * block size for AES. */ @Test public void aesIVSize() { try { SecretKeySpec key = PBESecretKeySpec("cat".toCharArray(), "dog".getBytes(), 6000, KEY_SIZE); Cipher encryptor = Cipher.getInstance(CIPHER_TRANSFORM); encryptor.init(Cipher.ENCRYPT_MODE, key); byte[] IV = encryptor.getIV(); // IV should be 16 bytes long (128 bits) assertEquals(IV.length, 16); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * Confirm that I can securely generate a 16-bit blob of random data. I will * use this to generate salts for each password file. */ @Test public void secureRandomFunctionality() { SecureRandom rand = new SecureRandom(); byte[] arr = new byte[16]; rand.nextBytes(arr); String str = new String(arr); assertEquals(16, str.length()); } /** * Generates a new {@link SecretKeySpec} via Password Based Encryption. This * interface mirrors {@link PBEKeySpec}, but returns the right kind of * {@link KeySpec} for my algorithm. * @param password - the password. * @param salt - the salt. * @param iterationCount - the iteration count. * @param keyLength - the to-be-derived key length. * @return a {@link SecretKeySpec} suitable for use with my encryption algorithm. * @throws NoSuchAlgorithmException - if it can't use the key generating algorithm. * @throws InvalidKeySpecException - if something goes horribly wrong with the JCA. */ private SecretKeySpec PBESecretKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException { // PBEKeySpec won't return a SecretKey, so I have to jump through // hoops to get everything to the right type. KeySpec baseKey = new PBEKeySpec(password, salt, iterationCount, keyLength); // Cannot use AES with SecretKeyFactory.getInstance. // I'd prefer to use something like PBKDF2WithHmacSHA256 or // PBEWithHmacSHA256AndAES_256 instead of PBKDF2WithHmacSHA1 but // the last is what my version of java supports out of the box. SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALG); SecretKey secretKey = factory.generateSecret(baseKey); return new SecretKeySpec(secretKey.getEncoded(), "AES"); } }
package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.net.SocketException; import java.net.URI; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import android.util.Log; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; /** * OpacApi implementation for Web Opacs of the TouchPoint product, developed by * OCLC. */ public class TouchPoint extends BaseApi implements OpacApi { protected String opac_url = ""; protected JSONObject data; protected Library library; protected String CSId; protected String identifier; protected String reusehtml; protected int resultcount = 10; protected long logged_in; protected Account logged_in_as; protected final long SESSION_LIFETIME = 1000 * 60 * 3; protected String ENCODING = "UTF-8"; protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>(); static { defaulttypes.put("g", MediaType.EBOOK); defaulttypes.put("d", MediaType.CD); defaulttypes.put("Buch", MediaType.BOOK); defaulttypes.put("Bücher", MediaType.BOOK); defaulttypes.put("Printmedien", MediaType.BOOK); defaulttypes.put("Zeitschrift", MediaType.MAGAZINE); defaulttypes.put("Zeitschriften", MediaType.MAGAZINE); defaulttypes.put("zeitung", MediaType.NEWSPAPER); defaulttypes.put( "Einzelband einer Serie, siehe auch übergeordnete Titel", MediaType.BOOK); defaulttypes.put("0", MediaType.BOOK); defaulttypes.put("1", MediaType.BOOK); defaulttypes.put("2", MediaType.BOOK); defaulttypes.put("3", MediaType.BOOK); defaulttypes.put("4", MediaType.BOOK); defaulttypes.put("5", MediaType.BOOK); defaulttypes.put("6", MediaType.SCORE_MUSIC); defaulttypes.put("7", MediaType.CD_MUSIC); defaulttypes.put("8", MediaType.CD_MUSIC); defaulttypes.put("Tonträger", MediaType.CD_MUSIC); defaulttypes.put("12", MediaType.CD); defaulttypes.put("13", MediaType.CD); defaulttypes.put("CD", MediaType.CD); defaulttypes.put("DVD", MediaType.DVD); defaulttypes.put("14", MediaType.CD); defaulttypes.put("15", MediaType.DVD); defaulttypes.put("16", MediaType.CD); defaulttypes.put("audiocd", MediaType.CD); defaulttypes.put("Film", MediaType.MOVIE); defaulttypes.put("Filme", MediaType.MOVIE); defaulttypes.put("17", MediaType.MOVIE); defaulttypes.put("18", MediaType.MOVIE); defaulttypes.put("19", MediaType.MOVIE); defaulttypes.put("20", MediaType.DVD); defaulttypes.put("dvd", MediaType.DVD); defaulttypes.put("21", MediaType.SCORE_MUSIC); defaulttypes.put("Noten", MediaType.SCORE_MUSIC); defaulttypes.put("22", MediaType.BOARDGAME); defaulttypes.put("26", MediaType.CD); defaulttypes.put("27", MediaType.CD); defaulttypes.put("28", MediaType.EBOOK); defaulttypes.put("31", MediaType.BOARDGAME); defaulttypes.put("35", MediaType.MOVIE); defaulttypes.put("36", MediaType.DVD); defaulttypes.put("37", MediaType.CD); defaulttypes.put("29", MediaType.AUDIOBOOK); defaulttypes.put("41", MediaType.GAME_CONSOLE); defaulttypes.put("42", MediaType.GAME_CONSOLE); defaulttypes.put("46", MediaType.GAME_CONSOLE_NINTENDO); defaulttypes.put("52", MediaType.EBOOK); defaulttypes.put("56", MediaType.EBOOK); defaulttypes.put("96", MediaType.EBOOK); defaulttypes.put("97", MediaType.EBOOK); defaulttypes.put("99", MediaType.EBOOK); defaulttypes.put("EB", MediaType.EBOOK); defaulttypes.put("ebook", MediaType.EBOOK); defaulttypes.put("buch01", MediaType.BOOK); defaulttypes.put("buch02", MediaType.PACKAGE_BOOKS); defaulttypes.put("Medienpaket", MediaType.PACKAGE); defaulttypes.put("datenbank", MediaType.PACKAGE); defaulttypes .put("Medienpaket, Lernkiste, Lesekiste", MediaType.PACKAGE); defaulttypes.put("buch03", MediaType.BOOK); defaulttypes.put("buch04", MediaType.PACKAGE_BOOKS); defaulttypes.put("buch05", MediaType.PACKAGE_BOOKS); defaulttypes.put("Web-Link", MediaType.URL); defaulttypes.put("ejournal", MediaType.EDOC); defaulttypes.put("karte", MediaType.MAP); } public List<SearchField> getSearchFields() throws IOException, JSONException { if (!initialised) start(); String html = httpGet(opac_url + "/search.do?methodToCall=switchSearchPage&SearchType=2", ENCODING); Document doc = Jsoup.parse(html); List<SearchField> fields = new ArrayList<SearchField>(); Elements options = doc .select("select[name=searchCategories[0]] option"); for (Element option : options) { TextSearchField field = new TextSearchField(); field.setDisplayName(option.text()); field.setId(option.attr("value")); field.setHint(""); fields.add(field); } for (Element dropdown : doc.select(".accordion-body select")) { parseDropdown(dropdown, fields, doc); } return fields; } private void parseDropdown(Element dropdownElement, List<SearchField> fields, Document doc) throws JSONException { Elements options = dropdownElement.select("option"); DropdownSearchField dropdown = new DropdownSearchField(); List<Map<String, String>> values = new ArrayList<Map<String, String>>(); dropdown.setId(dropdownElement.attr("name")); // Some fields make no sense or are not supported in the app if (dropdown.getId().equals("numberOfHits") || dropdown.getId().equals("timeOut") || dropdown.getId().equals("rememberList")) return; for (Element option : options) { Map<String, String> value = new HashMap<String, String>(); value.put("key", option.attr("value")); value.put("value", option.text()); values.add(value); } dropdown.setDropdownValues(values); dropdown.setDisplayName(dropdownElement.parent().select("label").text()); fields.add(dropdown); } @Override public void start() throws ClientProtocolException, SocketException, IOException, NotReachableException { // Some libraries require start parameters for start.do, like Login=foo String startparams = ""; if (data.has("startparams")) { try { startparams = "?" + data.getString("startparams"); } catch (JSONException e) { e.printStackTrace(); } } String html = httpGet(opac_url + "/start.do" + startparams, ENCODING); initialised = true; Document doc = Jsoup.parse(html); CSId = doc.select("input[name=CSId]").val(); super.start(); } @Override public void init(Library lib) { super.init(lib); this.library = lib; this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); } catch (JSONException e) { throw new RuntimeException(e); } } public static String getStringFromBundle(Map<String, String> bundle, String key) { // Workaround for Bundle.getString(key, default) being available not // before API 12 String res = bundle.get(key); if (res == null) res = ""; return res; } protected int addParameters(Map<String, String> query, String key, String searchkey, List<NameValuePair> params, int index) { if (!query.containsKey(key) || query.get(key).equals("")) return index; if (index != 0) params.add(new BasicNameValuePair("combinationOperator[" + index + "]", "AND")); params.add(new BasicNameValuePair("searchCategories[" + index + "]", searchkey)); params.add(new BasicNameValuePair("searchString[" + index + "]", query .get(key))); return index + 1; } @Override public SearchRequestResult search(List<SearchQuery> query) throws IOException, NotReachableException, OpacErrorException, JSONException { List<NameValuePair> params = new ArrayList<NameValuePair>(); int index = 0; start(); params.add(new BasicNameValuePair("methodToCall", "submitButtonCall")); params.add(new BasicNameValuePair("CSId", CSId)); params.add(new BasicNameValuePair("methodToCallParameter", "submitSearch")); params.add(new BasicNameValuePair("refine", "false")); for (SearchQuery entry : query) { if (entry.getValue().equals("")) continue; if (entry.getSearchField() instanceof DropdownSearchField) { params.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } else { if (index != 0) params.add(new BasicNameValuePair("combinationOperator[" + index + "]", "AND")); params.add(new BasicNameValuePair("searchCategories[" + index + "]", entry.getKey())); params.add(new BasicNameValuePair( "searchString[" + index + "]", entry.getValue())); index++; } } if (index == 0) { throw new OpacErrorException( stringProvider.getString(StringProvider.NO_CRITERIA_INPUT)); } if (index > 4) { throw new OpacErrorException(stringProvider.getFormattedString( StringProvider.LIMITED_NUM_OF_CRITERIA, 4)); } params.add(new BasicNameValuePair("submitButtonCall_submitSearch", "Suchen")); params.add(new BasicNameValuePair("numberOfHits", "10")); String html = httpGet( opac_url + "/search.do?" + URLEncodedUtils.format(params, "UTF-8"), ENCODING); return parse_search(html, 1); } public SearchRequestResult volumeSearch(Map<String, String> query) throws IOException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("methodToCall", "volumeSearch")); params.add(new BasicNameValuePair("dbIdentifier", query .get("dbIdentifier"))); params.add(new BasicNameValuePair("catKey", query.get("catKey"))); params.add(new BasicNameValuePair("periodical", "N")); String html = httpGet( opac_url + "/search.do?" + URLEncodedUtils.format(params, "UTF-8"), ENCODING); return parse_search(html, 1); } @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException, OpacErrorException { if (!initialised) start(); String html = httpGet(opac_url + "/hitList.do?methodToCall=pos&identifier=" + identifier + "&curPos=" + (((page - 1) * resultcount) + 1), ENCODING); return parse_search(html, page); } protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException, IOException { Document doc = Jsoup.parse(html); if (doc.select("#RefineHitListForm").size() > 0) { // the results are located on a different page loaded via AJAX html = httpGet( opac_url + "/speedHitList.do?_=" + String.valueOf(System.currentTimeMillis() / 1000) + "&hitlistindex=0&exclusionList=", ENCODING); Log.d("opac", html); doc = Jsoup.parse(html); } if (doc.select(".nodata").size() > 0) { return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1); } doc.setBaseUri(opac_url + "/searchfoo"); int results_total = -1; String resultnumstr = doc.select(".box-header h2").first().text(); if (resultnumstr.contains("(1/1)") || resultnumstr.contains(" 1/1")) { reusehtml = html; throw new OpacErrorException("is_a_redirect"); } else if (resultnumstr.contains("(")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*\\(([0-9]+)\\).*", "$1")); } else if (resultnumstr.contains(": ")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*: ([0-9]+)$", "$1")); } Elements table = doc.select("table.data tbody tr"); identifier = null; Elements links = doc.select("table.data a"); boolean haslink = false; for (Element node : links) { if (node.hasAttr("href") & node.attr("href").contains("singleHit.do") && !haslink) { haslink = true; try { List<NameValuePair> anyurl = URLEncodedUtils.parse( new URI(node.attr("href").replace(" ", "%20") .replace("&amp;", "&")), ENCODING); for (NameValuePair nv : anyurl) { if (nv.getName().equals("identifier")) { identifier = nv.getValue(); break; } } } catch (Exception e) { e.printStackTrace(); } } } List<SearchResult> results = new ArrayList<SearchResult>(); for (int i = 0; i < table.size(); i++) { Element tr = table.get(i); SearchResult sr = new SearchResult(); if (tr.select(".type .icn").size() > 0) { String[] fparts = tr.select(".type .icn").first().attr("src") .split("/"); String fname = fparts[fparts.length - 1]; String changedFname = fname.toLowerCase(Locale.GERMAN) .replace(".jpg", "").replace(".gif", "") .replace(".png", ""); // File names can look like this: "20_DVD_Video.gif" Pattern pattern = Pattern.compile("(\\d+)_.*"); Matcher matcher = pattern.matcher(changedFname); if (matcher.find()) changedFname = matcher.group(1); MediaType defaulttype = defaulttypes.get(changedFname); if (data.has("mediatypes")) { try { sr.setType(MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname))); } catch (JSONException e) { sr.setType(defaulttype); } catch (IllegalArgumentException e) { sr.setType(defaulttype); } } else { sr.setType(defaulttype); } } if (tr.select(".cover img").size() > 0) { sr.setCover(tr.select(".cover img").attr("src")); } List<Node> children = tr.select(".results").first().childNodes(); int childrennum = children.size(); List<String[]> strings = new ArrayList<String[]>(); for (int ch = 0; ch < childrennum; ch++) { Node node = children.get(ch); if (node instanceof TextNode) { String text = ((TextNode) node).text().trim(); if (text.length() > 3) strings.add(new String[] { "text", "", text }); } else if (node instanceof Element) { List<Node> subchildren = node.childNodes(); for (int j = 0; j < subchildren.size(); j++) { Node subnode = subchildren.get(j); if (subnode instanceof TextNode) { String text = ((TextNode) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), "text", text, ((Element) node).className(), ((Element) node).attr("style") }); } else if (subnode instanceof Element) { String text = ((Element) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), ((Element) subnode).tag().getName(), text, ((Element) node).className(), ((Element) node).attr("style") }); } } } } StringBuilder description = new StringBuilder(); int k = 0; boolean yearfound = false; boolean titlefound = false; boolean sigfound = false; for (String[] part : strings) { if (part[0] == "a" && (k == 0 || !titlefound)) { if (k != 0) description.append("<br />"); description.append("<b>" + part[2] + "</b>"); titlefound = true; } else if (part[2].matches("\\D*[0-9]{4}\\D*") && part[2].length() <= 10) { yearfound = true; if (k != 0) description.append("<br />"); description.append(part[2]); } else if (k == 1 && !yearfound && part[2].matches("^\\s*\\([0-9]{4}\\)$")) { if (k != 0) description.append("<br />"); description.append(part[2]); } else if (k == 1 && !yearfound && part[2].matches("^\\s*\\([0-9]{4}\\)$")) { if (k != 0) description.append("<br />"); description.append(part[2]); } else if (k > 1 && k < 4 && !sigfound && part[0].equals("text") && part[2].matches("^[A-Za-z0-9,\\- ]+$")) { description.append("<br />"); description.append(part[2]); } if (part.length == 4) { if (part[0].equals("span") && part[3].equals("textgruen")) { sr.setStatus(SearchResult.Status.GREEN); } else if (part[0].equals("span") && part[3].equals("textrot")) { sr.setStatus(SearchResult.Status.RED); } } else if (part.length == 5) { if (part[4].contains("purple")) { sr.setStatus(SearchResult.Status.YELLOW); } } if (sr.getStatus() == null) { if ((part[2].contains("entliehen") && part[2] .startsWith("Vormerkung ist leider nicht möglich")) || part[2] .contains("nur in anderer Zweigstelle ausleihbar und nicht bestellbar")) { sr.setStatus(SearchResult.Status.RED); } else if (part[2].startsWith("entliehen") || part[2] .contains("Ein Exemplar finden Sie in einer anderen Zweigstelle")) { sr.setStatus(SearchResult.Status.YELLOW); } else if ((part[2].startsWith("bestellbar") && !part[2] .contains("nicht bestellbar")) || (part[2].startsWith("vorbestellbar") && !part[2] .contains("nicht vorbestellbar")) || (part[2].startsWith("vorbestellbar") && !part[2] .contains("nicht vorbestellbar")) || (part[2].startsWith("vormerkbar") && !part[2] .contains("nicht vormerkbar")) || (part[2].contains("heute zurückgebucht")) || (part[2].contains("ausleihbar") && !part[2] .contains("nicht ausleihbar"))) { sr.setStatus(SearchResult.Status.GREEN); } if (sr.getType() != null) { if (sr.getType().equals(MediaType.EBOOK) || sr.getType().equals(MediaType.EVIDEO) || sr.getType().equals(MediaType.MP3)) // Especially Onleihe.de ebooks are often marked // green though they are not available. sr.setStatus(SearchResult.Status.UNKNOWN); } } k++; } sr.setInnerhtml(description.toString()); sr.setNr(10 * (page - 1) + i); sr.setId(null); results.add(sr); } resultcount = results.size(); return new SearchRequestResult(results, results_total, page); } @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException { if (id == null && reusehtml != null) { DetailledItem r = parse_result(reusehtml); reusehtml = null; return r; } // Some libraries require start parameters for start.do, like Login=foo String startparams = ""; if (data.has("startparams")) { try { startparams = data.getString("startparams") + "&"; } catch (JSONException e) { e.printStackTrace(); } } String hbp = ""; if (homebranch != null) hbp = "&selectedViewBranchlib=" + homebranch; String html = httpGet(opac_url + "/start.do?" + startparams + "searchType=1&Query=0%3D%22" + id + "%22" + hbp, ENCODING); return parse_result(html); } @Override public DetailledItem getResult(int nr) throws IOException { if (reusehtml != null) { return getResultById(null, null); } String html = httpGet( opac_url + "/singleHit.do?tab=showExemplarActive&methodToCall=showHit&curPos=" + (nr + 1) + "&identifier=" + identifier, ENCODING); return parse_result(html); } protected DetailledItem parse_result(String html) throws IOException { Document doc = Jsoup.parse(html); doc.setBaseUri(opac_url); String html2 = httpGet(opac_url + "/singleHit.do?methodToCall=activateTab&tab=showTitleActive", ENCODING); Document doc2 = Jsoup.parse(html2); doc2.setBaseUri(opac_url); String html3 = httpGet( opac_url + "/singleHit.do?methodToCall=activateTab&tab=showAvailabilityActive", ENCODING); Document doc3 = Jsoup.parse(html3); doc3.setBaseUri(opac_url); DetailledItem result = new DetailledItem(); try { result.setId(doc.select("#bibtip_id").text().trim()); } catch (Exception ex) { ex.printStackTrace(); } List<String> reservationlinks = new ArrayList<String>(); for (Element link : doc3.select("#vormerkung a, #tab-content a")) { String href = link.absUrl("href"); Map<String, String> hrefq = getQueryParamsFirst(href); if (result.getId() == null) { // ID retrieval String key = hrefq.get("katkey"); if (key != null) { result.setId(key); break; } } // Vormerken if (hrefq.get("methodToCall") != null) { if (hrefq.get("methodToCall").equals("doVormerkung") || hrefq.get("methodToCall").equals("doBestellung")) reservationlinks.add(href.split("\\?")[1]); } } if (reservationlinks.size() == 1) { result.setReservable(true); result.setReservation_info(reservationlinks.get(0)); } else if (reservationlinks.size() == 0) { result.setReservable(false); } else { // TODO: Multiple options - handle this case! } if (doc.select(".data td img").size() == 1) { result.setCover(doc.select(".data td img").first().attr("abs:src")); downloadCover(result); } if (doc.select(".aw_teaser_title").size() == 1) { result.setTitle(doc.select(".aw_teaser_title").first().text() .trim()); } else if (doc.select(".data td strong").size() > 0) { result.setTitle(doc.select(".data td strong").first().text().trim()); } else { result.setTitle(""); } if (doc.select(".aw_teaser_title_zusatz").size() > 0) { result.addDetail(new Detail("Titelzusatz", doc .select(".aw_teaser_title_zusatz").text().trim())); } String title = ""; String text = ""; boolean takeover = false; Element detailtrs = doc2.select(".box-container .data td").first(); for (Node node : detailtrs.childNodes()) { if (node instanceof Element) { if (((Element) node).tagName().equals("strong")) { title = ((Element) node).text().trim(); text = ""; } else { if (((Element) node).tagName().equals("a") && (((Element) node).text().trim() .contains("hier klicken") || title .equals("Link:"))) { text = text + ((Element) node).attr("href"); takeover = true; break; } } } else if (node instanceof TextNode) { text = text + ((TextNode) node).text(); } } if (!takeover) { text = ""; title = ""; } detailtrs = doc2.select("#tab-content .data td").first(); if (detailtrs != null) { for (Node node : detailtrs.childNodes()) { if (node instanceof Element) { if (((Element) node).tagName().equals("strong")) { if (!text.equals("") && !title.equals("")) { result.addDetail(new Detail(title.trim(), text .trim())); if (title.equals("Titel:")) { result.setTitle(text.trim()); } text = ""; } title = ((Element) node).text().trim(); } else { if (((Element) node).tagName().equals("a") && (((Element) node).text().trim() .contains("hier klicken") || title .equals("Link:"))) { text = text + ((Element) node).attr("href"); } else { text = text + ((Element) node).text(); } } } else if (node instanceof TextNode) { text = text + ((TextNode) node).text(); } } } else { if (doc2.select("#tab-content .fulltitle tr").size() > 0) { Elements rows = doc2.select("#tab-content .fulltitle tr"); for (Element tr : rows) { if (tr.children().size() == 2) { Element valcell = tr.child(1); String value = valcell.text().trim(); if (valcell.select("a").size() == 1) { value = valcell.select("a").first().absUrl("href"); } result.addDetail(new Detail(tr.child(0).text().trim(), value)); } } } else { result.addDetail(new Detail(stringProvider .getString(StringProvider.ERROR), stringProvider .getString(StringProvider.COULD_NOT_LOAD_DETAIL))); } } if (!text.equals("") && !title.equals("")) { result.addDetail(new Detail(title.trim(), text.trim())); if (title.equals("Titel:")) { result.setTitle(text.trim()); } } for (Element link : doc3.select("#tab-content a")) { Map<String, String> hrefq = getQueryParamsFirst(link.absUrl("href")); if (result.getId() == null) { // ID retrieval String key = hrefq.get("katkey"); if (key != null) { result.setId(key); break; } } } for (Element link : doc3.select(".box-container a")) { if (link.text().trim().equals("Download")) { result.addDetail(new Detail(stringProvider .getString(StringProvider.DOWNLOAD), link .absUrl("href"))); } } Map<String, Integer> copy_columnmap = new HashMap<String, Integer>(); // Default values copy_columnmap.put(DetailledItem.KEY_COPY_BARCODE, 1); copy_columnmap.put(DetailledItem.KEY_COPY_BRANCH, 3); copy_columnmap.put(DetailledItem.KEY_COPY_STATUS, 4); Elements copy_columns = doc.select("#tab-content .data tr#bg2 th"); for (int i = 0; i < copy_columns.size(); i++) { Element th = copy_columns.get(i); String head = th.text().trim(); if (head.contains("Status")) { copy_columnmap.put(DetailledItem.KEY_COPY_STATUS, i); } if (head.contains("Zweigstelle")) { copy_columnmap.put(DetailledItem.KEY_COPY_BRANCH, i); } if (head.contains("Mediennummer")) { copy_columnmap.put(DetailledItem.KEY_COPY_BARCODE, i); } if (head.contains("Standort")) { copy_columnmap.put(DetailledItem.KEY_COPY_LOCATION, i); } if (head.contains("Signatur")) { copy_columnmap.put(DetailledItem.KEY_COPY_SHELFMARK, i); } } Pattern status_lent = Pattern .compile("^(entliehen) bis ([0-9]{1,2}.[0-9]{1,2}.[0-9]{2,4}) \\(gesamte Vormerkungen: ([0-9]+)\\)$"); Pattern status_and_barcode = Pattern.compile("^(.*) ([0-9A-Za-z]+)$"); Elements exemplartrs = doc.select("#tab-content .data tr").not("#bg2"); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN); for (Element tr : exemplartrs) { try { Map<String, String> e = new HashMap<String, String>(); Element status = tr.child(copy_columnmap .get(DetailledItem.KEY_COPY_STATUS)); Element barcode = tr.child(copy_columnmap .get(DetailledItem.KEY_COPY_BARCODE)); String barcodetext = barcode.text().trim() .replace(" Wegweiser", ""); // STATUS String statustext = ""; if (status.getElementsByTag("b").size() > 0) { statustext = status.getElementsByTag("b").text().trim(); } else { statustext = status.text().trim(); } if (copy_columnmap.get(DetailledItem.KEY_COPY_STATUS) == copy_columnmap .get(DetailledItem.KEY_COPY_BARCODE)) { Matcher matcher1 = status_and_barcode.matcher(statustext); if (matcher1.matches()) { statustext = matcher1.group(1); barcodetext = matcher1.group(2); } } Matcher matcher = status_lent.matcher(statustext); if (matcher.matches()) { e.put(DetailledItem.KEY_COPY_STATUS, matcher.group(1)); e.put(DetailledItem.KEY_COPY_RETURN, matcher.group(2)); e.put(DetailledItem.KEY_COPY_RESERVATIONS, matcher.group(3)); e.put(DetailledItem.KEY_COPY_RETURN_TIMESTAMP, String .valueOf(sdf.parse(matcher.group(2)).getTime())); } else { e.put(DetailledItem.KEY_COPY_STATUS, statustext); } e.put(DetailledItem.KEY_COPY_BARCODE, barcodetext); if (status.select("a[href*=doVormerkung]").size() == 1) { e.put(DetailledItem.KEY_COPY_RESINFO, status.select("a[href*=doVormerkung]").attr("href") .split("\\?")[1]); } String branchtext = tr .child(copy_columnmap .get(DetailledItem.KEY_COPY_BRANCH)).text() .trim().replace(" Wegweiser", ""); e.put(DetailledItem.KEY_COPY_BRANCH, branchtext); if (copy_columnmap.containsKey(DetailledItem.KEY_COPY_LOCATION)) { e.put(DetailledItem.KEY_COPY_LOCATION, tr.child( copy_columnmap .get(DetailledItem.KEY_COPY_LOCATION)) .text().trim().replace(" Wegweiser", "")); } if (copy_columnmap .containsKey(DetailledItem.KEY_COPY_SHELFMARK)) { e.put(DetailledItem.KEY_COPY_SHELFMARK, tr.child( copy_columnmap .get(DetailledItem.KEY_COPY_SHELFMARK)) .text().trim().replace(" Wegweiser", "")); } result.addCopy(e); } catch (Exception ex) { ex.printStackTrace(); } } try { Element isvolume = null; Map<String, String> volume = new HashMap<String, String>(); Elements links = doc.select(".data td a"); int elcount = links.size(); for (int eli = 0; eli < elcount; eli++) { List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI( links.get(eli).attr("href")), "UTF-8"); for (NameValuePair nv : anyurl) { if (nv.getName().equals("methodToCall") && nv.getValue().equals("volumeSearch")) { isvolume = links.get(eli); } else if (nv.getName().equals("catKey")) { volume.put("catKey", nv.getValue()); } else if (nv.getName().equals("dbIdentifier")) { volume.put("dbIdentifier", nv.getValue()); } } if (isvolume != null) { volume.put("volume", "true"); result.setVolumesearch(volume); break; } } } catch (Exception e) { e.printStackTrace(); } return result; } @Override public ReservationResult reservation(DetailledItem item, Account acc, int useraction, String selection) throws IOException { return null; } @Override public ProlongResult prolong(String a, Account account, int useraction, String Selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { return null; } @Override public AccountData account(Account acc) throws IOException, NotReachableException, JSONException, SocketException, OpacErrorException { return null; } @Override public boolean isAccountSupported(Library library) { return false; } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account acc) throws ClientProtocolException, SocketException, IOException, NotReachableException { return null; } @Override public String getShareUrl(String id, String title) { String startparams = ""; if (data.has("startparams")) { try { startparams = data.getString("startparams") + "&"; } catch (JSONException e) { e.printStackTrace(); } } if (id != null && id != "") return opac_url + "/start.do?" + startparams + "searchType=1&Query=0%3D%22" + id + "%22"; else return opac_url + "/start.do?" + startparams + "searchType=1&Query=-1%3D%22" + title + "%22"; } @Override public int getSupportFlags() { int flags = SUPPORT_FLAG_ACCOUNT_PROLONG_ALL | SUPPORT_FLAG_CHANGE_ACCOUNT; flags |= SUPPORT_FLAG_ENDLESS_SCROLLING; return flags; } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { if (!initialised) start(); if (System.currentTimeMillis() - logged_in > SESSION_LIFETIME || logged_in_as == null) { try { account(account); } catch (JSONException e) { e.printStackTrace(); return new ProlongAllResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e) { return new ProlongAllResult(MultiStepResult.Status.ERROR, e.getMessage()); } } else if (logged_in_as.getId() != account.getId()) { try { account(account); } catch (JSONException e) { e.printStackTrace(); return new ProlongAllResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e) { return new ProlongAllResult(MultiStepResult.Status.ERROR, e.getMessage()); } } // We have to call the page we originally found the link on first... String html = httpGet( opac_url + "/userAccount.do?methodToCall=renewalPossible&renewal=account", ENCODING); Document doc = Jsoup.parse(html); if (doc.select("table.data").size() > 0) { List<Map<String, String>> result = new ArrayList<Map<String, String>>(); for (Element td : doc.select("table.data tr td")) { Map<String, String> line = new HashMap<String, String>(); if (!td.text().contains("Titel") || !td.text().contains("Status")) continue; String nextNodeIs = ""; for (Node n : td.childNodes()) { String text = ""; if (n instanceof Element) { text = ((Element) n).text(); } else if (n instanceof TextNode) { text = ((TextNode) n).text(); } else continue; if (text.trim().length() == 0) continue; if (text.contains("Titel:")) nextNodeIs = ProlongAllResult.KEY_LINE_TITLE; else if (text.contains("Verfasser:")) nextNodeIs = ProlongAllResult.KEY_LINE_AUTHOR; else if (text.contains("Leihfristende:")) nextNodeIs = ProlongAllResult.KEY_LINE_NEW_RETURNDATE; else if (text.contains("Status:")) nextNodeIs = ProlongAllResult.KEY_LINE_MESSAGE; else if (text.contains("Mediennummer:") || text.contains("Signatur:")) nextNodeIs = ""; else if (nextNodeIs.length() > 0) { line.put(nextNodeIs, text.trim()); nextNodeIs = ""; } } result.add(line); } return new ProlongAllResult(MultiStepResult.Status.OK, result); } return new ProlongAllResult(MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.COULD_NOT_LOAD_ACCOUNT)); } @Override public SearchRequestResult filterResults(Filter filter, Option option) throws IOException, NotReachableException, OpacErrorException { // TODO Auto-generated method stub return null; } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { } @Override public void setLanguage(String language) { // TODO Auto-generated method stub } @Override public Set<String> getSupportedLanguages() throws IOException { // TODO Auto-generated method stub return null; } }
package heufybot.modules; import heufybot.core.HeufyBot; import heufybot.utils.FileUtils; import heufybot.utils.PastebinUtils; import heufybot.utils.StringUtils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; public class OutOfContext extends Module { private String dataPath = "data/ooclog.txt"; public OutOfContext() { this.authType = Module.AuthType.Anyone; this.trigger = "^" + commandPrefix + "(ooc)($| .*)"; } public void processEvent(final String source, String message, String triggerUser, List<String> params) { final HeufyBot bot = this.bot; if(params.size() == 1) { Thread thread = new Thread(new Runnable() { public void run() { String data = FileUtils.readFile(dataPath); if(data.equals("")) { bot.getIRC().cmdPRIVMSG(source, "No quotes to be posted."); } else { String result = PastebinUtils.post(data, "HeufyBot OutOfContext Log", "10M"); if(result == null) { bot.getIRC().cmdPRIVMSG(source, "Error: OoC Log could not be posted."); } else if(result.startsWith("http://pastebin.com/")) { bot.getIRC().cmdPRIVMSG(source, "OoC Log posted: " + result + " (Link expires in 10 minutes)."); } else { bot.getIRC().cmdPRIVMSG(source, "Error: " + result + "."); } } } }); thread.start(); } else { params.remove(0); String subCommand = params.remove(0).toLowerCase(); if(subCommand.equals("add")) { String newQuote = StringUtils.removeFormattingAndColors(StringUtils.join(params, " ")); DateFormat dateFormat = new SimpleDateFormat("[yyyy/MM/dd] [HH:mm]"); Date date = new Date(); String dateString = dateFormat.format(date); String toQuote = ""; if(newQuote.matches("^<.*>.*") || newQuote.matches("^\\* .*") || newQuote.matches("^\\[.*\\] <.*>.*") || newQuote.matches("^\\[.*\\] \\* .*")) { if(newQuote.matches("^\\[.*\\] <.*>.*") || newQuote.matches("^\\[.*\\] \\* .*")) { if(newQuote.matches("^\\[.*\\] \\* .*")) { toQuote = newQuote.substring(newQuote.indexOf("* ") + 2).split(" ")[0]; newQuote = dateString + " " + newQuote.substring(newQuote.indexOf("*")); } else { toQuote = newQuote.substring(newQuote.indexOf("<") + 1, newQuote.indexOf(">")); newQuote = dateString + " " + newQuote.substring(newQuote.indexOf("<")); } } else if(newQuote.matches("^<.*>.*") || newQuote.matches("^\\* .*")) { if(newQuote.matches("^\\* .*")) { toQuote = newQuote.substring(newQuote.indexOf("* ") + 2).split(" ")[0]; } else { toQuote = newQuote.substring(newQuote.indexOf("<") + 1, newQuote.indexOf(">")); } newQuote = dateString + " " + newQuote; } if(bot.getIRC().getServerInfo().getReverseUserPrefixes().containsKey(toQuote.substring(0, 1))) { newQuote = newQuote.replace(toQuote, toQuote.substring(1)); } FileUtils.writeFileAppend(dataPath, newQuote + "\n"); bot.getIRC().cmdPRIVMSG(source, "Quote \"" + newQuote + "\" was added to the log!"); } else { bot.getIRC().cmdPRIVMSG(source, "No nickname was found in this quote."); } } else if(subCommand.equals("searchnick")) { if(params.size() == 0) { bot.getIRC().cmdPRIVMSG(source, search(triggerUser, false)); } else { bot.getIRC().cmdPRIVMSG(source, search(params.get(0), false)); } } else if(subCommand.equals("search")) { bot.getIRC().cmdPRIVMSG(source, search(StringUtils.join(params, " "), true)); } else if(subCommand.equals("random")) { bot.getIRC().cmdPRIVMSG(source, search(".*", true)); } else if(subCommand.equals("remove")) { String search = StringUtils.join(params, " "); String quoteFile = FileUtils.readFile(dataPath); String[] quotes = quoteFile.split("\n"); ArrayList<String> quoteList = new ArrayList<String>(); ArrayList<String> matches = new ArrayList<String>(); Pattern pattern = Pattern.compile(".*" + search + ".*", Pattern.CASE_INSENSITIVE); if(quotes[0].length() < 21) { bot.getIRC().cmdPRIVMSG(source, "No quotes in the log."); } else { for(int i = 0; i < quotes.length; i++) { quoteList.add(quotes[i]); if(pattern.matcher(quotes[i].substring(21)).matches()) { matches.add(quotes[i]); } } if(matches.size() == 0) { bot.getIRC().cmdPRIVMSG(source, "No matches for '" + search + "' found."); } else if(matches.size() > 1) { bot.getIRC().cmdPRIVMSG(source, "Unable to remove quote, " + matches.size() + " matches were found."); } else { for(Iterator<String> iter = quoteList.iterator(); iter.hasNext();) { String quote = iter.next(); if(quote.equalsIgnoreCase(matches.get(0))) { iter.remove(); } } FileUtils.deleteFile(dataPath); FileUtils.touchFile(dataPath); for(String quote : quoteList) { FileUtils.writeFileAppend(dataPath, quote + "\n"); } bot.getIRC().cmdPRIVMSG(source, "[OutOfContext] Quote '" + matches.get(0) + "' was removed from the log!"); } } } else { bot.getIRC().cmdPRIVMSG(source, "[OutOfContext] Invalid operation. Please try again."); } } } private String search(String searchString, boolean searchInQuotes) { String quoteFile = FileUtils.readFile(dataPath); String[] quotes = quoteFile.split("\n"); ArrayList<String> matches = new ArrayList<String>(); Pattern pattern = Pattern.compile(".*" + searchString + ".*", Pattern.CASE_INSENSITIVE); if(quotes[0].length() < 21) { return "No quotes in the log."; } else { if(searchInQuotes) //Search for a word or words in the quotes themselves { for(int i = 0; i < quotes.length; i++) { if(quotes[i].indexOf("<") == 21) { if(pattern.matcher(quotes[i].substring(quotes[i].indexOf(">") + 1)).matches()) { matches.add(quotes[i]); } } else { if(pattern.matcher(quotes[i].substring(21)).matches()) { matches.add(quotes[i]); } } } } else //search for nicknames { for(int i = 0; i < quotes.length; i++) { if(quotes[i].substring(21).matches("^<.*>.*")) { if(pattern.matcher(quotes[i].substring(quotes[i].indexOf("<") + 1, quotes[i].indexOf(">"))).matches()) { matches.add(quotes[i]); } } else if(quotes[i].substring(21).matches("^\\* .*")) { if(pattern.matcher(quotes[i].substring(quotes[i].indexOf("* ") + 2).split(" ")[0]).matches()) { matches.add(quotes[i]); } } } } if(matches.size() == 0) { return "No matches for \"" + searchString + "\" found."; } else { int quoteID = (int) (Math.random() * matches.size()); return "Quote #" + (quoteID + 1) + "/" + matches.size() + " - " + matches.get(quoteID); } } } public String getHelp(String message) { if(message.matches("ooc add")) { return "Commands: " + commandPrefix + "ooc add <quote> | Add a quote to the Out of Context log. Format is \"<nick> message\" for normal messages and \"* nick message\" for actions."; } else if(message.matches("ooc remove")) { return "Commands: " + commandPrefix + "ooc remove <quote> | Remove a quote from the Out of Context log. Provide words that are in the quote you're trying to remove. Quote will only be removed if there's only one match."; } else if(message.matches("ooc search")) { return "Commands: " + commandPrefix + "ooc search <quote> | Search for a quote in the Out of Context log. The results are the ones that have the given words in them"; } else if(message.matches("ooc searchnick")) { return "Commands: " + commandPrefix + "ooc searchnick <nickname> | Search for a quote in the Out of Context log by providing a nickname or part of one."; } else if(message.matches("ooc random")) { return "Commands: " + commandPrefix + "ooc random | Returns a random quote from the Out of Context log."; } return "Commands: " + commandPrefix + "ooc (add/remove/search/searchnick/random) | The log of Out of Context quotes! Without a subcommand this will post a link to the log. Type \"" + commandPrefix + "help ooc <subcommand>\" for help on a specific subcommand."; } public void onLoad() { FileUtils.touchFile(dataPath); } public void onUnload() { } }
package ru.job4j.list; import org.junit.Test; import java.util.List; import java.util.ArrayList; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class UserConvertTest { @Test public void listToHMapTest() { UserConvert userConvert = new UserConvert(); User user1 = new User(0, "Max", "Voronezh"); List<User> list = new ArrayList<User>(); list.add(user1); userConvert.process(list).get(0); assertThat(userConvert.process(list).get(0), is(user1)); } }
package com.illposed.osc; import com.illposed.osc.utility.OSCJavaToByteArrayConverter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; /** * An simple (non-bundle) OSC message. * * An OSC <i>Message</i> is made up of * an <i>Address Pattern</i> (the receiver of the message) * and <i>Arguments</i> (the content of the message). * * @author Chandrasekhar Ramakrishnan */ public class OSCMessage extends AbstractOSCPacket { /** * Java regular expression pattern matching a single invalid character. * The invalid characters are: * ' ', '#', '*', ',', '?', '[', ']', '{', '}' */ private static final Pattern ILLEGAL_ADDRESS_CHAR = Pattern.compile("[ \\ private String address; private List<Object> arguments; /** * Creates an empty OSC Message. * In order to send this OSC message, * you need to set the address and optionally some arguments. */ public OSCMessage() { this(null); } /** * Creates an OSCMessage with an address already initialized. * @param address the recipient of this OSC message */ public OSCMessage(String address) { this(address, null); } /** * Creates an OSCMessage with an address * and arguments already initialized. * @param address the recipient of this OSC message * @param arguments the data sent to the receiver */ public OSCMessage(String address, Collection<Object> arguments) { checkAddress(address); this.address = address; if (arguments == null) { this.arguments = new LinkedList<Object>(); } else { this.arguments = new ArrayList<Object>(arguments); } } /** * The receiver of this message. * @return the receiver of this OSC Message */ public String getAddress() { return address; } /** * Set the address of this message. * @param address the receiver of the message */ public void setAddress(String address) { checkAddress(address); this.address = address; contentChanged(); } /** * Add an argument to the list of arguments. * @param argument a Float, Double, String, Character, Integer, Long, Boolean, null * or an array of these */ public void addArgument(Object argument) { arguments.add(argument); contentChanged(); } /** * The arguments of this message. * @return the arguments to this message */ public List<Object> getArguments() { return Collections.unmodifiableList(arguments); } /** * Convert the address into a byte array. * Used internally only. * @param stream where to write the address to */ private void computeAddressByteArray(OSCJavaToByteArrayConverter stream) { stream.write(address); } /** * Convert the arguments into a byte array. * Used internally only. * @param stream where to write the arguments to */ private void computeArgumentsByteArray(OSCJavaToByteArrayConverter stream) { stream.write(','); stream.writeTypes(arguments); for (final Object argument : arguments) { stream.write(argument); } } @Override protected byte[] computeByteArray(OSCJavaToByteArrayConverter stream) { computeAddressByteArray(stream); computeArgumentsByteArray(stream); return stream.toByteArray(); } /** * Throws an exception if the given address is invalid. * We explicitly allow <code>null</code> here, * because we want to allow to set the address in a lazy fashion. * @param address to be checked for validity */ private static void checkAddress(String address) { // NOTE We explicitly allow <code>null</code> here, // because we want to allow to set in a lazy fashion. if ((address != null) && !isValidAddress(address)) { throw new IllegalArgumentException("Not a valid OSC address: " + address); } } /** * Checks whether a given string is a valid OSC <i>Address Pattern</i>. * @param address to be checked for validity * @return true if the supplied string constitutes a valid OSC address */ public static boolean isValidAddress(String address) { return (address != null) && !address.isEmpty() && address.charAt(0) == '/' && !address.contains(" && !ILLEGAL_ADDRESS_CHAR.matcher(address).find(); } }
package com.llj.network; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import org.jivesoftware.smack.AbstractXMPPConnection; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.parsing.ExceptionLoggingCallback; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; import org.jivesoftware.smack.util.TLSUtils; import org.pushingpixels.substance.api.shaper.RectangularButtonShaper; public class SeverConnection { public static String severDNS = "ec2-54-254-130-230.ap-southeast-1.compute.amazonaws.com"; public static int severPort = 5222; public static String xmppDomain = "ip-172-31-21-142.ap-southeast-1.compute.internal"; public static AbstractXMPPConnection connection;// Create a XMPPConnection public static void login(String username, String pass) { // Create a connection to the server. XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder() .setUsernameAndPassword(username, pass) .setHost(severDNS) .setPort(severPort) .setServiceName(xmppDomain); try { TLSUtils.acceptAllCertificates(builder);// Trust all certificates } catch (NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } try { XMPPTCPConnectionConfiguration configuration = builder.build(); connection = new XMPPTCPConnection(configuration); connection.setParsingExceptionCallback(new ExceptionLoggingCallback()); connection.connect(); //return connection; } catch (SmackException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (XMPPException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { System.err.println(username + ":" + pass+" successfully login the xmpp server."); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //return null; } public static void main(String[] args) { login("lgc", "111111"); } }
/** * @author dgeorge * * $Id: BaseManager.java,v 1.4 2005-10-26 20:54:51 georgeda Exp $ * * $Log: not supported by cvs2svn $ * Revision 1.3 2005/09/29 18:31:14 georgeda * Changed visibility of base functions to protected * * Revision 1.2 2005/09/26 14:02:38 georgeda * Added common code * * */ package gov.nih.nci.camod.service.impl; import gov.nih.nci.camod.service.Manager; import gov.nih.nci.common.persistence.Persist; import gov.nih.nci.common.persistence.Search; import gov.nih.nci.common.persistence.exception.PersistenceException; import gov.nih.nci.common.persistence.hibernate.HibernateUtil; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Base class for managers. Provides the generic Object based calls. */ public class BaseManager implements Manager { protected final Log log = LogFactory.getLog(getClass()); /** * Get all of the objects models in the DB * * @return the list of all objects * * @exception throws * an Exception if an error occurred */ protected List getAll(Class inClass) throws Exception { log.trace("Entering BaseManager.getAll"); List theObjects = null; try { theObjects = Search.query(inClass); } catch (Exception e) { log.error("Exception occurred in BaseManager.getAll", e); throw e; } log.trace("Exiting BaseManager.getAll"); return theObjects; } /** * Get a specific object by unique ID * * @param id * The unique id for the object * * @return the object if found, null otherwise * @throws Exception * * @exception Exception * if an error occurred */ protected Object get(String inId, Class inClass) throws Exception { log.trace("Entering BaseManager.get"); Object theObject = null; try { log.debug("Querying for id: " + inId); theObject = Search.queryById(inClass, new Long(inId)); } catch (PersistenceException pe) { log.error("Exception occurred in BaseManager.get", pe); throw pe; } catch (Exception e) { log.error("Exception occurred in BaseManager.get", e); throw e; } log.trace("Exiting BaseManager.get"); return theObject; } /** * Save an object * * @param inObject * The object to save * * @exception Exception * if an error occurred */ protected void save(Object inObject) throws Exception { log.trace("Entering BaseManager.save"); try { // Begin an transaction HibernateUtil.beginTransaction(); // Save the object log.debug("Saving object"); Persist.save(inObject); // Commit all changes or none HibernateUtil.commitTransaction(); } catch (PersistenceException pe) { HibernateUtil.rollbackTransaction(); log.error("PersistenceException in BaseManager.save", pe); throw pe; } catch (Exception e) { HibernateUtil.rollbackTransaction(); log.error("Exception in BaseManager.save", e); throw e; } } /** * Remove an object from the system. Should remove all associated data as * well * * @param inId * The unique id of the object to delete * * @throws Exception * An error occurred when attempting to delete the object */ protected void remove(String inId, Class inClass) throws Exception { log.trace("Entering BaseManager.remove"); try { // Begin an transaction HibernateUtil.beginTransaction(); log.debug("Removing object: " + inId); Persist.deleteById(inClass, new Long(inId)); // Commit all changes or none HibernateUtil.commitTransaction(); } catch (PersistenceException pe) { HibernateUtil.rollbackTransaction(); log.error("Unable to delete object: ", pe); throw pe; } catch (Exception e) { HibernateUtil.rollbackTransaction(); log.error("Unable to delete object: ", e); throw e; } log.trace("Exiting BaseManager.remove"); } }
package replicant.messages; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; /** * The message that represents a set of changes to subscriptions and entities that should be applied atomically. */ @SuppressFBWarnings( "EI_EXPOSE_REP" ) @JsType( isNative = true, namespace = JsPackage.GLOBAL, name = "Object" ) public class UseCacheMessage extends ServerToClientMessage { @JsOverlay public static final String TYPE = "use-cache"; @Nonnull private String channel; @Nonnull private String etag; @GwtIncompatible @Nonnull public static UseCacheMessage create( @Nullable final Integer requestId, @Nonnull final String channel, @Nonnull final String eTag ) { final UseCacheMessage changeSet = new UseCacheMessage(); changeSet.type = TYPE; changeSet.requestId = null == requestId ? null : requestId.doubleValue(); changeSet.channel = Objects.requireNonNull( channel ); changeSet.etag = Objects.requireNonNull( eTag ); return changeSet; } @JsOverlay @Nonnull public final String getChannel() { return channel; } @JsOverlay @Nonnull public final String getEtag() { return etag; } }
package interdroid.vdb.content.avro; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import interdroid.vdb.content.GenericContentProvider; import interdroid.vdb.content.metadata.EntityInfo; import interdroid.vdb.content.metadata.FieldInfo; public class AvroEntityInfo extends EntityInfo { private static final Logger logger = LoggerFactory.getLogger(AvroEntityInfo.class); // TODO: (nick) Support sort order from the schema as default sort order. // TODO: (nick) Support default values from the schema // TODO: (nick) Support properties to specify what the key is instead of/in addition to supporting implicit keys we use now // TODO: (nick) Support cross namespace entities. We could embed the URI for the entity in the parent_id instead of an integer id. // TODO: (nick) Fixed are named. Those should have their own table probably or they will break. private Schema schema_; public AvroEntityInfo(Schema schema, AvroMetadata avroMetadata) { this(schema, avroMetadata, null); } public AvroEntityInfo(Schema schema, AvroMetadata avroMetadata, EntityInfo parentEntity) { schema_ = schema; this.parentEntity = parentEntity; if (parentEntity != null && !this.schema_.getNamespace().equals(parentEntity.namespace())) { throw new RuntimeException("Only entities in the same namespace are currently supported"); } avroMetadata.put(this); parseSchema(avroMetadata, parentEntity); if (parentEntity != null) { parentEntity.children.add(this); } } private void parseSchema(AvroMetadata avroMetadata, EntityInfo parentEntity) { if (logger.isDebugEnabled()) logger.debug("Constructing avro entity with name: " + name() + " in namespace: " + namespace() + " schema: " + schema_); // Every entity gets an _id int field as a primary key FieldInfo keyField = new AvroFieldInfo(new Field(AvroContentProvider.ID_COLUMN_NAME, Schema.create(Schema.Type.INT), null, null), true); fields.put(keyField.fieldName, keyField); this.key.add(keyField); // Sub entities get columns which reference their parent key // TODO: (nick) For cross namespace this should be a string with the URI probably. if (parentEntity != null) { for (FieldInfo field : parentEntity.key) { if (logger.isDebugEnabled()) logger.debug("Adding parent key field."); keyField = new AvroFieldInfo(new Field(GenericContentProvider.PARENT_COLUMN_PREFIX + field.fieldName, ((AvroFieldInfo)field).schema_, null, null), false); keyField.targetEntity = parentEntity; keyField.targetField = field; fields.put(keyField.fieldName, keyField); } } switch (schema_.getType()) { case ENUM: parseEnum(avroMetadata); break; case RECORD: parseRecord(avroMetadata); break; default: throw new RuntimeException("Unsupported entity type: " + schema_); } } private void parseEnum(AvroMetadata avroMetadata) { AvroFieldInfo field = new AvroFieldInfo(new Schema.Field(AvroContentProvider.VALUE_COLUMN_NAME, Schema.create(Schema.Type.STRING), null, null), false); fields.put(field.fieldName, field); setEnumValues(schema_); } private void parseRecord(AvroMetadata avroMetadata) { // Walk the fields in the record constructing either primitive fields or entity fields for (Field field: schema_.getFields()) { switch (field.schema().getType()) { case ARRAY: case MAP: case ENUM: case RECORD: { FieldInfo fieldInfo = new AvroFieldInfo(field); fields.put(fieldInfo.fieldName, fieldInfo); EntityInfo innerType = fetchOrBuildEntity(avroMetadata, field.schema(), field.name(), this); fieldInfo.targetEntity = innerType; // TODO: Support for complex keys. fieldInfo.targetField = innerType.key.get(0); if (logger.isDebugEnabled()) logger.debug("Adding sub-table field: " + fieldInfo.fieldName); break; } case UNION: { // Unions get three fields, one to hold the type the value has, one to hold the name if it is a named type and one for the value // We are abusing SQLite manifest typing on the value column with good reason FieldInfo typeField = new AvroFieldInfo(new Field(field.name() + AvroContentProvider.TYPE_COLUMN_NAME, Schema.create(Schema.Type.STRING), null, null), true); fields.put(typeField.fieldName, typeField); FieldInfo typeNameField = new AvroFieldInfo(new Field(field.name() + AvroContentProvider.TYPE_NAME_COLUMN_NAME, Schema.create(Schema.Type.STRING), null, null), true); fields.put(typeNameField.fieldName, typeNameField); if (logger.isDebugEnabled()) logger.debug("Adding union field: " + field.name()); // Make sure all of the possible inner types for the union exist for (Schema innerType : field.schema().getTypes()) { switch (innerType.getType()) { case ARRAY: case MAP: fetchOrBuildEntity(avroMetadata, innerType, field.name(), this); break; case ENUM: case RECORD: fetchOrBuildEntity(avroMetadata, innerType, innerType.getName(), this); break; } } FieldInfo fieldInfo = new AvroFieldInfo(field, false); if (logger.isDebugEnabled()) logger.debug("Adding field: " + fieldInfo.fieldName); fields.put(fieldInfo.fieldName, fieldInfo); break; } case FIXED: case FLOAT: case INT: case LONG: case BOOLEAN: case BYTES: case DOUBLE: case STRING: case NULL: { FieldInfo fieldInfo = new AvroFieldInfo(field, false); if (logger.isDebugEnabled()) logger.debug("Adding field: " + fieldInfo.fieldName); fields.put(fieldInfo.fieldName, fieldInfo); break; } default: throw new RuntimeException("Unsupported type: " + field.schema()); } } } private EntityInfo fetchOrBuildEntity(AvroMetadata avroMetadata, Schema fieldSchema, String fieldName, EntityInfo parent) { EntityInfo innerType; switch (fieldSchema.getType()) { case ARRAY: // Build the association type innerType = buildArrayAssociationTable(avroMetadata, fieldSchema, fieldName, parent); // Construct the target type if required. switch (fieldSchema.getElementType().getType()) { case RECORD: case ENUM: // Make sure the target type exists. fetchOrBuildEntity(avroMetadata, fieldSchema.getElementType(), fieldName, innerType); break; case ARRAY: // Make sure the target type exists. fetchOrBuildEntity(avroMetadata, fieldSchema.getElementType(), fieldName, innerType); break; case MAP: // Make sure the target type exists. fetchOrBuildEntity(avroMetadata, fieldSchema.getElementType(), fieldName, innerType); break; case BOOLEAN: case BYTES: case DOUBLE: case FIXED: case FLOAT: case INT: case LONG: case NULL: case STRING: case UNION: break; default: throw new RuntimeException("Unsupported type: " + fieldSchema); } break; case ENUM: { innerType = avroMetadata.getEntity(fieldSchema.getFullName()); if (innerType == null) { // Enums are built with no parent since we point to them with an integer key innerType = new AvroEntityInfo(fieldSchema, avroMetadata, null); } break; } case MAP: // Now we need to build an association table innerType = buildMapAssociationTable(avroMetadata, fieldSchema, fieldName, parent); // Construct the target type if required. switch (fieldSchema.getElementType().getType()) { case RECORD: case ENUM: case ARRAY: case MAP: // Make sure the target type exists. fetchOrBuildEntity(avroMetadata, fieldSchema.getValueType(), fieldName, innerType); break; case BOOLEAN: case BYTES: case DOUBLE: case FIXED: case FLOAT: case INT: case LONG: case NULL: case STRING: case UNION: break; default: throw new RuntimeException("Unsupported type: " + fieldSchema); } case RECORD: innerType = avroMetadata.getEntity(fieldSchema.getFullName()); // Construct the inner type entity. if (innerType == null) { innerType = new AvroEntityInfo(fieldSchema, avroMetadata); } break; case UNION: case BOOLEAN: case BYTES: case DOUBLE: case FIXED: case FLOAT: case INT: case LONG: case NULL: case STRING: default: throw new RuntimeException("Unsupported type: " + fieldSchema); } return innerType; } private EntityInfo buildMapAssociationTable(AvroMetadata avroMetadata, Schema fieldSchema, String fieldName, EntityInfo parent) { List<Field>mapFields = new ArrayList<Field>(); mapFields.add(new Schema.Field(AvroContentProvider.KEY_COLUMN_NAME, Schema.create(Schema.Type.STRING), null, null)); // Maps of unions get an extra type field if (fieldSchema.getType() == Type.UNION) { mapFields.add(new Schema.Field(AvroContentProvider.TYPE_COLUMN_NAME, Schema.create(Schema.Type.STRING), null, null)); } mapFields.add(new Schema.Field(fieldName, Schema.create(Schema.Type.BYTES), null, null)); Schema mapSchema = Schema.createRecord(getFullName() + AvroContentProvider.MAP_TABLE_INFIX + fieldName, null, schema_.getNamespace(), false); mapSchema.setFields(mapFields); return new AvroEntityInfo(mapSchema, avroMetadata, parent); } private EntityInfo buildArrayAssociationTable(AvroMetadata avroMetadata, Schema fieldSchema, String fieldName, EntityInfo parent) { List<Field>arrayFields = new ArrayList<Field>(); // Arrays of unions get an extra type field if (fieldSchema.getType() == Type.UNION) { arrayFields.add(new Schema.Field(AvroContentProvider.TYPE_COLUMN_NAME, Schema.create(Schema.Type.STRING), null, null)); } arrayFields.add(new Schema.Field(fieldName, Schema.create(Schema.Type.BYTES), null, null)); Schema mapSchema = Schema.createRecord(getFullName() + AvroContentProvider.ARRAY_TABLE_INFIX + fieldName, null, schema_.getNamespace(), false); mapSchema.setFields(arrayFields); return new AvroEntityInfo(mapSchema, avroMetadata, parent); } @Override public String name() { return schema_.getName(); } public String namespace() { return schema_.getNamespace(); } @Override public String contentType() { return "vnd.android.cursor.dir/vnd." + namespaceDot() + name(); } @Override public String itemContentType() { return "vnd.android.cursor.item/vnd." + namespaceDot() + name(); } private void setEnumValues(Schema fieldSchema) { enumValues = new HashMap<Integer, String>(); for (String value : fieldSchema.getEnumSymbols()) { enumValues.put(fieldSchema.getEnumOrdinal(value), value); } } }
package org.apache.commons.lang; import java.util.NoSuchElementException; import java.util.StringTokenizer; /** * <code>WordWrapUtils</code> is a utility class to assist with word wrapping. * * @author Henri Yandell * @author Stephen Colebourne * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a> * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @version $Id: WordWrapUtils.java,v 1.4 2003/06/08 23:27:26 scolebourne Exp $ */ public class WordWrapUtils { /** * <p><code>WordWrapUtils</code> instances should NOT be constructed in * standard programming. Instead, the class should be used as * <code>WordWrapUtils.wordWrap("foo bar");</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public WordWrapUtils() { } // Wrapping /** * Wraps a block of text to a specified line length. * <p> * This method takes a block of text, which might have long lines in it * and wraps the long lines based on the supplied wrapColumn parameter. * It was initially implemented for use by VelocityEmail. If there are tabs * in inString, you are going to get results that are a bit strange, * since tabs are a single character but are displayed as 4 or 8 * spaces. Remove the tabs. * * @param str text which is in need of word-wrapping * @param newline the characters that define a newline * @param wrapColumn the column to wrap the words at * @return the text with all the long lines word-wrapped */ public static String wrapText(String str, String newline, int wrapColumn) { StringTokenizer lineTokenizer = new StringTokenizer(str, newline, true); StringBuffer stringBuffer = new StringBuffer(); while (lineTokenizer.hasMoreTokens()) { try { String nextLine = lineTokenizer.nextToken(); if (nextLine.length() > wrapColumn) { // This line is long enough to be wrapped. nextLine = wrapLine(nextLine, newline, wrapColumn); } stringBuffer.append(nextLine); } catch (NoSuchElementException nsee) { // thrown by nextToken(), but I don't know why it would break; } } return (stringBuffer.toString()); } /** * Wraps a single line of text. * Called by wrapText() to do the real work of wrapping. * * @param line a line which is in need of word-wrapping * @param newline the characters that define a newline * @param wrapColumn the column to wrap the words at * @return a line with newlines inserted */ private static String wrapLine(String line, String newline, int wrapColumn) { StringBuffer wrappedLine = new StringBuffer(); while (line.length() > wrapColumn) { int spaceToWrapAt = line.lastIndexOf(' ', wrapColumn); if (spaceToWrapAt >= 0) { wrappedLine.append(line.substring(0, spaceToWrapAt)); wrappedLine.append(newline); line = line.substring(spaceToWrapAt + 1); } // This must be a really long word or URL. Pass it // through unchanged even though it's longer than the // wrapColumn would allow. This behavior could be // dependent on a parameter for those situations when // someone wants long words broken at line length. else { spaceToWrapAt = line.indexOf(' ', wrapColumn); if (spaceToWrapAt >= 0) { wrappedLine.append(line.substring(0, spaceToWrapAt)); wrappedLine.append(newline); line = line.substring(spaceToWrapAt + 1); } else { wrappedLine.append(line); line = ""; } } } // Whatever is left in line is short enough to just pass through wrappedLine.append(line); return (wrappedLine.toString()); } // Word wrapping /** * Create a word-wrapped version of a String. Wrap at 80 characters and * use newlines as the delimiter. If a word is over 80 characters long * use a - sign to split it. */ public static String wordWrap(String str) { return wordWrap(str, 80, "\n", "-"); } /** * Create a word-wrapped version of a String. Wrap at a specified width and * use newlines as the delimiter. If a word is over the width in lenght * use a - sign to split it. */ public static String wordWrap(String str, int width) { return wordWrap(str, width, "\n", "-"); } /** * Word-wrap a string. * * @param str String to word-wrap * @param width int to wrap at * @param delim String to use to separate lines * @param split String to use to split a word greater than width long * * @return String that has been word wrapped */ public static String wordWrap(String str, int width, String delim, String split) { int sz = str.length(); /// shift width up one. mainly as it makes the logic easier width++; // our best guess as to an initial size StringBuffer buffer = new StringBuffer(sz / width * delim.length() + sz); // every line will include a delim on the end width = width - delim.length(); int idx = -1; String substr = null; // beware: i is rolled-back inside the loop for (int i = 0; i < sz; i += width) { // on the last line if (i > sz - width) { buffer.append(str.substring(i)); break; } // the current line substr = str.substring(i, i + width); // is the delim already on the line idx = substr.indexOf(delim); if (idx != -1) { buffer.append(substr.substring(0, idx)); buffer.append(delim); i -= width - idx - delim.length(); // Erase a space after a delim. Is this too obscure? if(substr.length() > idx + 1) { if (substr.charAt(idx + 1) != '\n') { if (Character.isWhitespace(substr.charAt(idx + 1))) { i++; } } } continue; } idx = -1; // figure out where the last space is char[] chrs = substr.toCharArray(); for (int j = width; j > 0; j if (Character.isWhitespace(chrs[j - 1])) { idx = j; break; } } // idx is the last whitespace on the line. if (idx == -1) { for (int j = width; j > 0; j if (chrs[j - 1] == '-') { idx = j; break; } } if (idx == -1) { buffer.append(substr); buffer.append(delim); } else { if (idx != width) { idx++; } buffer.append(substr.substring(0, idx)); buffer.append(delim); i -= width - idx; } } else { buffer.append(substr.substring(0, idx)); buffer.append(StringUtils.repeat(" ", width - idx)); buffer.append(delim); i -= width - idx; } } return buffer.toString(); } }
package org.apache.velocity.io; import java.io.IOException; import java.io.Writer; /** * Implementation of a fast Writer. It was originally taken from JspWriter * and modified to have less syncronization going on. * * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author Anil K. Vijendran * @version $Id: VelocityWriter.java,v 1.8 2003/08/24 17:31:12 dlr Exp $ */ public final class VelocityWriter extends Writer { /** * constant indicating that the Writer is not buffering output */ public static final int NO_BUFFER = 0; /** * constant indicating that the Writer is buffered and is using the * implementation default buffer size */ public static final int DEFAULT_BUFFER = -1; /** * constant indicating that the Writer is buffered and is unbounded; * this is used in BodyContent */ public static final int UNBOUNDED_BUFFER = -2; protected int bufferSize; protected boolean autoFlush; private Writer writer; private char cb[]; private int nextChar; private static int defaultCharBufferSize = 8 * 1024; private boolean flushed = false; /** * Create a buffered character-output stream that uses a default-sized * output buffer. * * @param response A Servlet Response */ public VelocityWriter(Writer writer) { this(writer, defaultCharBufferSize, true); } /** * private constructor. */ private VelocityWriter(int bufferSize, boolean autoFlush) { this.bufferSize = bufferSize; this.autoFlush = autoFlush; } /** * This method returns the size of the buffer used by the JspWriter. * * @return the size of the buffer in bytes, or 0 is unbuffered. */ public int getBufferSize() { return bufferSize; } /** * This method indicates whether the JspWriter is autoFlushing. * * @return if this JspWriter is auto flushing or throwing IOExceptions on * buffer overflow conditions */ public boolean isAutoFlush() { return autoFlush; } public VelocityWriter(Writer writer, int sz, boolean autoFlush) { this(sz, autoFlush); if (sz < 0) throw new IllegalArgumentException("Buffer size <= 0"); this.writer = writer; cb = sz == 0 ? null : new char[sz]; nextChar = 0; } private final void init( Writer writer, int sz, boolean autoFlush ) { this.writer= writer; if( sz > 0 && ( cb == null || sz > cb.length ) ) cb=new char[sz]; nextChar = 0; this.autoFlush=autoFlush; this.bufferSize=sz; } /** * Flush the output buffer to the underlying character stream, without * flushing the stream itself. This method is non-private only so that it * may be invoked by PrintStream. */ private final void flushBuffer() throws IOException { if (bufferSize == 0) return; flushed = true; if (nextChar == 0) return; writer.write(cb, 0, nextChar); nextChar = 0; } /** * Discard the output buffer. */ public final void clear() { nextChar = 0; } private final void bufferOverflow() throws IOException { throw new IOException("overflow"); } /** * Flush the stream. * */ public final void flush() throws IOException { flushBuffer(); if (writer != null) { writer.flush(); } } /** * Close the stream. * */ public final void close() throws IOException { if (writer == null) return; flush(); } /** * @return the number of bytes unused in the buffer */ public final int getRemaining() { return bufferSize - nextChar; } /** * Write a single character. * */ public final void write(int c) throws IOException { if (bufferSize == 0) { writer.write(c); } else { if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); cb[nextChar++] = (char) c; } } /** * Our own little min method, to avoid loading * <code>java.lang.Math</code> if we've run out of file * descriptors and we're trying to print a stack trace. */ private final int min(int a, int b) { return (a < b ? a : b); } /** * Write a portion of an array of characters. * * <p> Ordinarily this method stores characters from the given array into * this stream's buffer, flushing the buffer to the underlying stream as * needed. If the requested length is at least as large as the buffer, * however, then this method will flush the buffer and write the characters * directly to the underlying stream. Thus redundant * <code>DiscardableBufferedWriter</code>s will not copy data unnecessarily. * * @param cbuf A character array * @param off Offset from which to start reading characters * @param len Number of characters to write * */ public final void write(char cbuf[], int off, int len) throws IOException { if (bufferSize == 0) { writer.write(cbuf, off, len); return; } if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); writer.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write an array of characters. This method cannot be inherited from the * Writer class because it must suppress I/O exceptions. */ public final void write(char buf[]) throws IOException { write(buf, 0, buf.length); } /** * Write a portion of a String. * * @param s String to be written * @param off Offset from which to start reading characters * @param len Number of characters to be written * */ public final void write(String s, int off, int len) throws IOException { if (bufferSize == 0) { writer.write(s, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); s.getChars(b, b + d, cb, nextChar); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write a string. This method cannot be inherited from the Writer class * because it must suppress I/O exceptions. */ public final void write(String s) throws IOException { write(s, 0, s.length()); } /** * resets this class so that it can be reused * */ public final void recycle( Writer writer) { this.writer = writer; flushed = false; clear(); } }
// TiffParser.java package loci.formats.tiff; import java.io.IOException; import loci.common.DataTools; import loci.common.LogTools; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.formats.FormatException; import loci.formats.codec.BitBuffer; import loci.formats.codec.CodecOptions; public class TiffParser { // -- Fields -- /** Input source from which to parse TIFF data. */ protected RandomAccessInputStream in; /** Cached tile buffer to avoid re-allocations when reading tiles. */ private byte[] cachedTileBuffer; // -- Constructors -- /** Constructs a new TIFF parser from the given input source. */ public TiffParser(RandomAccessInputStream in) { this.in = in; } // -- TiffParser methods -- /** Gets the stream from which TIFF data is being parsed. */ public RandomAccessInputStream getStream() { return in; } /** Tests this stream to see if it represents a TIFF file. */ public boolean isValidHeader() { try { return checkHeader() != null; } catch (IOException e) { return false; } } /** * Checks the TIFF header. * * @return true if little-endian, * false if big-endian, * or null if not a TIFF. */ public Boolean checkHeader() throws IOException { if (in.length() < 4) return null; // byte order must be II or MM in.seek(0); int endianOne = in.read(); int endianTwo = in.read(); boolean littleEndian = endianOne == TiffConstants.LITTLE && endianTwo == TiffConstants.LITTLE; boolean bigEndian = endianOne == TiffConstants.BIG && endianTwo == TiffConstants.BIG; if (!littleEndian && !bigEndian) return null; // check magic number (42) in.order(littleEndian); short magic = in.readShort(); if (magic != TiffConstants.MAGIC_NUMBER && magic != TiffConstants.BIG_TIFF_MAGIC_NUMBER) { return null; } return new Boolean(littleEndian); } // -- TiffParser methods - IFD parsing -- /** * Gets all IFDs within the TIFF file, or null * if the input source is not a valid TIFF file. */ public IFDList getIFDs() throws IOException { return getIFDs(false); } /** * Gets all IFDs within the TIFF file, or null * if the input source is not a valid TIFF file. * If 'skipThumbnails' is set to true, thumbnail IFDs will not be returned. */ public IFDList getIFDs(boolean skipThumbnails) throws IOException { // check TIFF header Boolean result = checkHeader(); if (result == null) return null; in.seek(2); boolean bigTiff = in.readShort() == TiffConstants.BIG_TIFF_MAGIC_NUMBER; long offset = getFirstOffset(bigTiff); // compute maximum possible number of IFDs, for loop safety // each IFD must have at least one directory entry, which means that // each IFD must be at least 2 + 12 + 4 = 18 bytes in length long ifdMax = (in.length() - 8) / (bigTiff ? 22 : 18); // read in IFDs IFDList ifds = new IFDList(); for (long ifdNum=0; ifdNum<ifdMax; ifdNum++) { IFD ifd = getIFD(ifdNum, offset, bigTiff); if (ifd == null || ifd.size() <= 2) break; Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE); int subfileType = subfile == null ? 0 : subfile.intValue(); if (!skipThumbnails || subfileType == 0) { ifds.add(ifd); } else ifd = null; offset = getNextOffset(bigTiff, offset); if (offset <= 0 || offset >= in.length()) { if (offset != 0) { LogTools.debug("getIFDs: invalid IFD offset: " + offset); } break; } } return ifds; } /** * Gets the first IFD within the TIFF file, or null * if the input source is not a valid TIFF file. */ public IFD getFirstIFD() throws IOException { // check TIFF header Boolean result = checkHeader(); if (result == null) return null; in.seek(2); boolean bigTiff = in.readShort() == TiffConstants.BIG_TIFF_MAGIC_NUMBER; long offset = getFirstOffset(bigTiff); IFD ifd = getIFD(0, offset, bigTiff); if (ifd != null) { ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff)); } return ifd; } public TiffIFDEntry getFirstIFDEntry(int tag) throws IOException { // First lets re-position the file pointer by checking the TIFF header Boolean result = checkHeader(); if (result == null) return null; in.seek(2); boolean bigTiff = in.readShort() == TiffConstants.BIG_TIFF_MAGIC_NUMBER; // Get the offset of the first IFD long offset = getFirstOffset(bigTiff); // The following loosely resembles the logic of getIFD()... in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff; for (int i = 0; i < numEntries; i++) { in.seek(offset + // The beginning of the IFD 2 + // The width of the initial numEntries field (bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY) * i); int entryTag = in.readShort() & 0xffff; // Skip this tag unless it matches the one we want if (entryTag != tag) continue; // Parse the entry's "Type" int entryType = in.readShort() & 0xffff; // Parse the entry's "ValueCount" int valueCount = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt(); if (valueCount < 0) { throw new RuntimeException("Count of '" + valueCount + "' unexpected."); } // Parse the entry's "ValueOffset" long valueOffset = getNextOffset(bigTiff, offset); return new TiffIFDEntry(entryTag, entryType, valueCount, valueOffset); } throw new IllegalArgumentException("Unknown tag: " + tag); } /** * Gets offset to the first IFD, or -1 if stream is not TIFF. * Assumes the stream is positioned properly (checkHeader just called). */ public long getFirstOffset() throws IOException { return getFirstOffset(false); } /** * Gets offset to the first IFD, or -1 if stream is not TIFF. * Assumes the stream is positioned properly (checkHeader just called). * * @param bigTiff true if this is a BigTIFF file (8 byte pointers). */ public long getFirstOffset(boolean bigTiff) throws IOException { if (bigTiff) in.skipBytes(4); return bigTiff ? in.readLong() : in.readInt(); } /** Gets the IFD stored at the given offset. */ public IFD getIFD(long ifdNum, long offset) throws IOException { return getIFD(ifdNum, offset, false); } /** Gets the IFD stored at the given offset. */ public IFD getIFD(long ifdNum, long offset, boolean bigTiff) throws IOException { IFD ifd = new IFD(); // save little-endian flag to internal LITTLE_ENDIAN tag ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(in.isLittleEndian())); ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff)); // read in directory entries for this IFD LogTools.debug("getIFDs: seeking IFD #" + ifdNum + " at " + offset); in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readShort() & 0xffff; LogTools.debug("getIFDs: " + numEntries + " directory entries to read"); if (numEntries == 0 || numEntries == 1) return ifd; int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY; int baseOffset = bigTiff ? 8 : 2; int threshhold = bigTiff ? 8 : 4; for (int i=0; i<numEntries; i++) { in.seek(offset + baseOffset + bytesPerEntry * i); int tag = in.readShort() & 0xffff; int type = in.readShort() & 0xffff; // BigTIFF case is a slight hack because the count could be // greater than Integer.MAX_VALUE int count = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt(); int bpe = IFD.getIFDTypeLength(type); LogTools.debug("getIFDs: read " + IFD.getIFDTagName(tag) + " (type=" + IFD.getIFDTypeName(type) + "; count=" + count + ")"); if (count < 0 || bpe <= 0) { // invalid data in.skipBytes(bytesPerEntry - 4 - (bigTiff ? 8 : 4)); continue; } Object value = null; if (count > threshhold / bpe) { long pointer = getNextOffset(bigTiff, 0); LogTools.debug("getIFDs: seeking to offset: " + pointer); in.seek(pointer); } long inputLen = in.length(); long inputPointer = in.getFilePointer(); if (count * bpe + inputPointer > inputLen) { int oldCount = count; count = (int) ((inputLen - inputPointer) / bpe); LogTools.debug("getIFDs: truncated " + (oldCount - count) + " array elements for tag " + tag); } if (count < 0 || count > in.length()) break; if (type == IFD.BYTE) { // 8-bit unsigned integer if (count == 1) value = new Short(in.readByte()); else { byte[] bytes = new byte[count]; in.readFully(bytes); // bytes are unsigned, so use shorts short[] shorts = new short[count]; for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff); value = shorts; } } else if (type == IFD.ASCII) { // 8-bit byte that contain a 7-bit ASCII code; // the last byte must be NUL (binary zero) byte[] ascii = new byte[count]; in.read(ascii); // count number of null terminators int nullCount = 0; for (int j=0; j<count; j++) { if (ascii[j] == 0 || j == count - 1) nullCount++; } // convert character array to array of strings String[] strings = nullCount == 1 ? null : new String[nullCount]; String s = null; int c = 0, ndx = -1; for (int j=0; j<count; j++) { if (ascii[j] == 0) { s = new String(ascii, ndx + 1, j - ndx - 1); ndx = j; } else if (j == count - 1) { // handle non-null-terminated strings s = new String(ascii, ndx + 1, j - ndx); } else s = null; if (strings != null && s != null) strings[c++] = s; } value = strings == null ? (Object) s : strings; } else if (type == IFD.SHORT) { // 16-bit (2-byte) unsigned integer if (count == 1) value = new Integer(in.readShort() & 0xffff); else { int[] shorts = new int[count]; for (int j=0; j<count; j++) { shorts[j] = in.readShort() & 0xffff; } value = shorts; } } else if (type == IFD.LONG || type == IFD.IFD) { // 32-bit (4-byte) unsigned integer if (count == 1) value = new Long(in.readInt()); else { long[] longs = new long[count]; for (int j=0; j<count; j++) longs[j] = in.readInt(); value = longs; } } else if (type == IFD.LONG8 || type == IFD.SLONG8 || type == IFD.IFD8) { if (count == 1) value = new Long(in.readLong()); else { long[] longs = new long[count]; for (int j=0; j<count; j++) longs[j] = in.readLong(); value = longs; } } else if (type == IFD.RATIONAL || type == IFD.SRATIONAL) { // Two LONGs or SLONGs: the first represents the numerator // of a fraction; the second, the denominator if (count == 1) value = new TiffRational(in.readInt(), in.readInt()); else { TiffRational[] rationals = new TiffRational[count]; for (int j=0; j<count; j++) { rationals[j] = new TiffRational(in.readInt(), in.readInt()); } value = rationals; } } else if (type == IFD.SBYTE || type == IFD.UNDEFINED) { // SBYTE: An 8-bit signed (twos-complement) integer // UNDEFINED: An 8-bit byte that may contain anything, // depending on the definition of the field if (count == 1) value = new Byte(in.readByte()); else { byte[] sbytes = new byte[count]; in.read(sbytes); value = sbytes; } } else if (type == IFD.SSHORT) { // A 16-bit (2-byte) signed (twos-complement) integer if (count == 1) value = new Short(in.readShort()); else { short[] sshorts = new short[count]; for (int j=0; j<count; j++) sshorts[j] = in.readShort(); value = sshorts; } } else if (type == IFD.SLONG) { // A 32-bit (4-byte) signed (twos-complement) integer if (count == 1) value = new Integer(in.readInt()); else { int[] slongs = new int[count]; for (int j=0; j<count; j++) slongs[j] = in.readInt(); value = slongs; } } else if (type == IFD.FLOAT) { // Single precision (4-byte) IEEE format if (count == 1) value = new Float(in.readFloat()); else { float[] floats = new float[count]; for (int j=0; j<count; j++) floats[j] = in.readFloat(); value = floats; } } else if (type == IFD.DOUBLE) { // Double precision (8-byte) IEEE format if (count == 1) value = new Double(in.readDouble()); else { double[] doubles = new double[count]; for (int j=0; j<count; j++) { doubles[j] = in.readDouble(); } value = doubles; } } if (value != null && !ifd.containsKey(new Integer(tag))) { ifd.put(new Integer(tag), value); } } in.seek(offset + baseOffset + bytesPerEntry * numEntries); if (!(ifd.get(IFD.IMAGE_WIDTH) instanceof Number) || !(ifd.get(IFD.IMAGE_LENGTH) instanceof Number)) { return null; } return ifd; } /** Convenience method for obtaining a stream's first ImageDescription. */ public String getComment() throws IOException { IFD firstIFD = getFirstIFD(); return firstIFD == null ? null : firstIFD.getComment(); } // -- TiffParser methods - image reading -- public byte[] getTile(IFD ifd, int row, int col) throws FormatException, IOException { int samplesPerPixel = ifd.getSamplesPerPixel(); if (ifd.getPlanarConfiguration() == 2) samplesPerPixel = 1; int bpp = ifd.getBytesPerSample()[0]; int width = (int) ifd.getTileWidth(); int height = (int) ifd.getTileLength(); byte[] buf = new byte[width * height * samplesPerPixel * bpp]; return getTile(ifd, buf, row, col); } public byte[] getTile(IFD ifd, byte[] buf, int row, int col) throws FormatException, IOException { byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES, false, null); CodecOptions options = new CodecOptions(); options.interleaved = true; options.littleEndian = ifd.isLittleEndian(); long tileWidth = ifd.getTileWidth(); long tileLength = ifd.getTileLength(); int samplesPerPixel = ifd.getSamplesPerPixel(); int planarConfig = ifd.getPlanarConfiguration(); int compression = ifd.getCompression(); long numTileCols = ifd.getTilesPerRow(); int pixel = ifd.getBytesPerSample()[0]; int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel; long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); int tileNumber = (int) (row * numTileCols + col); byte[] tile = new byte[(int) stripByteCounts[tileNumber]]; in.seek(stripOffsets[tileNumber]); in.read(tile); int size = (int) (tileWidth * tileLength * pixel * effectiveChannels); options.maxBytes = size; if (jpegTable != null) { byte[] q = new byte[jpegTable.length + tile.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(tile, 2, q, jpegTable.length - 2, tile.length - 2); tile = TiffCompression.uncompress(q, compression, options); } else tile = TiffCompression.uncompress(tile, compression, options); TiffCompression.undifference(tile, ifd); unpackBytes(buf, 0, tile, ifd); return buf; } /** Reads the image defined in the given IFD from the input source. */ public byte[][] getSamples(IFD ifd) throws FormatException, IOException { return getSamples(ifd, 0, 0, (int) ifd.getImageWidth(), (int) ifd.getImageLength()); } /** Reads the image defined in the given IFD from the input source. */ public byte[][] getSamples(IFD ifd, int x, int y, int w, int h) throws FormatException, IOException { int samplesPerPixel = ifd.getSamplesPerPixel(); int bpp = ifd.getBytesPerSample()[0]; long width = ifd.getImageWidth(); long length = ifd.getImageLength(); byte[] b = new byte[(int) (w * h * samplesPerPixel * bpp)]; getSamples(ifd, b, x, y, w, h); byte[][] samples = new byte[samplesPerPixel][(int) (w * h * bpp)]; for (int i=0; i<samplesPerPixel; i++) { System.arraycopy(b, (int) (i*w*h*bpp), samples[i], 0, samples[i].length); } b = null; return samples; } public byte[] getSamples(IFD ifd, byte[] buf) throws FormatException, IOException { long width = ifd.getImageWidth(); long length = ifd.getImageLength(); return getSamples(ifd, buf, 0, 0, width, length); } public byte[] getSamples(IFD ifd, byte[] buf, int x, int y, long width, long height) throws FormatException, IOException { LogTools.debug("parsing IFD entries"); // get internal non-IFD entries boolean littleEndian = ifd.isLittleEndian(); in.order(littleEndian); // get relevant IFD entries int samplesPerPixel = ifd.getSamplesPerPixel(); long tileWidth = ifd.getTileWidth(); long tileLength = ifd.getTileLength(); long numTileRows = ifd.getTilesPerColumn(); long numTileCols = ifd.getTilesPerRow(); int planarConfig = ifd.getPlanarConfiguration(); int pixel = ifd.getBytesPerSample()[0]; int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel; ifd.printIFD(); if (width * height > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength > " + Integer.MAX_VALUE + " is not supported (" + width + " x " + height + ")"); } if (width * height * effectiveChannels * pixel > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength x " + "SamplesPerPixel x BitsPerSample > " + Integer.MAX_VALUE + " is not supported (" + width + " x " + height + " x " + samplesPerPixel + " x " + (pixel * 8) + ")"); } // casting to int is safe because we have already determined that // width * height is less than Integer.MAX_VALUE int numSamples = (int) (width * height); // read in image strips LogTools.debug("reading image data (samplesPerPixel=" + samplesPerPixel + "; numSamples=" + numSamples + ")"); long nrows = numTileRows; if (planarConfig == 2) numTileRows *= samplesPerPixel; Region imageBounds = new Region(x, y, (int) width, (int) (height * (samplesPerPixel / effectiveChannels))); int endX = (int) width + x; int endY = (int) height + y; int rowLen = pixel * (int) tileWidth; int tileSize = (int) (rowLen * tileLength); int planeSize = (int) (width * height * pixel); int outputRowLen = (int) (pixel * width); int bufferSizeSamplesPerPixel = samplesPerPixel; if (ifd.getPlanarConfiguration() == 2) bufferSizeSamplesPerPixel = 1; int bpp = ifd.getBytesPerSample()[0]; int bufferSize = (int) tileWidth * (int) tileLength * bufferSizeSamplesPerPixel * bpp; if (cachedTileBuffer == null || cachedTileBuffer.length != bufferSize) { cachedTileBuffer = new byte[bufferSize]; } for (int row=0; row<numTileRows; row++) { for (int col=0; col<numTileCols; col++) { Region tileBounds = new Region(col * (int) tileWidth, (int) (row * tileLength), (int) tileWidth, (int) tileLength); if (!imageBounds.intersects(tileBounds)) continue; if (planarConfig == 2) { tileBounds.y = (int) ((row % nrows) * tileLength); } getTile(ifd, cachedTileBuffer, row, col); // adjust tile bounds, if necessary int tileX = (int) Math.max(tileBounds.x, x); int tileY = (int) Math.max(tileBounds.y, y); int realX = tileX % (int) tileWidth; int realY = tileY % (int) tileLength; int twidth = (int) Math.min(endX - tileX, tileWidth - realX); int theight = (int) Math.min(endY - tileY, tileLength - realY); // copy appropriate portion of the tile to the output buffer int copy = pixel * twidth; realX *= pixel; realY *= rowLen; for (int q=0; q<effectiveChannels; q++) { int src = (int) (q * tileSize) + realX + realY; int dest = (int) (q * planeSize) + pixel * (tileX - x) + outputRowLen * (tileY - y); if (planarConfig == 2) dest += (planeSize * (row / nrows)); for (int tileRow=0; tileRow<theight; tileRow++) { System.arraycopy(cachedTileBuffer, src, buf, dest, copy); src += rowLen; dest += outputRowLen; } } } } return buf; } // -- Utility methods - byte stream decoding -- /** * Extracts pixel information from the given byte array according to the * bits per sample, photometric interpretation, and the specified byte * ordering. * No error checking is performed. * This method is tailored specifically for planar (separated) images. */ public static void planarUnpack(byte[] samples, int startIndex, byte[] bytes, IFD ifd) throws FormatException { BitBuffer bb = new BitBuffer(bytes); int numBytes = ifd.getBytesPerSample()[0]; int realBytes = numBytes; if (numBytes == 3) numBytes++; int bitsPerSample = ifd.getBitsPerSample()[0]; boolean littleEndian = ifd.isLittleEndian(); int photoInterp = ifd.getPhotometricInterpretation(); for (int j=0; j<bytes.length / realBytes; j++) { int value = bb.getBits(bitsPerSample); if (littleEndian) value = DataTools.swap(value) >> (32 - bitsPerSample); if (photoInterp == PhotoInterp.WHITE_IS_ZERO) { value = (int) (Math.pow(2, bitsPerSample) - 1 - value); } else if (photoInterp == PhotoInterp.CMYK) { value = Integer.MAX_VALUE - value; } if (numBytes*(startIndex + j) < samples.length) { DataTools.unpackBytes(value, samples, numBytes*(startIndex + j), numBytes, littleEndian); } } } /** * Extracts pixel information from the given byte array according to the * bits per sample, photometric interpretation and color map IFD directory * entry values, and the specified byte ordering. * No error checking is performed. */ public static void unpackBytes(byte[] samples, int startIndex, byte[] bytes, IFD ifd) throws FormatException { if (ifd.getPlanarConfiguration() == 2) { planarUnpack(samples, startIndex, bytes, ifd); return; } int compression = ifd.getCompression(); int photoInterp = ifd.getPhotometricInterpretation(); if (compression == TiffCompression.JPEG) photoInterp = PhotoInterp.RGB; int[] bitsPerSample = ifd.getBitsPerSample(); int nChannels = bitsPerSample.length; int nSamples = samples.length / nChannels; int totalBits = 0; for (int i=0; i<nChannels; i++) totalBits += bitsPerSample[i]; int sampleCount = 8 * bytes.length / totalBits; if (photoInterp == PhotoInterp.Y_CB_CR) sampleCount *= 3; LogTools.debug("unpacking " + sampleCount + " samples (startIndex=" + startIndex + "; totalBits=" + totalBits + "; numBytes=" + bytes.length + ")"); long imageWidth = ifd.getImageWidth(); int bps0 = bitsPerSample[0]; int numBytes = ifd.getBytesPerSample()[0]; boolean noDiv8 = bps0 % 8 != 0; boolean bps8 = bps0 == 8; boolean bps16 = bps0 == 16; int row = startIndex / (int) imageWidth; int col = 0; int cw = 0, ch = 0; boolean littleEndian = ifd.isLittleEndian(); int[] reference = ifd.getIFDIntArray(IFD.REFERENCE_BLACK_WHITE, false); int[] subsampling = ifd.getIFDIntArray(IFD.Y_CB_CR_SUB_SAMPLING, false); TiffRational[] coefficients = (TiffRational[]) ifd.getIFDValue(IFD.Y_CB_CR_COEFFICIENTS); int count = 0; BitBuffer bb = new BitBuffer(bytes); // Hyper optimisation that takes any 8-bit or 16-bit data, where there is // only one channel, the source byte buffer's size is less than or equal to // that of the destination buffer and for which no special unpacking is // required and performs a simple array copy. Over the course of reading // semi-large datasets this can save **billions** of method calls. // Wed Aug 5 19:04:59 BST 2009 // Chris Allan <callan@glencoesoftware.com> if ((bps8 || bps16) && bytes.length <= samples.length && nChannels == 1 && photoInterp != PhotoInterp.WHITE_IS_ZERO && photoInterp != PhotoInterp.CMYK && photoInterp != PhotoInterp.Y_CB_CR) { System.arraycopy(bytes, 0, samples, 0, bytes.length); return; } for (int j=0; j<sampleCount; j++) { for (int i=0; i<nChannels; i++) { int index = numBytes * (j * nChannels + i); int ndx = startIndex + j; if (ndx >= nSamples) { break; } int outputIndex = i * nSamples + ndx * numBytes; if (noDiv8) { // bits per sample is not a multiple of 8 short s = 0; if ((i == 0 && photoInterp == PhotoInterp.RGB_PALETTE) || (photoInterp != PhotoInterp.CFA_ARRAY && photoInterp != PhotoInterp.RGB_PALETTE)) { s = (short) (bb.getBits(bps0) & 0xffff); if ((ndx % imageWidth) == imageWidth - 1 && bps0 < 8) { bb.skipBits((imageWidth * bps0 * sampleCount) % 8); } } if (photoInterp == PhotoInterp.WHITE_IS_ZERO || photoInterp == PhotoInterp.CMYK) { // invert colors s = (short) (Math.pow(2, bitsPerSample[0]) - 1 - s); } if (outputIndex + numBytes <= samples.length) { DataTools.unpackBytes(s, samples, outputIndex, numBytes, littleEndian); } } else if (bps8) { // special case handles 8-bit data more quickly if (outputIndex >= samples.length) break; if (photoInterp != PhotoInterp.Y_CB_CR) { samples[outputIndex] = (byte) (bytes[index] & 0xff); } if (photoInterp == PhotoInterp.WHITE_IS_ZERO) { // invert color value samples[outputIndex] = (byte) (255 - samples[outputIndex]); } else if (photoInterp == PhotoInterp.CMYK) { samples[outputIndex] = (byte) (Integer.MAX_VALUE - samples[outputIndex]); } else if (photoInterp == PhotoInterp.Y_CB_CR) { if (i == bitsPerSample.length - 1) { float lumaRed = 0.299f; float lumaGreen = 0.587f; float lumaBlue = 0.114f; if (coefficients != null) { lumaRed = coefficients[0].floatValue(); lumaGreen = coefficients[1].floatValue(); lumaBlue = coefficients[2].floatValue(); } int subX = subsampling == null ? 2 : subsampling[0]; int subY = subsampling == null ? 2 : subsampling[1]; int block = subX * subY; int lumaIndex = j + (2 * (j / block)); int chromaIndex = (j / block) * (block + 2) + block; if (chromaIndex + 1 >= bytes.length) break; int tile = ndx / block; int pixel = ndx % block; int nTiles = (int) (imageWidth / subX); long r = subY * (tile / nTiles) + (pixel / subX); long c = subX * (tile % nTiles) + (pixel % subX); int idx = (int) (r * imageWidth + c); if (idx < nSamples) { int y = (bytes[lumaIndex] & 0xff) - reference[0]; int cb = (bytes[chromaIndex] & 0xff) - reference[2]; int cr = (bytes[chromaIndex + 1] & 0xff) - reference[4]; int red = (int) (cr * (2 - 2 * lumaRed) + y); int blue = (int) (cb * (2 - 2 * lumaBlue) + y); int green = (int) ((y - lumaBlue * blue - lumaRed * red) / lumaGreen); samples[idx] = (byte) red; samples[nSamples + idx] = (byte) green; samples[2*nSamples + idx] = (byte) blue; } } } } // end if (bps8) else { int offset = numBytes + index < bytes.length ? index : bytes.length - numBytes; long v = DataTools.bytesToLong(bytes, offset, numBytes, littleEndian); if (photoInterp == PhotoInterp.WHITE_IS_ZERO) { // invert color value long max = (long) Math.pow(2, numBytes * 8) - 1; v = max - v; } else if (photoInterp == PhotoInterp.CMYK) { v = Integer.MAX_VALUE - v; } if (ndx*numBytes >= nSamples) break; DataTools.unpackBytes(v, samples, i*nSamples + ndx*numBytes, numBytes, littleEndian); } // end else } } } /** * Read a file offset. * For bigTiff, a 64-bit number is read. For other Tiffs, a 32-bit number * is read and possibly adjusted for a possible carry-over from the previous * offset. */ long getNextOffset(boolean bigTiff, long previous) throws IOException { if (bigTiff) { return in.readLong(); } long offset = (previous & ~0xffffffffL) | (in.readInt() & 0xffffffffL); if (offset < previous) { offset += 0x100000000L; } return offset; } }
package loci.common; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NIOFileHandle extends AbstractNIOHandle { // -- Constants -- /** Logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(NIOFileHandle.class); //-- Static fields -- /** Default NIO buffer size to facilitate buffered I/O. */ protected static int defaultBufferSize = 1048576; /** * Default NIO buffer size to facilitate buffered I/O for read/write streams. */ protected static int defaultRWBufferSize = 8192; // -- Fields -- /** The random access file object backing this FileHandle. */ protected RandomAccessFile raf; /** The file channel backed by the random access file. */ protected FileChannel channel; /** The absolute position within the file. */ protected long position = 0; /** The absolute position of the start of the buffer. */ protected long bufferStartPosition = 0; /** The buffer size. */ protected int bufferSize; /** The buffer itself. */ protected ByteBuffer buffer; /** Whether or not the file is opened read/write. */ protected boolean isReadWrite = false; /** The default map mode for the file. */ protected FileChannel.MapMode mapMode = FileChannel.MapMode.READ_ONLY; /** The buffer's byte ordering. */ protected ByteOrder order; /** Provider class for NIO byte buffers, allocated or memory mapped. */ protected NIOByteBufferProvider byteBufferProvider; /** The original length of the file. */ private Long defaultLength; // -- Constructors -- /** * Creates a random access file stream to read from, and * optionally to write to, the file specified by the File argument. */ public NIOFileHandle(File file, String mode, int bufferSize) throws IOException { this.bufferSize = bufferSize; validateMode(mode); if (mode.equals("rw")) { isReadWrite = true; mapMode = FileChannel.MapMode.READ_WRITE; } raf = new RandomAccessFile(file, mode); channel = raf.getChannel(); byteBufferProvider = new NIOByteBufferProvider(channel, mapMode); buffer(position, 0); // if we know the length won't change, cache the original length if (mode.equals("r")) { defaultLength = raf.length(); } } /** * Creates a random access file stream to read from, and * optionally to write to, the file specified by the File argument. */ public NIOFileHandle(File file, String mode) throws IOException { this(file, mode, mode.equals("rw") ? defaultRWBufferSize : defaultBufferSize); } /** * Creates a random access file stream to read from, and * optionally to write to, a file with the specified name. */ public NIOFileHandle(String name, String mode) throws IOException { this(new File(name), mode); } // -- NIOFileHandle API methods -- /** * Set the default buffer size for read-only files. * * Subsequent uses of the NIOFileHandle(String, String) and * NIOFileHandle(File, String) constructors will use this buffer size. */ public static void setDefaultBufferSize(int size) { defaultBufferSize = size; } /** * Set the default buffer size for read/write files. * * Subsequent uses of the NIOFileHandle(String, String) and * NIOFileHandle(File, String) constructors will use this buffer size. */ public static void setDefaultReadWriteBufferSize(int size) { defaultRWBufferSize = size; } // -- FileHandle and Channel API methods -- /** Gets the random access file object backing this FileHandle. */ public RandomAccessFile getRandomAccessFile() { return raf; } /** Gets the FileChannel from this FileHandle. */ public FileChannel getFileChannel() { return channel; } /** Gets the current buffer size. */ public int getBufferSize() { return bufferSize; } // -- AbstractNIOHandle API methods -- /* @see AbstractNIOHandle.setLength(long) */ public void setLength(long length) throws IOException { raf.seek(length - 1); raf.write((byte) 0); buffer = null; } // -- IRandomAccess API methods -- /* @see IRandomAccess.close() */ public void close() throws IOException { raf.close(); } /* @see IRandomAccess.getFilePointer() */ public long getFilePointer() { return position; } /* @see IRandomAccess.length() */ public long length() throws IOException { if (defaultLength != null) { return defaultLength; } return raf.length(); } /* @see IRandomAccess.getOrder() */ public ByteOrder getOrder() { return buffer == null ? order : buffer.order(); } /* @see IRandomAccess.setOrder(ByteOrder) */ public void setOrder(ByteOrder order) { this.order = order; if (buffer != null) { buffer.order(order); } } /* @see IRandomAccess.read(byte[]) */ public int read(byte[] b) throws IOException { return read(ByteBuffer.wrap(b)); } /* @see IRandomAccess.read(byte[], int, int) */ public int read(byte[] b, int off, int len) throws IOException { return read(ByteBuffer.wrap(b), off, len); } /* @see IRandomAccess.read(ByteBuffer) */ public int read(ByteBuffer buf) throws IOException { return read(buf, 0, buf.capacity()); } /* @see IRandomAccess.read(ByteBuffer, int, int) */ public int read(ByteBuffer buf, int off, int len) throws IOException { buf.position(off); buf.limit(off + len); channel.position(position); int readLength = channel.read(buf); buffer(position + readLength, 0); // Return value of NIO channel's is -1 when zero bytes are read at the end // of the file. return readLength == -1? 0 : readLength; } /* @see IRandomAccess.seek(long) */ public void seek(long pos) throws IOException { if (mapMode == FileChannel.MapMode.READ_WRITE && pos > length()) { setLength(pos); } buffer(pos, 0); } /* @see java.io.DataInput.readBoolean() */ public boolean readBoolean() throws IOException { return readByte() == 1; } /* @see java.io.DataInput.readByte() */ public byte readByte() throws IOException { buffer(position, 1); position += 1; try { return buffer.get(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readChar() */ public char readChar() throws IOException { buffer(position, 2); position += 2; try { return buffer.getChar(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readDouble() */ public double readDouble() throws IOException { buffer(position, 8); position += 8; try { return buffer.getDouble(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readFloat() */ public float readFloat() throws IOException { buffer(position, 4); position += 4; try { return buffer.getFloat(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readFully(byte[]) */ public void readFully(byte[] b) throws IOException { read(b); } /* @see java.io.DataInput.readFully(byte[], int, int) */ public void readFully(byte[] b, int off, int len) throws IOException { read(b, off, len); } /* @see java.io.DataInput.readInt() */ public int readInt() throws IOException { buffer(position, 4); position += 4; try { return buffer.getInt(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readLine() */ public String readLine() throws IOException { raf.seek(position); String line = raf.readLine(); buffer(raf.getFilePointer(), 0); return line; } /* @see java.io.DataInput.readLong() */ public long readLong() throws IOException { buffer(position, 8); position += 8; try { return buffer.getLong(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readShort() */ public short readShort() throws IOException { buffer(position, 2); position += 2; try { return buffer.getShort(); } catch (BufferUnderflowException e) { EOFException eof = new EOFException(EOF_ERROR_MSG); eof.initCause(e); throw eof; } } /* @see java.io.DataInput.readUnsignedByte() */ public int readUnsignedByte() throws IOException { return readByte() & 0xFF; } /* @see java.io.DataInput.readUnsignedShort() */ public int readUnsignedShort() throws IOException { return readShort() & 0xFFFF; } /* @see java.io.DataInput.readUTF() */ public String readUTF() throws IOException { raf.seek(position); String utf8 = raf.readUTF(); buffer(raf.getFilePointer(), 0); return utf8; } /* @see java.io.DataInput.skipBytes(int) */ public int skipBytes(int n) throws IOException { if (n < 1) { return 0; } long oldPosition = position; long newPosition = oldPosition + Math.min(n, length()); buffer(newPosition, 0); return (int) (position - oldPosition); } // -- DataOutput API methods -- /* @see java.io.DataOutput.write(byte[]) */ public void write(byte[] b) throws IOException { write(ByteBuffer.wrap(b)); } /* @see java.io.DataOutput.write(byte[], int, int) */ public void write(byte[] b, int off, int len) throws IOException { write(ByteBuffer.wrap(b), off, len); } /* @see IRandomAccess.write(ByteBuffer) */ public void write(ByteBuffer buf) throws IOException { write(buf, 0, buf.capacity()); } /* @see IRandomAccess.write(ByteBuffer, int, int) */ public void write(ByteBuffer buf, int off, int len) throws IOException { writeSetup(len); buf.limit(off + len); buf.position(off); position += channel.write(buf, position); buffer = null; } /* @see java.io.DataOutput.write(int b) */ public void write(int b) throws IOException { writeByte(b); } /* @see java.io.DataOutput.writeBoolean(boolean) */ public void writeBoolean(boolean v) throws IOException { writeByte(v ? 1 : 0); } /* @see java.io.DataOutput.writeByte(int) */ public void writeByte(int v) throws IOException { writeSetup(1); buffer.put((byte) v); doWrite(1); } /* @see java.io.DataOutput.writeBytes(String) */ public void writeBytes(String s) throws IOException { write(s.getBytes(Constants.ENCODING)); } /* @see java.io.DataOutput.writeChar(int) */ public void writeChar(int v) throws IOException { writeSetup(2); buffer.putChar((char) v); doWrite(2); } /* @see java.io.DataOutput.writeChars(String) */ public void writeChars(String s) throws IOException { write(s.getBytes("UTF-16BE")); } /* @see java.io.DataOutput.writeDouble(double) */ public void writeDouble(double v) throws IOException { writeSetup(8); buffer.putDouble(v); doWrite(8); } /* @see java.io.DataOutput.writeFloat(float) */ public void writeFloat(float v) throws IOException { writeSetup(4); buffer.putFloat(v); doWrite(4); } /* @see java.io.DataOutput.writeInt(int) */ public void writeInt(int v) throws IOException { writeSetup(4); buffer.putInt(v); doWrite(4); } /* @see java.io.DataOutput.writeLong(long) */ public void writeLong(long v) throws IOException { writeSetup(8); buffer.putLong(v); doWrite(8); } /* @see java.io.DataOutput.writeShort(int) */ public void writeShort(int v) throws IOException { writeSetup(2); buffer.putShort((short) v); doWrite(2); } /* @see java.io.DataOutput.writeUTF(String) */ public void writeUTF(String str) throws IOException { // NB: number of bytes written is greater than the length of the string int strlen = str.getBytes(Constants.ENCODING).length + 2; writeSetup(strlen); raf.seek(position); raf.writeUTF(str); position += strlen; buffer = null; } /** * Aligns the NIO buffer, maps it if it is not currently and sets all * relevant positions and offsets. * @param offset The location within the file to read from. * @param size The requested read length. * @throws IOException If there is an issue mapping, aligning or allocating * the buffer. */ private void buffer(long offset, int size) throws IOException { position = offset; long newPosition = offset + size; if (newPosition < bufferStartPosition || newPosition > bufferStartPosition + bufferSize || buffer == null) { bufferStartPosition = offset; if (length() > 0 && length() - 1 < bufferStartPosition) { bufferStartPosition = length() - 1; } long newSize = Math.min(length() - bufferStartPosition, bufferSize); if (newSize < size && newSize == bufferSize) newSize = size; if (newSize + bufferStartPosition > length()) { newSize = length() - bufferStartPosition; } offset = bufferStartPosition; ByteOrder byteOrder = buffer == null ? order : getOrder(); buffer = byteBufferProvider.allocate(bufferStartPosition, (int) newSize); if (byteOrder != null) setOrder(byteOrder); } buffer.position((int) (offset - bufferStartPosition)); if (buffer.position() + size > buffer.limit() && mapMode == FileChannel.MapMode.READ_WRITE) { buffer.limit(buffer.position() + size); } } private void writeSetup(int length) throws IOException { validateLength(length); buffer(position, length); } private void doWrite(int length) throws IOException { buffer.position(buffer.position() - length); channel.write(buffer, position); position += length; } }
package bdv.viewer; import bdv.viewer.state.SourceGroup; import bdv.viewer.state.SourceState; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static bdv.viewer.DisplayMode.FUSED; import static bdv.viewer.DisplayMode.FUSEDGROUP; import static bdv.viewer.DisplayMode.GROUP; import static bdv.viewer.DisplayMode.SINGLE; import static bdv.viewer.VisibilityAndGrouping.Event.CURRENT_GROUP_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.CURRENT_SOURCE_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.DISPLAY_MODE_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.GROUP_ACTIVITY_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.GROUP_NAME_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.SOURCE_ACTVITY_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.SOURCE_TO_GROUP_ASSIGNMENT_CHANGED; import static bdv.viewer.VisibilityAndGrouping.Event.VISIBILITY_CHANGED; /** * @deprecated This is not necessary anymore, because {@link ViewerState} can be modified directly. * (See {@link ViewerPanel#state()}.) * * Manage visibility and currentness of sources and groups, as well as grouping * of sources, and display mode. * * @author Tobias Pietzsch &lt;tobias.pietzsch@gmail.com&gt; */ @Deprecated public class VisibilityAndGrouping { @Deprecated public static final class Event { public static final int CURRENT_SOURCE_CHANGED = 0; public static final int CURRENT_GROUP_CHANGED = 1; public static final int SOURCE_ACTVITY_CHANGED = 2; public static final int GROUP_ACTIVITY_CHANGED = 3; public static final int DISPLAY_MODE_CHANGED = 4; public static final int SOURCE_TO_GROUP_ASSIGNMENT_CHANGED = 5; public static final int GROUP_NAME_CHANGED = 6; public static final int VISIBILITY_CHANGED = 7; public static final int NUM_SOURCES_CHANGED = 8; public static final int NUM_GROUPS_CHANGED = 9; public final int id; public final VisibilityAndGrouping visibilityAndGrouping; public Event( final int id, final VisibilityAndGrouping v ) { this.id = id; this.visibilityAndGrouping = v; } } @Deprecated public interface UpdateListener { void visibilityChanged( Event e ); } protected final CopyOnWriteArrayList< UpdateListener > updateListeners; private final bdv.viewer.state.ViewerState deprecatedViewerState; private final ViewerState state; @Deprecated public ViewerState getState() { return state; } @Deprecated public VisibilityAndGrouping( final bdv.viewer.state.ViewerState viewerState ) { updateListeners = new CopyOnWriteArrayList<>(); deprecatedViewerState = viewerState; state = viewerState.getState(); viewerState.getState().changeListeners().add( e -> { switch ( e ) { case CURRENT_SOURCE_CHANGED: update( Event.CURRENT_SOURCE_CHANGED ); break; case CURRENT_GROUP_CHANGED: update( Event.CURRENT_GROUP_CHANGED ); break; case SOURCE_ACTIVITY_CHANGED: update( Event.SOURCE_ACTVITY_CHANGED ); break; case GROUP_ACTIVITY_CHANGED: update( Event.GROUP_ACTIVITY_CHANGED ); break; case SOURCE_TO_GROUP_ASSIGNMENT_CHANGED: update( Event.SOURCE_TO_GROUP_ASSIGNMENT_CHANGED ); break; case GROUP_NAME_CHANGED: update( Event.GROUP_NAME_CHANGED ); break; case NUM_SOURCES_CHANGED: update( Event.NUM_SOURCES_CHANGED ); break; case NUM_GROUPS_CHANGED: update( Event.NUM_GROUPS_CHANGED ); break; case VISIBILITY_CHANGED: update( Event.VISIBILITY_CHANGED ); break; case DISPLAY_MODE_CHANGED: update( Event.DISPLAY_MODE_CHANGED ); break; } } ); } @Deprecated public int numSources() { return state.getSources().size(); } @Deprecated public List< SourceState< ? > > getSources() { return deprecatedViewerState.getSources(); } @Deprecated public int numGroups() { return state.getGroups().size(); } @Deprecated public List< SourceGroup > getSourceGroups() { return deprecatedViewerState.getSourceGroups(); } @Deprecated public synchronized DisplayMode getDisplayMode() { return state.getDisplayMode(); } @Deprecated public synchronized void setDisplayMode( final DisplayMode displayMode ) { state.setDisplayMode( displayMode ); } @Deprecated public synchronized int getCurrentSource() { return state.getSources().indexOf( state.getCurrentSource() ); } /** * TODO * * @param sourceIndex */ @Deprecated public synchronized void setCurrentSource( final int sourceIndex ) { if ( sourceIndex < 0 || sourceIndex >= numSources() ) return; state.setCurrentSource( state.getSources().get( sourceIndex ) ); }; @Deprecated public synchronized void setCurrentSource( final Source< ? > source ) { state.setCurrentSource( soc( source ) ); }; @Deprecated public synchronized boolean isSourceActive( final int sourceIndex ) { if ( sourceIndex < 0 || sourceIndex >= numSources() ) return false; return state.isSourceActive( state.getSources().get( sourceIndex ) ); } /** * Set the source active (visible in fused mode) or inactive. * * @param sourceIndex * @param isActive */ @Deprecated public synchronized void setSourceActive( final int sourceIndex, final boolean isActive ) { if ( sourceIndex < 0 || sourceIndex >= numSources() ) return; state.setSourceActive( state.getSources().get( sourceIndex ), isActive ); } /** * Set the source active (visible in fused mode) or inactive. * * @param source * @param isActive */ @Deprecated public synchronized void setSourceActive( final Source< ? > source, final boolean isActive ) { state.setSourceActive( soc( source ), isActive ); } @Deprecated public synchronized int getCurrentGroup() { return state.getGroups().indexOf( state.getCurrentGroup() ); } /** * TODO * * @param groupIndex */ @Deprecated public synchronized void setCurrentGroup( final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; final bdv.viewer.SourceGroup group = state.getGroups().get( groupIndex ); state.setCurrentGroup( group ); final List< SourceAndConverter< ? > > sources = new ArrayList<>( state.getSourcesInGroup( group ) ); if ( ! sources.isEmpty() ) { sources.sort( state.sourceOrder() ); state.setCurrentSource( sources.get( 0 ) ); } } @Deprecated public synchronized boolean isGroupActive( final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return false; return state.isGroupActive( state.getGroups().get( groupIndex ) ); } /** * Set the group active (visible in fused mode) or inactive. * * @param groupIndex * @param isActive */ @Deprecated public synchronized void setGroupActive( final int groupIndex, final boolean isActive ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.setGroupActive( state.getGroups().get( groupIndex ), isActive ); } @Deprecated public synchronized void setGroupName( final int groupIndex, final String name ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.setGroupName( state.getGroups().get( groupIndex ), name ); } @Deprecated public synchronized void addSourceToGroup( final int sourceIndex, final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.addSourceToGroup( state.getSources().get( sourceIndex ), state.getGroups().get( groupIndex ) ); } @Deprecated public synchronized void removeSourceFromGroup( final int sourceIndex, final int groupIndex ) { if ( groupIndex < 0 || groupIndex >= numGroups() ) return; state.removeSourceFromGroup( state.getSources().get( sourceIndex ), state.getGroups().get( groupIndex ) ); } /** * TODO * @param index */ @Deprecated public synchronized void setCurrentGroupOrSource( final int index ) { if ( isGroupingEnabled() ) setCurrentGroup( index ); else setCurrentSource( index ); } /** * TODO * @param index */ @Deprecated public synchronized void toggleActiveGroupOrSource( final int index ) { if ( isGroupingEnabled() ) setGroupActive( index, !isGroupActive( index ) ); else setSourceActive( index, !isSourceActive( index ) ); } @Deprecated public synchronized boolean isGroupingEnabled() { final DisplayMode mode = state.getDisplayMode(); return ( mode == GROUP ) || ( mode == FUSEDGROUP ); } @Deprecated public synchronized boolean isFusedEnabled() { final DisplayMode mode = state.getDisplayMode(); return ( mode == FUSED ) || ( mode == FUSEDGROUP ); } @Deprecated public synchronized void setGroupingEnabled( final boolean enable ) { setDisplayMode( isFusedEnabled() ? ( enable ? FUSEDGROUP : FUSED ) : ( enable ? GROUP : SINGLE ) ); } @Deprecated public synchronized void setFusedEnabled( final boolean enable ) { setDisplayMode( isGroupingEnabled() ? ( enable ? FUSEDGROUP : GROUP ) : ( enable ? FUSED : SINGLE ) ); } @Deprecated public synchronized boolean isSourceVisible( final int sourceIndex ) { return state.isSourceVisibleAndPresent( state.getSources().get( sourceIndex ) ); } @Deprecated protected void update( final int id ) { final Event event = new Event( id, this ); for ( final UpdateListener l : updateListeners ) l.visibilityChanged( event ); } @Deprecated public void addUpdateListener( final UpdateListener l ) { updateListeners.add( l ); } @Deprecated public void removeUpdateListener( final UpdateListener l ) { updateListeners.remove( l ); } @Deprecated private SourceAndConverter< ? > soc( Source< ? > source ) { for ( SourceAndConverter< ? > soc : state.getSources() ) if ( soc.getSpimSource() == source ) return soc; return null; } }
package br.icc.ddd.scrum.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; /** * Toda entidade do sistema deve herdar desta classe abstrata */ @MappedSuperclass public abstract class Entidade implements Serializable { private static final long serialVersionUID = 4394209939156982282L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true) protected Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
package com.airbnb.plog; import com.google.common.cache.CacheBuilder; import com.google.common.cache.Weigher; import com.typesafe.config.Config; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import lombok.Data; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class PlogDefragmenter extends MessageToMessageDecoder<MultiPartMessageFragment> { private final StatisticsReporter stats; private final Map<Long, IncomingMultiPartMessage> incompleteMessages; private final Charset charset; public PlogDefragmenter(Charset charset, StatisticsReporter stats, Config config) { this.charset = charset; this.stats = stats; incompleteMessages = new CacheBuilder<Long, IncomingMultiPartMessage>() .maximumWeight(config.getInt("max_size")) .weigher(new Weigher<Long, IncomingMultiPartMessage>() { @Override public int weigh(Long id, IncomingMultiPartMessage msg) { return msg.length(); } }).build(); } private long identifierFor(MultiPartMessageFragment fragment) { return fragment.getMsgId() + (2 ^ 32) * fragment.getMsgPort(); } private synchronized IngestionResult ingestIntoIncompleteMessage(MultiPartMessageFragment fragment) { final long id = identifierFor(fragment); final IncomingMultiPartMessage fromMap = incompleteMessages.get(id); if (fromMap != null) { fromMap.ingestFragment(fragment); return new IngestionResult(false, id, fromMap); } else { IncomingMultiPartMessage message = IncomingMultiPartMessage.fromFragment(fragment); insertInMap(id, message); return new IngestionResult(true, id, message); } } private IncomingMultiPartMessage fragmentToMessage(MultiPartMessageFragment fragment) { if (fragment.isAlone()) return IncomingMultiPartMessage.fromFragment(fragment); /* Actually multi-part */ final IngestionResult ingestion = ingestIntoIncompleteMessage(fragment); if (ingestion.isInsertion()) while (payloadSize.get() > maxPayloadSize) removeFromMap(incompleteMessages.entrySet().iterator().next().getKey()); else if (ingestion.getMessage().isComplete()) removeFromMap(ingestion.getId()); return ingestion.getMessage(); } private void removeFromMap(long id) { final IncomingMultiPartMessage removed = incompleteMessages.remove(id); if (removed != null) payloadSize.addAndGet(-1 * removed.length()); } private void insertInMap(long id, IncomingMultiPartMessage message) { incompleteMessages.put(id, message); payloadSize.addAndGet(message.length()); } @Override protected void decode(ChannelHandlerContext ctx, MultiPartMessageFragment fragment, List<Object> out) throws Exception { final IncomingMultiPartMessage msg = fragmentToMessage(fragment); if (msg.isComplete()) { final ByteBuf payload = msg.getPayload(); out.add(payloadToString(payload)); stats.receivedV0MultipartMessage(); } } private String payloadToString(ByteBuf payload) { final int length = payload.readableBytes(); final byte[] bytes = new byte[length]; payload.readBytes(bytes, 0, length); return new String(bytes, charset); } @Data private static final class IngestionResult { final boolean insertion; final long id; final IncomingMultiPartMessage message; } }
package com.amee.domain; import com.amee.domain.data.DataCategory; import com.amee.domain.data.DataItem; import com.amee.domain.item.BaseItemValue; import com.amee.domain.item.data.NuDataItem; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; public interface IDataItemService extends IItemService { public final static Date EPOCH = new Date(0); public List<NuDataItem> getDataItems(IDataCategoryReference dataCategory); public List<NuDataItem> getDataItems(Set<Long> dataItemIds); public Map<String, NuDataItem> getDataItemMap(Set<Long> dataItemIds, boolean loadValues); public NuDataItem getItemByUid(String uid); public NuDataItem getDataItemByPath(DataCategory parent, String path); public String getLabel(NuDataItem dataItem); public void persist(NuDataItem dataItem); public void persist(BaseItemValue itemValue); public void remove(DataItem dataItem); }
package com.auth0.exception; import java.util.Collections; import java.util.Map; /** * Class that represents an Auth0 Server error captured from a http response. Provides different methods to get a clue of why the request failed. * i.e.: * <pre> * {@code * { * statusCode: 400, * description: "Query validation error: 'String 'users' does not match pattern. Must be a comma separated list of the following values: name,strategy,options,enabled_clients,id,provisioning_ticket_url' on property fields (A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve all fields).", * error: "invalid_query_string" * } * } * </pre> */ @SuppressWarnings("WeakerAccess") public class APIException extends Auth0Exception { private String error; private String description; private int statusCode; private Map<String, Object> values; public APIException(String payload, int statusCode, Throwable cause) { super(createMessage(payload, statusCode), cause); this.description = payload; this.statusCode = statusCode; } public APIException(Map<String, Object> values, int statusCode) { super(createMessage(obtainExceptionMessage(values), statusCode)); this.values = Collections.unmodifiableMap(values); this.error = obtainExceptionError(this.values); this.description = obtainExceptionMessage(this.values); this.statusCode = statusCode; } /** * Getter for the Http Status Code received in the response. * i.e. a {@code status_code=403} would mean that the token has an insufficient scope. * * @return the status code. */ public int getStatusCode() { return statusCode; } /** * Getter for the exception error code. * i.e. a {@code error=invalid_query_string} would mean that the query parameters sent in the request were invalid. * * @return the error code. */ public String getError() { return error; } /** * Returns a value from the error map, if any. * * @param key key of the value to return * @return the value if found or null */ public Object getValue(String key) { if (values == null) { return null; } return values.get(key); } /** * Getter for the exception user friendly description of why the request failed. * i.e. the description may say which query parameters are valid for that endpoint. * * @return the description. */ public String getDescription() { return description; } private static String createMessage(String description, int statusCode) { return String.format("Request failed with status code %d: %s", statusCode, description); } private static String obtainExceptionMessage(Map<String, Object> values) { if (values.containsKey("error_description")) { return (String) values.get("error_description"); } if (values.containsKey("description")) { Object description = values.get("description"); if (description instanceof String) { return (String) description; } else { PasswordStrengthErrorParser policy = new PasswordStrengthErrorParser((Map<String, Object>) description); return policy.getDescription(); } } if (values.containsKey("message")) { return (String) values.get("message"); } if (values.containsKey("error")) { return (String) values.get("error"); } return "Unknown exception"; } private static String obtainExceptionError(Map<String, Object> values) { if (values.containsKey("errorCode")) { return (String) values.get("errorCode"); } if (values.containsKey("error")) { return (String) values.get("error"); } if (values.containsKey("code")) { return (String) values.get("code"); } return "Unknown error"; } }
package com.comphenix.example; import com.google.common.base.Splitter; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.primitives.Primitives; import kernitus.plugin.OldCombatMechanics.utilities.reflection.Reflector; import kernitus.plugin.OldCombatMechanics.utilities.reflection.type.ClassType; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.concurrent.ConcurrentMap; public class NbtFactory { // Convert between NBT id and the equivalent class in java private static final BiMap<Integer, Class<?>> NBT_CLASS = HashBiMap.create(); private static final BiMap<Integer, NbtType> NBT_ENUM = HashBiMap.create(); // Shared instance private static NbtFactory INSTANCE; private final Field[] DATA_FIELD = new Field[12]; // The NBT base class private Class<?> BASE_CLASS; private Class<?> COMPOUND_CLASS; private Method NBT_CREATE_TAG; private Method NBT_GET_TYPE; private Field NBT_LIST_TYPE; // CraftItemStack private Class<?> CRAFT_STACK; private Field CRAFT_HANDLE; private Field STACK_TAG; /** * Construct an instance of the NBT factory by deducing the class of NBTBase. */ private NbtFactory(){ if(BASE_CLASS == null){ try{ // Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing // with CraftBukkit or its derivatives. This does not work in MCPC+ however. ClassLoader loader = NbtFactory.class.getClassLoader(); //String packageName = "org.bukkit.craftbukkit.v1_6_R2"; String packageName = Bukkit.getServer().getClass().getPackage().getName(); Class<?> offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); // Prepare NBT COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); BASE_CLASS = Reflector.getClass(ClassType.NMS, "NBTBase"); NBT_GET_TYPE = getMethod(0, Modifier.STATIC, BASE_CLASS, "getTypeId"); NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, BASE_CLASS, "createTag", byte.class); // Prepare CraftItemStack CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); CRAFT_HANDLE = getField(null, CRAFT_STACK, "handle"); STACK_TAG = getField(null, CRAFT_HANDLE.getType(), "tag"); // Loading/saving // LOAD_COMPOUND = getMethod(Modifier.STATIC, 0, BASE_CLASS, null, DataInput.class); // SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, BASE_CLASS, null, BASE_CLASS, DataOutput.class); } catch(ClassNotFoundException e){ throw new IllegalStateException("Unable to find offline player.", e); } } } /* Loading/saving compounds private Method LOAD_COMPOUND; private Method SAVE_COMPOUND;*/ /** * Retrieve or construct a shared NBT factory. * * @return The factory. */ private static NbtFactory get(){ if(INSTANCE == null) INSTANCE = new NbtFactory(); return INSTANCE; } /** * Construct a new NBT list of an unspecified type. * * @return The NBT list. */ public static NbtList createList(Object... content){ return createList(Arrays.asList(content)); } /** * Construct a new NBT list of an unspecified type. * * @return The NBT list. */ public static NbtList createList(Iterable<?> iterable){ NbtList list = get().new NbtList( INSTANCE.createNbtTag(NbtType.TAG_LIST, "", null) ); // Add the content as well for(Object obj : iterable) list.add(obj); return list; } /** * Construct a new NBT compound. * <p> * * @return The NBT compound. */ public static NbtCompound createCompound(){ return get().new NbtCompound( INSTANCE.createNbtTag(NbtType.TAG_COMPOUND, "", null) ); } /** * Construct a new NBT root compound. * <p> * This compound must be given a name, as it is the root object. * * @param name - the name of the compound. * @return The NBT compound. */ public static NbtCompound createRootCompound(String name){ return get().new NbtCompound( INSTANCE.createNbtTag(NbtType.TAG_COMPOUND, name, null) ); } /** * Construct a new NBT wrapper from a list. * * @param nmsList - the NBT list. * @return The wrapper. */ public static NbtList fromList(Object nmsList){ return get().new NbtList(nmsList); } /** * Construct a new NBT wrapper from a compound. * * @param nmsCompound - the NBT compund. * @return The wrapper. */ public static NbtCompound fromCompound(Object nmsCompound){ return get().new NbtCompound(nmsCompound); } public static void setItemTag(ItemStack stack, NbtCompound compound){ checkItemStack(stack); Object nms = getFieldValue(get().CRAFT_HANDLE, stack); // Now update the tag compound setFieldValue(get().STACK_TAG, nms, compound.getHandle()); } /** * Construct a wrapper for an NBT tag stored (in memory) in an item stack. This is where * auxillary data such as enchanting, name and lore is stored. It does not include items * material, damage value or count. * <p> * The item stack must be a wrapper for a CraftItemStack. * * @param stack - the item stack. * @return A wrapper for its NBT tag. */ public static NbtCompound fromItemTag(ItemStack stack){ checkItemStack(stack); Object nms = getFieldValue(get().CRAFT_HANDLE, stack); Object tag = getFieldValue(get().STACK_TAG, nms); // Create the tag if it doesn't exist if(tag == null){ NbtCompound compound = createRootCompound("tag"); setItemTag(stack, compound); return compound; } return fromCompound(tag); } /** * Retrieve a CraftItemStack version of the stack. * * @param stack - the stack to convert. * @return The CraftItemStack version. */ public static ItemStack getCraftItemStack(ItemStack stack){ // Any need to convert? if(stack == null || get().CRAFT_STACK.isAssignableFrom(stack.getClass())) return stack; try{ // Call the private constructor Constructor<?> caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class); caller.setAccessible(true); return (ItemStack) caller.newInstance(stack); } catch(Exception e){ throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); } } /** * Ensure that the given stack can store arbitrary NBT information. * * @param stack - the stack to check. */ private static void checkItemStack(ItemStack stack){ if(stack == null) throw new IllegalArgumentException("Stack cannot be NULL."); if(!get().CRAFT_STACK.isAssignableFrom(stack.getClass())) throw new IllegalArgumentException("Stack must be a CraftItemStack, found " + stack.getClass().getSimpleName()); if(stack.getType() == Material.AIR) throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information."); } /** * Invoke a method on the given target instance using the provided parameters. * * @param method - the method to invoke. * @param target - the target. * @param params - the parameters to supply. * @return The result of the method. */ private static Object invokeMethod(Method method, Object target, Object... params){ try{ return method.invoke(target, params); } catch(Exception e){ throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); } } private static void setFieldValue(Field field, Object target, Object value){ try{ field.set(target, value); } catch(Exception e){ throw new RuntimeException("Unable to set " + field + " for " + target, e); } } // /** // * Load the content of a file from a stream. // * <p> // * Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file. // * @param stream - the stream supplier. // * @param option - whether or not to decompress the input stream. // * @return The decoded NBT compound. // * @throws IOException If anything went wrong. // */ // public static NbtCompound fromStream(InputSupplier<? extends InputStream> stream, StreamOptions option) throws IOException { // InputStream input = null; // DataInputStream data = null; // try { // input = stream.getInput(); // data = new DataInputStream(new BufferedInputStream( // option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input // return fromCompound(invokeMethod(get().LOAD_COMPOUND, null, data)); // } finally { // if (data != null) // Closeables.closeQuietly(data); // if (input != null) // Closeables.closeQuietly(input); // /** // * Save the content of a NBT compound to a stream. // * <p> // * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. // * // * @param source - the NBT compound to save. // * @param stream - the stream. // * @param option - whether or not to compress the output. // * @throws IOException If anything went wrong. // */ // public static void saveStream(NbtCompound source, OutputSupplier<? extends OutputStream> stream, StreamOptions option) throws IOException { // OutputStream output = null; // DataOutputStream data = null; // try { // output = stream.getOutput(); // data = new DataOutputStream( // option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output // invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); // } finally { // if (data != null) { // try { // data.close(); // } catch (Exception e) { // if (output != null) { // try { // output.close(); // } catch (Exception e) { private static Object getFieldValue(Field field, Object target){ try{ return field.get(target); } catch(Exception e){ throw new RuntimeException("Unable to retrieve " + field + " for " + target, e); } } private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName, Class<?>... params){ for(Method method : clazz.getDeclaredMethods()){ // Limitation: Doesn't handle overloads if((method.getModifiers() & requireMod) == requireMod && (method.getModifiers() & bannedMod) == 0 && (methodName == null || method.getName().equals(methodName)) && Arrays.equals(method.getParameterTypes(), params)){ method.setAccessible(true); return method; } } // Search in every superclass if(clazz.getSuperclass() != null) return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params); throw new IllegalStateException(String.format( "Unable to find method %s (%s).", methodName, Arrays.asList(params))); } private static Field getField(Object instance, Class<?> clazz, String fieldName){ if(clazz == null) clazz = instance.getClass(); // Ignore access rules for(Field field : clazz.getDeclaredFields()){ if(field.getName().equals(fieldName)){ field.setAccessible(true); return field; } } // Recursively fild the correct field if(clazz.getSuperclass() != null) return getField(instance, clazz.getSuperclass(), fieldName); throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); } @SuppressWarnings("unchecked") private Map<String, Object> getDataMap(Object handle){ return (Map<String, Object>) getFieldValue( getDataField(NbtType.TAG_COMPOUND, handle), handle); } @SuppressWarnings("unchecked") private List<Object> getDataList(Object handle){ return (List<Object>) getFieldValue( getDataField(NbtType.TAG_LIST, handle), handle); } /** * Convert wrapped List and Map objects into their respective NBT counterparts. * * @param name - the name of the NBT element to create. * @param value - the value of the element to create. Can be a List or a Map. * @return The NBT element. */ private Object unwrapValue(String name, Object value){ if(value == null) return null; if(value instanceof Wrapper){ return ((Wrapper) value).getHandle(); } else if(value instanceof List){ throw new IllegalArgumentException("Can only insert a WrappedList."); } else if(value instanceof Map){ throw new IllegalArgumentException("Can only insert a WrappedCompound."); } else { return createNbtTag(getPrimitiveType(value), name, value); } } /** * Convert a given NBT element to a primitive wrapper or List/Map equivalent. * <p> * All changes to any mutable objects will be reflected in the underlying NBT element(s). * * @param nms - the NBT element. * @return The wrapper equivalent. */ private Object wrapNative(Object nms){ if(nms == null) return null; if(BASE_CLASS.isAssignableFrom(nms.getClass())){ final NbtType type = getNbtType(nms); // Handle the different types switch(type){ case TAG_COMPOUND: return new NbtCompound(nms); case TAG_LIST: return new NbtList(nms); default: return getFieldValue(getDataField(type, nms), nms); } } throw new IllegalArgumentException("Unexpected type: " + nms); } /** * Construct a new NMS NBT tag initialized with the given value. * * @param type - the NBT type. * @param name - the name of the NBT tag. * @param value - the value, or NULL to keep the original value. * @return The created tag. */ private Object createNbtTag(NbtType type, String name, Object value){ Object tag = invokeMethod(NBT_CREATE_TAG, null, (byte) type.id); if(value != null){ setFieldValue(getDataField(type, tag), tag, value); } return tag; } /** * Retrieve the field where the NBT class stores its value. * * @param type - the NBT type. * @param nms - the NBT class instance. * @return The corresponding field. */ private Field getDataField(NbtType type, Object nms){ if(DATA_FIELD[type.id] == null) DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); return DATA_FIELD[type.id]; } /** * Retrieve the NBT type from a given NMS NBT tag. * * @param nms - the native NBT tag. * @return The corresponding type. */ private NbtType getNbtType(Object nms){ int type = (Byte) invokeMethod(NBT_GET_TYPE, nms); return NBT_ENUM.get(type); } /** * Retrieve the nearest NBT type for a given primitive type. * * @param primitive - the primitive type. * @return The corresponding type. */ private NbtType getPrimitiveType(Object primitive){ NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get( Primitives.unwrap(primitive.getClass()) )); if(type == null) throw new IllegalArgumentException(String.format( "Illegal type: %s (%s)", primitive.getClass(), primitive)); return type; } /** * Whether or not to enable stream compression. * * @author Kristian */ public enum StreamOptions { NO_COMPRESSION, GZIP_COMPRESSION, } private enum NbtType { TAG_END(0, Void.class), TAG_BYTE(1, byte.class), TAG_SHORT(2, short.class), TAG_INT(3, int.class), TAG_LONG(4, long.class), TAG_FLOAT(5, float.class), TAG_DOUBLE(6, double.class), TAG_BYTE_ARRAY(7, byte[].class), TAG_INT_ARRAY(11, int[].class), TAG_STRING(8, String.class), TAG_LIST(9, List.class), TAG_COMPOUND(10, Map.class); // Unique NBT id public final int id; NbtType(int id, Class<?> type){ this.id = id; NBT_CLASS.put(id, type); NBT_ENUM.put(id, this); } private String getFieldName(){ if(this == TAG_COMPOUND) return "map"; else if(this == TAG_LIST) return "list"; else return "data"; } } /** * Represents an object that provides a view of a native NMS class. * * @author Kristian */ public interface Wrapper { /** * Retrieve the underlying native NBT tag. * * @return The underlying NBT. */ Object getHandle(); } /** * Represents a root NBT compound. * <p> * All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: * <ul> * <li>Primitive types</li> * <li>{@link java.lang.String String}</li> * <li>{@link NbtList}</li> * <li>{@link NbtCompound}</li> * </ul> * <p> * See also: * <ul> * <li>{@link NbtFactory#createCompound()}</li> * <li>{@link NbtFactory#fromCompound(Object)}</li> * </ul> * * @author Kristian */ public final class NbtCompound extends ConvertedMap { private NbtCompound(Object handle){ super(handle, getDataMap(handle)); } // Simplifiying access to each value public Byte getByte(String key, Byte defaultValue){ return containsKey(key) ? (Byte) get(key) : defaultValue; } public Short getShort(String key, Short defaultValue){ return containsKey(key) ? (Short) get(key) : defaultValue; } public Integer getInteger(String key, Integer defaultValue){ return containsKey(key) ? (Integer) get(key) : defaultValue; } public Long getLong(String key, Long defaultValue){ return containsKey(key) ? (Long) get(key) : defaultValue; } public Float getFloat(String key, Float defaultValue){ return containsKey(key) ? (Float) get(key) : defaultValue; } public Double getDouble(String key, Double defaultValue){ return containsKey(key) ? (Double) get(key) : defaultValue; } public String getString(String key, String defaultValue){ return containsKey(key) ? (String) get(key) : defaultValue; } public byte[] getByteArray(String key, byte[] defaultValue){ return containsKey(key) ? (byte[]) get(key) : defaultValue; } public int[] getIntegerArray(String key, int[] defaultValue){ return containsKey(key) ? (int[]) get(key) : defaultValue; } /** * Method for when items are not created following NBTtag convention and have Integers where there should be Longs */ public Long getIntegerOrLong(String key, Long defaultValue){ if(!containsKey(key)) return defaultValue; //Try casting to long; if doesn't work try casting to integer, if successful convert Int to Long and return Long resultingValue = defaultValue; try{ resultingValue = (Long) get(key); } catch(ClassCastException e){ //It's not a long, try casting to integer try{ resultingValue = ((Integer) get(key)).longValue(); } catch(ClassCastException e1){ System.out.println("NBT value was neither a Long or an Integer"); e1.printStackTrace(); } } return resultingValue; } /** * Retrieve the list by the given name. * * @param key - the name of the list. * @param createNew - whether or not to create a new list if its missing. * @return An existing list, a new list or NULL. */ public NbtList getList(String key, boolean createNew){ NbtList list = (NbtList) get(key); if(list == null) put(key, list = createList()); return list; } /** * Retrieve the map by the given name. * * @param key - the name of the map. * @param createNew - whether or not to create a new map if its missing. * @return An existing map, a new map or NULL. */ public NbtCompound getMap(String key, boolean createNew){ return getMap(Collections.singletonList(key), createNew); } // Done /** * Set the value of an entry at a given location. * <p> * Every element of the path (except the end) are assumed to be compounds, and will * be created if they are missing. * * @param path - the path to the entry. * @param value - the new value of this entry. * @return This compound, for chaining. */ public NbtCompound putPath(String path, Object value){ List<String> entries = getPathElements(path); Map<String, Object> map = getMap(entries.subList(0, entries.size() - 1), true); map.put(entries.get(entries.size() - 1), value); return this; } /** * Retrieve the value of a given entry in the tree. * <p> * Every element of the path (except the end) are assumed to be compounds. The * retrieval operation will be cancelled if any of them are missing. * * @param path - path to the entry. * @return The value, or NULL if not found. */ @SuppressWarnings("unchecked") public <T> T getPath(String path){ List<String> entries = getPathElements(path); NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); if(map != null){ return (T) map.get(entries.get(entries.size() - 1)); } return null; } /** * Save the content of a NBT compound to a stream. * <p> * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. * @param stream - the output stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ // public void saveTo(OutputSupplier<? extends OutputStream> stream, StreamOptions option) throws IOException { // saveStream(this, stream, option); /** * Retrieve a map from a given path. * * @param path - path of compounds to look up. * @param createNew - whether or not to create new compounds on the way. * @return The map at this location. */ private NbtCompound getMap(Iterable<String> path, boolean createNew){ NbtCompound current = this; for(String entry : path){ NbtCompound child = (NbtCompound) current.get(entry); if(child == null){ if(!createNew) throw new IllegalArgumentException("Cannot find " + entry + " in " + path); current.put(entry, child = createCompound()); } current = child; } return current; } /** * Split the path into separate elements. * * @param path - the path to split. * @return The elements. */ private List<String> getPathElements(String path){ return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path)); } } /** * Represents a root NBT list. * See also: * <ul> * <li>{@link NbtFactory#fromList(Object)}</li> * </ul> * * @author Kristian */ public final class NbtList extends ConvertedList { private NbtList(Object handle){ super(handle, getDataList(handle)); } } /** * Represents a class for caching wrappers. * * @author Kristian */ private final class CachedNativeWrapper { // Don't recreate wrapper objects private final ConcurrentMap<Object, Object> cache = new MapMaker().weakKeys().makeMap(); public Object wrap(Object value){ Object current = cache.get(value); if(current == null){ current = wrapNative(value); // Only cache composite objects if(current instanceof ConvertedMap || current instanceof ConvertedList){ cache.put(value, current); } } return current; } } /** * Represents a map that wraps another map and automatically * converts entries of its type and another exposed type. * * @author Kristian */ private class ConvertedMap extends AbstractMap<String, Object> implements Wrapper { private final Object handle; private final Map<String, Object> original; private final CachedNativeWrapper cache = new CachedNativeWrapper(); public ConvertedMap(Object handle, Map<String, Object> original){ this.handle = handle; this.original = original; } // For converting back and forth protected Object wrapOutgoing(Object value){ return cache.wrap(value); } protected Object unwrapIncoming(String key, Object wrapped){ return unwrapValue(key, wrapped); } // Modification @Override public Object put(String key, Object value){ return wrapOutgoing(original.put( key, unwrapIncoming(key, value) )); } // Performance @Override public Object get(Object key){ return wrapOutgoing(original.get(key)); } @Override public Object remove(Object key){ return wrapOutgoing(original.remove(key)); } @Override public boolean containsKey(Object key){ return original.containsKey(key); } @Override public Set<Entry<String, Object>> entrySet(){ return new AbstractSet<Entry<String, Object>>() { @Override public boolean add(Entry<String, Object> e){ String key = e.getKey(); Object value = e.getValue(); original.put(key, unwrapIncoming(key, value)); return true; } @Override public int size(){ return original.size(); } @Override public Iterator<Entry<String, Object>> iterator(){ return ConvertedMap.this.iterator(); } }; } private Iterator<Entry<String, Object>> iterator(){ final Iterator<Entry<String, Object>> proxy = original.entrySet().iterator(); return new Iterator<Entry<String, Object>>() { public boolean hasNext(){ return proxy.hasNext(); } public Entry<String, Object> next(){ Entry<String, Object> entry = proxy.next(); return new SimpleEntry<>( entry.getKey(), wrapOutgoing(entry.getValue()) ); } public void remove(){ proxy.remove(); } }; } public Object getHandle(){ return handle; } } /** * Represents a list that wraps another list and converts elements * of its type and another exposed type. * * @author Kristian */ private class ConvertedList extends AbstractList<Object> implements Wrapper { private final Object handle; private final List<Object> original; private final CachedNativeWrapper cache = new CachedNativeWrapper(); public ConvertedList(Object handle, List<Object> original){ if(NBT_LIST_TYPE == null) NBT_LIST_TYPE = getField(handle, null, "type"); this.handle = handle; this.original = original; } protected Object wrapOutgoing(Object value){ return cache.wrap(value); } protected Object unwrapIncoming(Object wrapped){ return unwrapValue("", wrapped); } @Override public Object get(int index){ return wrapOutgoing(original.get(index)); } @Override public int size(){ return original.size(); } @Override public Object set(int index, Object element){ return wrapOutgoing( original.set(index, unwrapIncoming(element)) ); } @Override public void add(int index, Object element){ Object nbt = unwrapIncoming(element); // Set the list type if its the first element if(size() == 0) setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id); original.add(index, nbt); } @Override public Object remove(int index){ return wrapOutgoing(original.remove(index)); } @Override public boolean remove(Object o){ return original.remove(unwrapIncoming(o)); } public Object getHandle(){ return handle; } } }
package com.elytradev.concrete; import java.util.ArrayList; import java.util.Collection; import com.google.common.base.Supplier; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.wrapper.InvWrapper; public class NBTHelper { /** * Convert the given Collection of INBTSerializable objects into an * NBTTagList. */ public <T extends INBTSerializable<U>, U extends NBTBase> NBTTagList serialize(Collection<T> in) { NBTTagList out = new NBTTagList(); for (T t : in) { out.appendTag(t.serializeNBT()); } return out; } /** * Convert the given NBTTagList into an ArrayList of INBTSerializable * objects, using freshly-created objects from the passed constructor. * <p> * Example: {@code NBTHelper.deserialize(MyObject::new, myNBTList)} */ public <T extends INBTSerializable<U>, U extends NBTBase> ArrayList<T> deserialize(Supplier<T> constructor, NBTTagList in) { return deserialize(constructor, in, ArrayList::new); } /** * Convert the given NBTTagList into a Collection of INBTSerializable * objects, using freshly-created objects from the passed constructor, and * a freshly-created collection from the passed collection constructor. * <p> * Example: {@code NBTHelper.deserialize(MyObject::new, myNBTList, ArrayList::new)} */ public <T extends INBTSerializable<U>, U extends NBTBase, C extends Collection<T>> C deserialize(Supplier<T> constructor, NBTTagList in, Supplier<C> collectionConstructor) { return deserializeInto(constructor, in, collectionConstructor.get()); } /** * Add INBTSerializable objects from the given NBTTagList into a * pre-existing Collection of the correct type, using freshly-created * objects from the passed constructor. * <p> * This method does not clear the passed collection, that's up to you if you * want to do it. * <p> * Example: {@code NBTHelper.deserialize(MyObject::new, myNBTList, myList)} */ public <T extends INBTSerializable<U>, U extends NBTBase, C extends Collection<T>> C deserializeInto(Supplier<T> constructor, NBTTagList in, C collection) { for (int i = 0; i < in.tagCount(); i++) { T t = constructor.get(); t.deserializeNBT((U)in.get(i)); collection.add(t); } return collection; } public NBTTagList serializeInventory(IInventory in) { return serializeInventory(new InvWrapper(in)); } public void deserializeInventory(IInventory out, NBTTagList in) { deserializeInventory(new InvWrapper(out), in); } public NBTTagList serializeInventory(IItemHandler in) { NBTTagList out = new NBTTagList(); for (int i = 0; i < in.getSlots(); i++) { ItemStack is = in.getStackInSlot(i); if (is == null || is.isEmpty()) continue; NBTTagCompound stackTag = is.serializeNBT(); stackTag.setInteger("Slot", i); out.appendTag(stackTag); } return out; } public void deserializeInventory(IItemHandlerModifiable out, NBTTagList in) { for (int i = 0; i < out.getSlots(); i++) { out.setStackInSlot(i, ItemStack.EMPTY); } for (int i = 0; i < in.tagCount(); i++) { NBTTagCompound stackTag = in.getCompoundTagAt(i); ItemStack is = new ItemStack(stackTag); out.setStackInSlot(stackTag.getInteger("Slot"), is); } } }
package com.gregory.testing.run; import com.gregory.testing.application.Server; import com.gregory.testing.message.Message; import com.gregory.testing.strategy.TestingStrategy; import java.util.List; public class TestCase { private final Server server; private final List<Message> messages; private final TestingStrategy strategy; public TestCase(Server server, List<Message> messages, TestingStrategy strategy) { this.server = server; this.messages = messages; this.strategy = strategy; } public Server server() { return server; } public List<Message> messages() { return messages; } public TestingStrategy strategy() { return strategy; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-11-09"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-07-19"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package com.linuxtek.kona.app.util; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linuxtek.kona.app.entity.KEmailAddress; import com.linuxtek.kona.util.KClassUtil; import com.linuxtek.kona.util.KDateUtil; import com.linuxtek.kona.util.KStringUtil; public class KUtil { private static Logger logger = LoggerFactory.getLogger(KUtil.class); private static KUtil instance = null; public static KUtil getInstance() { if (instance == null) { instance = new KUtil(); } return instance; } public static String uuid() { String uuid = UUID.randomUUID().toString(); uuid = uuid.replaceAll("-", ""); return uuid; } public static String year() { Integer year = KDateUtil.getYear(new Date()); return year.toString(); } public static String toString(Object obj) { if (obj == null) { return "[null]"; } return KClassUtil.toString(obj); } public static <EMAIL_ADDRESS extends KEmailAddress> String formatFirstName(EMAIL_ADDRESS email) { if (email == null) return ""; if (email.getFirstName() != null) { return email.getFirstName(); } return ""; } public String createLink(String baseUrl, String url) { if (baseUrl == null) baseUrl = ""; if (url == null) url = "/"; if (baseUrl.endsWith("/")) { baseUrl = KStringUtil.chop(baseUrl); } if (!url.startsWith("/")) { url = "/" + url; } String link = baseUrl + url; logger.debug("LINK: " + link); return link; } public static String formatDate(Date date) { String f = "MM/dd/yyyy"; return formatDate(date, f); } public static String formatDate(Date date, String format) { return formatDate(date, format, null); } public static String formatDate(Date date, String format, String timeZone) { if (date == null) return ""; Locale locale = Locale.getDefault(); if (timeZone == null) { timeZone = "America/New_York"; } TimeZone tz = TimeZone.getTimeZone(timeZone); return KDateUtil.format(date, format, locale, tz); } public static String formatCurrency(BigDecimal bd) { //Locale locale = new Locale("en_US"); return formatCurrency(bd, Locale.US); } public static String formatCurrency(BigDecimal bd, Locale locale) { if (bd == null) return (null); double d = bd.doubleValue(); NumberFormat form = NumberFormat.getCurrencyInstance(locale); return (form.format(d)); } public static void sleep(Long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } } }
package com.lothrazar.invcrafting; import java.lang.reflect.Field; import com.lothrazar.invcrafting.inventory.ContainerPlayerCrafting; import com.lothrazar.invcrafting.inventory.GuiInventoryCrafting; import com.lothrazar.invcrafting.inventory.InventoryPlayerCrafting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.inventory.InventoryScreen; import net.minecraft.entity.player.PlayerEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; public class Events { @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onGuiOpen(GuiOpenEvent event) { if (event.getGui() == null) { return; } Screen gui = event.getGui(); if (gui.getClass() == InventoryScreen.class && gui instanceof GuiInventoryCrafting == false) { gui = new GuiInventoryCrafting(Minecraft.getInstance().player); event.setGui(gui); } } @SubscribeEvent public void onEntityJoinWorld(EntityJoinWorldEvent event) { if (event.getEntity() instanceof PlayerEntity) { PlayerEntity player = (PlayerEntity) event.getEntity(); if (player.inventory instanceof InventoryPlayerCrafting == false) { //set not final try { Field inventoryField = ObfuscationReflectionHelper.findField(PlayerEntity.class, "field_71071_by"); inventoryField.setAccessible(true); //basically saetting this InventoryPlayerCrafting invCrafting = new InventoryPlayerCrafting(player); for (int i = 0; i < invCrafting.armorInventory.size(); i++) { invCrafting.armorInventory.set(i, player.inventory.armorInventory.get(i)); } for (int i = 0; i < invCrafting.mainInventory.size(); i++) { invCrafting.mainInventory.set(i, player.inventory.mainInventory.get(i)); } for (int i = 0; i < invCrafting.offHandInventory.size(); i++) { invCrafting.offHandInventory.set(i, player.inventory.offHandInventory.get(i)); } invCrafting.currentItem = player.inventory.currentItem; inventoryField.set(player, invCrafting); } catch (Exception e) { ModInvCrafting.LOGGER.error("Events set inventory error", e); } //now for container try { Field m = ObfuscationReflectionHelper.findField(PlayerEntity.class, "field_71069_bz");// "inventory"); m.setAccessible(true); //basically saetting this m.set(player, new ContainerPlayerCrafting((InventoryPlayerCrafting) player.inventory, !player.world.isRemote, player)); } catch (Exception e) { ModInvCrafting.LOGGER.error("Events set container error", e); } // player.container = new ContainerPlayerCrafting((InventoryPlayerCrafting) player.inventory, !player.world.isRemote, player); player.openContainer = player.container; } } } }
package com.moandjiezana.toml; import static com.moandjiezana.toml.ValueWriters.WRITERS; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.text.DateFormat; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * <p>Converts Objects to TOML</p> * * <p>An input Object can comprise arbitrarily nested combinations of Java primitive types, * other {@link Object}s, {@link Map}s, {@link List}s, and Arrays. {@link Object}s and {@link Map}s * are output to TOML tables, and {@link List}s and Array to TOML arrays.</p> * * <p>Example usage:</p> * <pre><code> * class AClass { * int anInt = 1; * int[] anArray = { 2, 3 }; * } * * String tomlString = new TomlWriter().write(new AClass()); * </code></pre> */ public class TomlWriter { public static class Builder { private int keyIndentation; private int tableIndentation; private int arrayDelimiterPadding = 0; public TomlWriter.Builder indentValuesBy(int spaces) { this.keyIndentation = spaces; return this; } public TomlWriter.Builder indentTablesBy(int spaces) { this.tableIndentation = spaces; return this; } /** * @param spaces number of spaces to put between opening square bracket and first item and between closing square bracket and last item * @return this TomlWriter.Builder instance */ public TomlWriter.Builder padArrayDelimitersBy(int spaces) { this.arrayDelimiterPadding = spaces; return this; } public TomlWriter build() { return new TomlWriter(keyIndentation, tableIndentation, arrayDelimiterPadding); } } private final WriterIndentationPolicy indentationPolicy; private GregorianCalendar calendar = new GregorianCalendar(); private DateFormat customDateFormat = null; /** * Creates a TomlWriter instance. */ public TomlWriter() { this(0, 0, 0); } private TomlWriter(int keyIndentation, int tableIndentation, int arrayDelimiterPadding) { this.indentationPolicy = new WriterIndentationPolicy(keyIndentation, tableIndentation, arrayDelimiterPadding); } /** * Write an Object into TOML String. * * @param from the object to be written * @return a string containing the TOML representation of the given Object */ public String write(Object from) { try { StringWriter output = new StringWriter(); write(from, output); return output.toString(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Write an Object in TOML to a {@link OutputStream}. * * @param from the object to be written * @param target the OutputStream to which the TOML will be written. The stream is not closed after being written to. * @throws IOException if target.write() fails */ public void write(Object from, OutputStream target) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(target); write(from, writer); writer.flush(); } /** * Write an Object in TOML to a {@link File}. * * @param from the object to be written * @param target the File to which the TOML will be written * @throws IOException if any file operations fail */ public void write(Object from, File target) throws IOException { FileWriter writer = new FileWriter(target); try { write(from, writer); } finally { writer.close(); } } /** * Write an Object in TOML to a {@link Writer}. * * @param from the object to be written * @param target the Writer to which TOML will be written. The Writer is not closed. * @throws IOException if target.write() fails */ public void write(Object from, Writer target) throws IOException { WRITERS.write(from, this, target); } WriterIndentationPolicy getIndentationPolicy() { return indentationPolicy; } /** * Set the {@link TimeZone} used when formatting datetimes. * * If unset, datetimes will be rendered in the current time zone. * * @param timeZone custom TimeZone. * @return this TomlWriter instance */ public TomlWriter setTimeZone(TimeZone timeZone) { calendar = new GregorianCalendar(timeZone); return this; } /** * Get the {@link TimeZone} in use for this TomlWriter. * * @return the currently set TimeZone. */ public TimeZone getTimeZone() { return calendar.getTimeZone(); } /** * Override the default date format. * * If a time zone was set with {@link #setTimeZone(TimeZone)}, it will be applied before formatting * datetimes. * * @param customDateFormat a custom DateFormat * @return this TomlWriter instance */ public TomlWriter setDateFormat(DateFormat customDateFormat) { this.customDateFormat = customDateFormat; return this; } public DateFormat getDateFormat() { return customDateFormat; } GregorianCalendar getCalendar() { return calendar; } }
package com.plaid.client; import com.plaid.client.exception.PlaidMfaException; import com.plaid.client.http.HttpDelegate; import com.plaid.client.request.ConnectOptions; import com.plaid.client.request.Credentials; import com.plaid.client.request.GetOptions; import com.plaid.client.request.InfoOptions; import com.plaid.client.response.AccountsResponse; import com.plaid.client.response.InfoResponse; import com.plaid.client.response.MessageResponse; import com.plaid.client.response.MfaResponse; import com.plaid.client.response.TransactionsResponse; import com.plaid.client.response.PlaidUserResponse; public interface PlaidUserClient { void setAccessToken(String accesstoken); String getAccessToken(); PlaidUserResponse exchangeToken(String publicToken); TransactionsResponse addUser(Credentials credentials, String type, String email, ConnectOptions connectOptions) throws PlaidMfaException; TransactionsResponse mfaConnectStep(String mfa, String type) throws PlaidMfaException; AccountsResponse achAuth(Credentials credentials, String type, ConnectOptions connectOptions) throws PlaidMfaException; AccountsResponse updateAchAuth(Credentials credentials, String accessToken) throws PlaidMfaException; AccountsResponse mfaAuthStep(String mfa, String type) throws PlaidMfaException; AccountsResponse updateMfaAuthStep(String mfa, String type) throws PlaidMfaException; AccountsResponse mfaAuthDeviceSelectionByDeviceType(String deviceType, String type) throws PlaidMfaException; AccountsResponse mfaAuthDeviceSelectionByDeviceMask(String deviceMask, String type) throws PlaidMfaException; TransactionsResponse updateTransactions(); TransactionsResponse updateTransactions(GetOptions options); TransactionsResponse updateCredentials(Credentials credentials, String type); TransactionsResponse updateWebhook(String webhook); AccountsResponse updateAuth(); MessageResponse deleteUser(); AccountsResponse checkBalance(); InfoResponse info(Credentials credentials, String type, InfoOptions options); TransactionsResponse addProduct(String product, ConnectOptions options); HttpDelegate getHttpDelegate(); }
package com.skelril.aurora; import com.sk89q.commandbook.CommandBook; import com.sk89q.commandbook.GodComponent; import com.skelril.aurora.admin.AdminComponent; import com.skelril.aurora.admin.AdminState; import com.skelril.aurora.util.ChatUtil; import com.skelril.aurora.util.LocationUtil; import com.zachsthings.libcomponents.ComponentInformation; import com.zachsthings.libcomponents.Depend; import com.zachsthings.libcomponents.InjectComponent; import com.zachsthings.libcomponents.bukkit.BukkitComponent; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; @ComponentInformation(friendlyName = "AFK Checker", desc = "AFK Checking.") @Depend(components = {GodComponent.class, AdminState.class}) public class IdleComponent extends BukkitComponent implements Runnable, Listener { private final CommandBook inst = CommandBook.inst(); private final Server server = CommandBook.server(); @InjectComponent AdminComponent adminComponent; @InjectComponent GodComponent godComponent; private ConcurrentHashMap<Player, Long> afk = new ConcurrentHashMap<>(); @Override public void enable() { //noinspection AccessStaticViaInstance inst.registerEvents(this); server.getScheduler().runTaskTimer(inst, this, 20 * 60, 20 * 10); } @Override public void run() { for (final Map.Entry<Player, Long> entry : afk.entrySet()) { if (System.currentTimeMillis() - entry.getValue() >= TimeUnit.MINUTES.toMillis(3)) { if (System.currentTimeMillis() - entry.getValue() >= TimeUnit.MINUTES.toMillis(60)) { LocationUtil.toGround(entry.getKey()); adminComponent.deadmin(entry.getKey(), true); entry.getKey().setSleepingIgnored(false); server.getScheduler().runTaskLater(inst, new Runnable() { @Override public void run() { entry.getKey().kickPlayer("Inactivity - 60 Minutes"); } }, 1); } else if (!entry.getKey().isSleepingIgnored()) { String name = entry.getKey().getName(); entry.getKey().setPlayerListName(ChatColor.GRAY + name.substring(0, Math.min(14, name.length()))); entry.getKey().setSleepingIgnored(true); godComponent.enableGodMode(entry.getKey()); ChatUtil.sendNotice(entry.getKey(), "You are now marked as AFK."); } } else if (entry.getKey().isSleepingIgnored()) { entry.getKey().setPlayerListName(entry.getKey().getName()); entry.getKey().setSleepingIgnored(false); if (!adminComponent.isAdmin(entry.getKey())) godComponent.disableGodMode(entry.getKey()); ChatUtil.sendNotice(entry.getKey(), "You are no longer marked as AFK."); } } } @EventHandler public void onEntityTargetPlayer(EntityTargetEvent event) { if (event.getTarget() instanceof Player && afk.containsKey(event.getTarget())) { if (System.currentTimeMillis() - afk.get(event.getTarget()) >= TimeUnit.MINUTES.toMillis(3)) { event.setCancelled(true); } } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { afk.put(event.getPlayer(), System.currentTimeMillis()); } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent event) { update(event.getPlayer()); } @EventHandler public void onCommand(PlayerCommandPreprocessEvent event) { update(event.getPlayer()); } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { update(event.getPlayer()); } @EventHandler public void onPlayerFish(PlayerFishEvent event) { update(event.getPlayer()); } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { if (event.getPlayer() instanceof Player) update((Player) event.getPlayer()); } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getWhoClicked() instanceof Player) update((Player) event.getWhoClicked()); } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (event.getPlayer() instanceof Player) update((Player) event.getPlayer()); } @EventHandler public void onEntityDamageEntityEvent(EntityDamageByEntityEvent event) { if (event.getDamager() instanceof Player) update((Player) event.getDamager()); } @EventHandler public void onMoveChange(PlayerMoveEvent event) { if (event.getFrom().distance(event.getTo()) >= 2.11) update(event.getPlayer()); } @EventHandler public void onPlayerDisconnect(PlayerQuitEvent event) { if (afk.containsKey(event.getPlayer())) afk.remove(event.getPlayer()); } /** * This method is used to update a player's last active time * * @param player - The player to update */ public void update(Player player) { afk.put(player, System.currentTimeMillis()); if (godComponent.hasGodMode(player) && !adminComponent.isAdmin(player)) { godComponent.disableGodMode(player); } } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util; import java.util.List; import java.util.Random; import com.google.common.collect.Lists; import com.samskivert.util.RandomUtil; import com.samskivert.util.StringUtil; import com.samskivert.util.Tuple; public class WeightedList<T> { public static <K> WeightedList<K> newList () { return new WeightedList<K>(); } public static <K> WeightedList<K> newList (K... entry) { return new WeightedList<K>().addAll(entry); } public static <K> WeightedList<K> newList (Float weight, K entry) { return new WeightedList<K>().addAll(weight, entry); } public static <K> WeightedList<K> newList (Float weight, K... entry) { return new WeightedList<K>().addAll(weight, entry); } /** * Adds the given items with a weight of 1. */ public WeightedList<T> addAll (T... items) { return addAll(1f, items); } /** * Adds the given item with the given weight. */ public WeightedList<T> addAll (float weight, T item) { _items.add(new Tuple<Float, T>(weight, item)); _weights = null; return this; } /** * Adds all of the given items with the given weight. */ public WeightedList<T> addAll (float weight, T... items) { for (T item : items) { addAll(weight, item); } return this; } /** * Returns the weight for the first found instance of the given item, * or -1 if we don't know about it. */ public float getWeight (T item) { for (Tuple<Float, T> tup : _items) { if (tup.right.equals(item)) { return tup.left; } } return -1; } /** * Removes the record we have for this item at this weight. */ public boolean remove (float weight, T item) { _weights = null; return _items.remove(new Tuple<Float, T>(weight, item)); } public T pickRandom () { return pickRandom(RandomUtil.rand); } public T pickRandom (Random rand) { if (_weights == null) { _weights = new float[_items.size()]; for (int ii = 0; ii < _weights.length; ii++) { _weights[ii] = _items.get(ii).left; } } int idx = RandomUtil.getWeightedIndex(_weights, rand); return idx == -1 ? null : _items.get(idx).right; } public List<Tuple<Float, T>> getItems () { return _items; } public int size () { return _items.size(); } @Override public String toString () { return _items.toString(); } protected float[] _weights; protected List<Tuple<Float, T>> _items = Lists.newArrayList(); }
package com.vito16.shop.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ConvertUtil { public static String toDateStr(Object o) throws ParseException { return o == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format((Date) o); } public static String toYMDStr(Object o) throws ParseException { return o == null ? null : new SimpleDateFormat("yyyy-MM-dd") .format((Date) o); } }
package com.xiaoleilu.hutool.lang; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.Set; import com.xiaoleilu.hutool.exceptions.UtilException; import com.xiaoleilu.hutool.util.CollectionUtil; import com.xiaoleilu.hutool.util.DateUtil; import com.xiaoleilu.hutool.util.StrUtil; /** * * * @author xiaoleilu * */ public class Conver { private Conver() { } /** * * @param clazz * @param value * @return */ public static Object parse(Class<?> clazz, Object value) { try { return clazz.cast(value); } catch (ClassCastException e) { String valueStr = String.valueOf(value); Object result = parseBasic(clazz, valueStr); if(result != null) { return result; } if(Date.class.isAssignableFrom(clazz)) { return DateUtil.parse(valueStr); }else if(clazz == BigInteger.class){ return new BigInteger(valueStr); }else if(clazz == BigDecimal.class) { return new BigDecimal(valueStr); }else if(clazz == byte[].class) { return valueStr.getBytes(); } return value; } } /** * * @param clazz * @param valueStr * @return null */ public static Object parseBasic(Class<?> clazz, String valueStr) { if(null == clazz || null == valueStr) { return null; } if(clazz.isAssignableFrom(String.class)){ return valueStr; } BasicType basicType = null; try { basicType = BasicType.valueOf(clazz.getSimpleName().toUpperCase()); } catch (Exception e) { return null; } switch (basicType) { case BYTE: if(clazz == byte.class) { return Byte.parseByte(valueStr); } return Byte.valueOf(valueStr); case SHORT: if(clazz == short.class) { return Short.parseShort(valueStr); } return Short.valueOf(valueStr); case INT: return Integer.parseInt(valueStr); case INTEGER: return Integer.valueOf(valueStr); case LONG: if(clazz == long.class) { return new BigDecimal(valueStr).longValue(); } return Long.valueOf(valueStr); case DOUBLE: if(clazz == double.class) { return new BigDecimal(valueStr).doubleValue(); } case FLOAT: if(clazz == float.class) { return Float.parseFloat(valueStr); } return Float.valueOf(valueStr); case BOOLEAN: if(clazz == boolean.class) { return Boolean.parseBoolean(valueStr); } return Boolean.valueOf(valueStr); case CHAR: return valueStr.charAt(0); case CHARACTER: return Character.valueOf(valueStr.charAt(0)); default: return null; } } /** * <br> * null<br> * * * @param value * @param defaultValue * @return */ public static String toStr(Object value, String defaultValue) { if(null == value) { return defaultValue; } if(value instanceof String) { return (String)value; } return value.toString(); } /** * <br> * null<br> * * * @param value * @param defaultValue * @return */ public static Character toChar(Object value, Character defaultValue) { if(null == value) { return defaultValue; } if(value instanceof Character) { return (Character)value; } final String valueStr = toStr(value, null); return StrUtil.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0); } /** * int<br> * <br> * * * @param value * @param defaultValue * @return */ public static Integer toInt(Object value, Integer defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Integer) { return (Integer)value; } if(value instanceof Number){ return ((Number) value).intValue(); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return Integer.parseInt(valueStr.trim()); } catch (Exception e) { return defaultValue; } } /** * byte<br> * <br> * * * @param value * @param defaultValue * @return */ public static Byte toByte(Object value, Byte defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Byte) { return (Byte)value; } if(value instanceof Number){ return ((Number) value).byteValue(); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return Byte.parseByte(valueStr); } catch (Exception e) { return defaultValue; } } /** * Short<br> * <br> * * * @param value * @param defaultValue * @return */ public static Short toShort(Object value, Short defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Short) { return (Short)value; } if(value instanceof Number){ return ((Number) value).shortValue(); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return Short.parseShort(valueStr.trim()); } catch (Exception e) { return defaultValue; } } /** * Integer<br> * @param <T> * @param isIgnoreConvertError null * @param values * @return */ @SafeVarargs public static <T> Integer[] toIntArray(boolean isIgnoreConvertError, T... values) { if(CollectionUtil.isEmpty(values)) { return new Integer[]{}; } final Integer[] ints = new Integer[values.length]; for(int i = 0; i < values.length; i++) { final Integer v = toInt(values[i], null); if(null == v && isIgnoreConvertError == false) { throw new UtilException(StrUtil.format("Convert [{}] to Integer error!", values[i])); } ints[i] = v; } return ints; } /** * long<br> * <br> * * * @param value * @param defaultValue * @return */ public static Long toLong(Object value, Long defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Long) { return (Long)value; } if(value instanceof Number){ return ((Number) value).longValue(); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return new BigDecimal(valueStr.trim()).longValue(); } catch (Exception e) { return defaultValue; } } /** * Long<br> * @param <T> * @param isIgnoreConvertError null * @param values * @return */ @SafeVarargs public static <T> Long[] toLongArray(boolean isIgnoreConvertError, T... values) { if(CollectionUtil.isEmpty(values)) { return new Long[]{}; } final Long[] longs = new Long[values.length]; for(int i = 0; i < values.length; i++) { final Long v = toLong(values[i], null); if(null == v && isIgnoreConvertError == false) { throw new UtilException(StrUtil.format("Convert [{}] to Long error!", values[i])); } longs[i] = v; } return longs; } /** * double<br> * <br> * * * @param value * @param defaultValue * @return */ public static Double toDouble(Object value, Double defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Double) { return (Double)value; } if(value instanceof Number){ return ((Number) value).doubleValue(); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return new BigDecimal(valueStr.trim()).doubleValue(); } catch (Exception e) { return defaultValue; } } /** * Double<br> * @param <T> * @param isIgnoreConvertError null * @param values * @return */ @SafeVarargs public static <T> Double[] toDoubleArray(boolean isIgnoreConvertError, T... values) { if(CollectionUtil.isEmpty(values)) { return new Double[]{}; } final Double[] doubles = new Double[values.length]; for(int i = 0; i < values.length; i++) { final Double v = toDouble(values[i], null); if(null == v && isIgnoreConvertError == false) { throw new UtilException(StrUtil.format("Convert [{}] to Double error!", values[i])); } doubles[i] = v; } return doubles; } /** * Float<br> * <br> * * * @param value * @param defaultValue * @return */ public static Float toFloat(Object value, Float defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Float) { return (Float)value; } if(value instanceof Number){ return ((Number) value).floatValue(); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return Float.parseFloat(valueStr.trim()); } catch (Exception e) { return defaultValue; } } /** * Float<br> * @param <T> * @param isIgnoreConvertError null * @param values * @return */ @SafeVarargs public static <T> Float[] toFloatArray(boolean isIgnoreConvertError, T... values) { if(CollectionUtil.isEmpty(values)) { return new Float[]{}; } final Float[] floats = new Float[values.length]; for(int i = 0; i < values.length; i++) { final Float v = toFloat(values[i], null); if(null == v && isIgnoreConvertError == false) { throw new UtilException(StrUtil.format("Convert [{}] to Float error!", values[i])); } floats[i] = v; } return floats; } /** * boolean<br> * <br> * * * @param value * @param defaultValue * @return */ public static Boolean toBool(Object value, Boolean defaultValue) { if (value == null){ return defaultValue; } if(value instanceof Boolean) { return (Boolean)value; } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return Boolean.parseBoolean(valueStr.trim()); } catch (Exception e) { return defaultValue; } } /** * Boolean<br> * @param <T> * @param isIgnoreConvertError null * @param values * @return */ @SafeVarargs public static <T> Boolean[] toBooleanArray(boolean isIgnoreConvertError, T... values) { if(CollectionUtil.isEmpty(values)) { return new Boolean[]{}; } final Boolean[] bools = new Boolean[values.length]; for(int i = 0; i < values.length; i++) { final Boolean v = toBool(values[i], null); if(null == v && isIgnoreConvertError == false) { throw new UtilException(StrUtil.format("Convert [{}] to Boolean error!", values[i])); } bools[i] = v; } return bools; } /** * Enum<br> * <br> * @param clazz EnumClass * @param value * @param defaultValue * @return Enum */ public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) { if (value == null){ return defaultValue; } if (clazz.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") E myE = (E) value; return myE; } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return Enum.valueOf(clazz,valueStr); } catch (Exception e) { return defaultValue; } } /** * BigInteger<br> * <br> * * * @param value * @param defaultValue * @return */ public static BigInteger toBigInteger(Object value, BigInteger defaultValue) { if (value == null){ return defaultValue; } if(value instanceof BigInteger) { return (BigInteger)value; } if(value instanceof Long) { return BigInteger.valueOf((Long)value); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return new BigInteger(valueStr); } catch (Exception e) { return defaultValue; } } /** * BigDecimal<br> * <br> * * * @param value * @param defaultValue * @return */ public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) { if (value == null){ return defaultValue; } if(value instanceof BigDecimal) { return (BigDecimal)value; } if(value instanceof Long) { return new BigDecimal((Long)value); } if(value instanceof Double) { return new BigDecimal((Double)value); } if(value instanceof Integer) { return new BigDecimal((Integer)value); } final String valueStr = toStr(value, null); if (StrUtil.isBlank(valueStr)){ return defaultValue; } try { return new BigDecimal(valueStr); } catch (Exception e) { return defaultValue; } } /** * * * @param input String. * @return . */ public static String toSBC(String input) { return toSBC(input, null); } /** * * * @param input String * @param notConvertSet * @return . */ public static String toSBC(String input, Set<Character> notConvertSet) { char c[] = input.toCharArray(); for (int i = 0; i < c.length; i++) { if(null != notConvertSet && notConvertSet.contains(c[i])) { continue; } if (c[i] == ' ') { c[i] = '\u3000'; } else if (c[i] < '\177') { c[i] = (char) (c[i] + 65248); } } return new String(c); } /** * * * @param input String. * @return */ public static String toDBC(String input) { return toDBC(input, null); } /** * * @param text * @param notConvertSet * @return */ public static String toDBC(String text, Set<Character> notConvertSet) { char c[] = text.toCharArray(); for (int i = 0; i < c.length; i++) { if(null != notConvertSet && notConvertSet.contains(c[i])) { continue; } if (c[i] == '\u3000') { c[i] = ' '; } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { c[i] = (char) (c[i] - 65248); } } String returnString = new String(c); return returnString; } /** * byte16 * @param bytes byte * @return */ public static String toHex(byte[] bytes) { final StringBuilder des = new StringBuilder(); String tmp = null; for (int i = 0; i < bytes.length; i++) { tmp = (Integer.toHexString(bytes[i] & 0xFF)); if (tmp.length() == 1) { des.append("0"); } des.append(tmp); } return des.toString(); } /** * <br/> * * * @param str * @param sourceCharset * @param destCharset * @return */ public static String convertCharset(String str, String sourceCharset, String destCharset) { if(StrUtil.hasBlank(str, sourceCharset, destCharset)) { return str; } try { return new String(str.getBytes(sourceCharset), destCharset); } catch (UnsupportedEncodingException e) { return str; } } /** * * * @param n * @return */ public static String digitUppercase(double n) { String fraction[] = { "", "" }; String digit[] = { "", "", "", "", "", "", "", "", "", "" }; String unit[][] = { { "", "", "" }, { "", "", "", "" } }; String head = n < 0 ? "" : ""; n = Math.abs(n); String s = ""; for (int i = 0; i < fraction.length; i++) { s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(.)+", ""); } if (s.length() < 1) { s = ""; } int integerPart = (int) Math.floor(n); for (int i = 0; i < unit[0].length && integerPart > 0; i++) { String p = ""; for (int j = 0; j < unit[1].length && n > 0; j++) { p = digit[integerPart % 10] + unit[1][j] + p; integerPart = integerPart / 10; } s = p.replaceAll("(.)*$", "").replaceAll("^$", "") + unit[0][i] + s; } return head + s.replaceAll("(.)*", "").replaceFirst("(.)+", "").replaceAll("(.)+", "").replaceAll("^$", ""); } }
package com.yahoo.sketches.hllmap; import static com.yahoo.sketches.hllmap.MapTestingUtil.LS; import static com.yahoo.sketches.hllmap.MapTestingUtil.TAB; import static com.yahoo.sketches.hllmap.MapTestingUtil.bytesToInt; import static com.yahoo.sketches.hllmap.MapTestingUtil.intToBytes; import com.yahoo.sketches.SketchesArgumentException; import com.yahoo.sketches.hash.MurmurHash3; @SuppressWarnings("unused") class HllMap extends Map { private static final double LOAD_FACTOR = 15.0/16.0; private static final int SIX_BIT_MASK = 0X3F; // 6 bits private static final int TEN_BIT_MASK = 0X3FF; //10 bits private static final int EIGHT_BIT_MASK = 0XFF; private final int k_; private final int hllArrLongs_; private final float entrySizeBytes_; private int tableEntries_; //Full size of the table private int capacityEntries_; //max capacity entries defined by Load factor private int curCountEntries_; //current count of valid entries private float growthFactor_; //e.g., 1.2 to 2.0 //Arrays private byte[] keysArr_; //keys of zero are allowed private long[] arrOfHllArr_; private double[] invPow2SumHiArr_; private double[] invPow2SumLoArr_; private double[] hipEstAccumArr_; private byte[] validBitArr_; /** * Private constructor used to set all finals * @param keySizeBytes size of key in bytes * @param k size of HLL sketch */ private HllMap(final int keySizeBytes, int k) { super(keySizeBytes); k_ = k; hllArrLongs_ = k/10 + 1; entrySizeBytes_ = (float) (keySizeBytes + hllArrLongs_ * 8 + 3 * 8 + 0.125); } public static HllMap getInstance(int tgtEntries, int keySizeBytes, int k, float growthFactor) { if (!com.yahoo.sketches.Util.isPowerOf2(k) || (k > 1024) || (k < 16)) { throw new SketchesArgumentException("K must be power of 2 and (16 <= k <= 1024): " + k); } if (growthFactor <= 1.0) { throw new SketchesArgumentException("growthFactor must be > 1.0: " + growthFactor); } if (tgtEntries < 16) { throw new SketchesArgumentException("tgtEntries must be >= 16"); } HllMap map = new HllMap(keySizeBytes, k); int entries = (int)Math.ceil(tgtEntries / LOAD_FACTOR); int tableEntries = Util.nextPrime(entries); map.tableEntries_ = tableEntries; map.capacityEntries_ = (int)(tableEntries * LOAD_FACTOR); map.curCountEntries_ = 0; map.growthFactor_ = growthFactor; map.keysArr_ = new byte[tableEntries * map.keySizeBytes_]; map.arrOfHllArr_ = new long[tableEntries * map.hllArrLongs_]; map.invPow2SumHiArr_ = new double[tableEntries]; map.invPow2SumLoArr_ = new double[tableEntries]; map.hipEstAccumArr_ = new double[tableEntries]; map.validBitArr_ = new byte[tableEntries/8 + 1]; return map; } public float getEntrySizeBytes() { return entrySizeBytes_; } public int getCapacityEntries() { return capacityEntries_; } public int getTableEntries() { return tableEntries_; } public int getSizeOfArrays() { return keysArr_.length + arrOfHllArr_.length * 8 + tableEntries_ * 24 + validBitArr_.length; } @Override double getEstimate(byte[] key) { if (key == null) return Double.NaN; int index = outerSearchForKey(keysArr_, key, validBitArr_); if (index < 0) { return 0; } return hipEstAccumArr_[index]; } @Override double update(byte[] key, int coupon) { if (key == null) return Double.NaN; boolean updated = false; int outerIndex = outerSearchForKey(keysArr_, key, validBitArr_); if (outerIndex < 0) { //not found, initialize new row int emptyOuterIndex = ~outerIndex; System.arraycopy(key, 0, keysArr_, emptyOuterIndex * keySizeBytes_, keySizeBytes_); Util.setBitToOne(validBitArr_, emptyOuterIndex); invPow2SumHiArr_[emptyOuterIndex] = k_; invPow2SumLoArr_[emptyOuterIndex] = 0; hipEstAccumArr_[emptyOuterIndex] = 0; updated = updateHll(emptyOuterIndex, coupon); //update HLL array, updates HIP double est = hipEstAccumArr_[emptyOuterIndex]; curCountEntries_++; if (curCountEntries_ > capacityEntries_) { growSize(); } //print("; "+updated + " "); return est; } //matching key found updated = updateHll(outerIndex, coupon); //update HLL array //print("; "+updated + " "); return hipEstAccumArr_[outerIndex]; } void updateEstimate(byte[] key, double estimate) { int outerIndex = outerSearchForKey(keysArr_, key, validBitArr_); if (outerIndex < 0) { throw new SketchesArgumentException("Key not found. "); } hipEstAccumArr_[outerIndex] = estimate; } private final void growSize() { int newTableEntries = Util.nextPrime((int)(tableEntries_ * growthFactor_)); int newCapacityEntries = (int)(newTableEntries * LOAD_FACTOR); byte[] newKeys = new byte[newTableEntries * keySizeBytes_]; long[] newHllArr = new long[newTableEntries * hllArrLongs_]; double[] newInvPow2Sum1 = new double[newTableEntries]; double[] newInvPow2Sum2 = new double[newTableEntries]; double[] newHipEstAccum = new double[newTableEntries]; byte[] newValidBit = new byte[newTableEntries/8 + 1]; for (int oldIndex = 0; oldIndex < tableEntries_; oldIndex++) { if (Util.isBitZero(validBitArr_, oldIndex)) continue; byte[] key = new byte[keySizeBytes_]; System.arraycopy(keysArr_, oldIndex * keySizeBytes_, key, 0, keySizeBytes_); //get old key int newIndex = outerSearchForEmpty(key, newTableEntries, newValidBit); System.arraycopy(key, 0, keysArr_, newIndex * keySizeBytes_, keySizeBytes_); //put key //put the rest of the row System.arraycopy( arrOfHllArr_, oldIndex * hllArrLongs_, newHllArr, newIndex * hllArrLongs_, hllArrLongs_); newInvPow2Sum1[newIndex] = invPow2SumHiArr_[oldIndex]; newInvPow2Sum2[newIndex] = invPow2SumLoArr_[oldIndex]; newHipEstAccum[newIndex] = hipEstAccumArr_[oldIndex]; Util.setBitToOne(newValidBit, oldIndex); } //restore into sketch tableEntries_ = newTableEntries; capacityEntries_ = (int)(tableEntries_ * LOAD_FACTOR); //curCountEntries_, growthFactor_ unchanged keysArr_ = newKeys; arrOfHllArr_ = newHllArr; invPow2SumHiArr_ = newInvPow2Sum1; //init to k invPow2SumLoArr_ = newInvPow2Sum2; //init to 0 hipEstAccumArr_ = newHipEstAccum; //init to 0 validBitArr_ = newValidBit; } /** * Returns the outer address for the given key given the array of keys, if found. * Otherwise, returns address twos complement of first empty slot found; * @param keyArr the given array of keys * @param key the key to search for * @return the address of the given key, or -1 if not found */ private static final int outerSearchForKey(byte[] keyArr, byte[] key, byte[] validBit) { final int keyLen = key.length; final int tableEntries = keyArr.length/keyLen; final long[] hash = MurmurHash3.hash(key, 0L); int index = (int) ((hash[0] >>> 1) % tableEntries); if (Util.isBitZero(validBit, index)) { //check if slot is empty return ~index; } if (Util.equals(key, 0, keyArr, index * keyLen, keyLen)) { //check for key match return index; } //keep searching final int stride = (int) ((hash[1] >>> 1) % (tableEntries - 2L) + 1L); final int loopIndex = index; do { index -= stride; if (index < 0) { index += tableEntries; } if (Util.isBitZero(validBit, index)) { //check if slot is empty return ~index; } if (Util.equals(key, 0, keyArr, index * keyLen, keyLen)) { //check for key match return index; } } while (index != loopIndex); return ~index; } /** * Find an empty slot for the given key. Throws an exception if no empty slots. * @param key the given key * @param tableEntries prime size of table * @param validBit the valid bit array * @return an empty slot for the given key */ private static final int outerSearchForEmpty(byte[] key, int tableEntries, byte[] validBit) { final int keyLen = key.length; final long[] hash = MurmurHash3.hash(key, 0L); int index = (int) ((hash[0] >>> 1) % tableEntries); if (Util.isBitZero(validBit, index)) { //check if slot is empty return index; } //keep searching final int stride = (int) ((hash[1] >>> 1) % (tableEntries - 2L) + 1L); final int loopIndex = index; do { index -= stride; if (index < 0) { index += tableEntries; } if (Util.isBitZero(validBit, index)) { //check if slot is empty return index; } } while (index != loopIndex); throw new SketchesArgumentException("No empty slots."); } //These methods are specifically tied to the HLL array layout /** * Returns the long that contains the hll index. * This is a function of the HLL array storage layout. * @param hllIdx the given hll index * @return the long that contains the hll index */ private static final int hllLongIdx(int hllIdx) { return hllIdx/10; } /** * Returns the long shift for the hll index. * This is a function of the HLL array storage layout. * @param hllIdx the given hll index * @return the long shift for the hll index */ private static final int hllShift(int hllIdx) { return ((hllIdx % 10) * 6) & SIX_BIT_MASK; } private final boolean updateHll(int outerIndex, int coupon) { int hllIdx = coupon & TEN_BIT_MASK; //lower 10 bits int newValue = (coupon >>> 10) & SIX_BIT_MASK; //upper 6 bits int shift = hllShift(hllIdx); int longIdx = hllLongIdx(hllIdx); long hllLong = arrOfHllArr_[outerIndex + longIdx]; int oldValue = (int)(hllLong >>> shift) & SIX_BIT_MASK; //print("hllIdx: " +hllIdx + ", newV: " + newValue + ", oldV: " + oldValue); //print("; invPwr2Sum: "+(invPow2SumHiArr_[outerIndex] + invPow2SumLoArr_[outerIndex])); if (newValue <= oldValue) return false; // newValue > oldValue //update hipEstAccum BEFORE updating invPow2Sum double invPow2Sum = invPow2SumHiArr_[outerIndex] + invPow2SumLoArr_[outerIndex]; double oneOverQ = k_ / invPow2Sum; hipEstAccumArr_[outerIndex] += oneOverQ; //print("; invPwr2Sum: "+invPow2Sum); //TODO //update invPow2Sum if (oldValue < 32) { invPow2SumHiArr_[outerIndex] -= Util.invPow2(oldValue); } else { invPow2SumLoArr_[outerIndex] -= Util.invPow2(oldValue); } if (newValue < 32) { invPow2SumHiArr_[outerIndex] += Util.invPow2(newValue); } else { invPow2SumLoArr_[outerIndex] += Util.invPow2(newValue); } //insert the new value hllLong &= ~(0X3FL << shift); //zero out the 6-bit field hllLong |= ((long)newValue) << shift; //insert arrOfHllArr_[outerIndex + longIdx] = hllLong; return true; } static int getHllValue(long[] arrOfHllArr, int outerIndex, int hllIdx) { int shift = hllShift(hllIdx); int longIdx = hllLongIdx(hllIdx); long hllLong = arrOfHllArr[outerIndex + longIdx]; return (int)(hllLong >>> shift) & SIX_BIT_MASK; } void printEntry(byte[] key) { if (key.length != 4) throw new SketchesArgumentException("Key must be 4 bytes"); int keyInt = bytesToInt(key); StringBuilder sb = new StringBuilder(); int outerIndex = outerSearchForKey(keysArr_, key, validBitArr_); if (outerIndex < 0) throw new SketchesArgumentException("Not Found: " + keyInt); sb.append(keyInt).append(TAB); sb.append(Util.isBitOne(validBitArr_, outerIndex)? "1" : "0").append(TAB); sb.append(Double.toString(invPow2SumHiArr_[outerIndex])).append(TAB); sb.append(Double.toString(invPow2SumLoArr_[outerIndex])).append(TAB); sb.append(hipEstAccumArr_[outerIndex]).append(LS); sb.append(hllToString(arrOfHllArr_, outerIndex, k_)); Util.println(sb.toString()); } String hllToString(long[] arrOfhllArr, int outerIndex, int k) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k_-1; i++) { int v = getHllValue(arrOfHllArr_, outerIndex, i); sb.append(v).append(":"); } int v = getHllValue(arrOfHllArr_, outerIndex, k_ - 1); sb.append(v); return sb.toString(); } private static void test1() { int k = 512; int u = 100000; int initEntries = 16; int keySize = 4; float rf = (float)1.2; HllMap map = HllMap.getInstance(initEntries, keySize, k, rf); println("Entry bytes : " + map.getEntrySizeBytes()); println("Capacity : " + map.getCapacityEntries()); println("Table Entries : " + map.getTableEntries()); println("Est Arr Size : " + (map.getEntrySizeBytes() * map.getTableEntries())); println("Size of Arrays: "+ map.getSizeOfArrays()); byte[] key = new byte[4]; byte[] id = new byte[4]; double est; key = intToBytes(1, key); for (int i=1; i<= u; i++) { id = intToBytes(i, id); int coupon = Util.coupon16(id, k); est = map.update(key, coupon); if (i % 1000 == 0) { double err = (est/i -1.0) * 100; String eStr = String.format("%.3f%%", err); println("i: "+i + "\t Est: " + est + TAB + eStr); } } println("Table Entries : " + map.getTableEntries()); println("Cur Count : " + map.curCountEntries_); println("RSE : " + (1/Math.sqrt(k))); //map.printEntry(key); } public static void main(String[] args) { test1(); } static void println(String s) { System.out.println(s); } static void print(String s) { System.out.print(s); } }
package de.mxro.maven.tools; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.mxro.file.FileItem; import de.mxro.file.Jre.FilesJre; import de.mxro.javafileutils.Collect; import de.mxro.javafileutils.Collect.LeafCheck; import de.mxro.process.Spawn; public class MavenProject { private static List<File> orderDirectoriesByBuildOrder(final List<File> directories, final List<Dependency> buildOrder, final boolean addOthers) { final List<File> res = new ArrayList<File>(directories.size()); final List<File> unprocessed = new LinkedList<File>(directories); final Map<String, Dependency> map = new HashMap<String, Dependency>(); for (final Dependency d : buildOrder) { map.put(d.artifactId(), d); } for (final File f : directories) { final Dependency match = map.get(f.getName()); if (match == null) { continue; } unprocessed.remove(f); res.add(f); } // System.out.println(unprocessed.size()); if (addOthers) { res.addAll(unprocessed); } return res; } public static boolean isMavenProject(final File directory) { for (final File child : directory.listFiles()) { if (child.getName().equals("pom.xml")) { return true; } } return false; } public static List<File> orderDirectoriesByBuildOrder(final List<File> directories, final List<Dependency> buildOrder) { return orderDirectoriesByBuildOrder(directories, buildOrder, true); } public static List<File> getDependendProjectsInCorrectOrder(final List<File> directories, final List<Dependency> buildOrder) { return orderDirectoriesByBuildOrder(directories, buildOrder, false); } public static boolean buildSuccessful(final String mavenOutput) { if (mavenOutput.contains("BUILD FAILURE") || !mavenOutput.contains("BUILD SUCCESS")) { return false; } else { return true; } } public static List<Dependency> dependencyBuildOrder(final File project) { final List<Dependency> res = new ArrayList<Dependency>(100); final String dependencyOutput = Spawn.runBashCommand("mvn dependency:tree -o | tail -n 10000", project); final Pattern pattern = Pattern.compile("- ([^:]*):([^:]*):([^:]*):([^:]*):"); final Matcher matcher = pattern.matcher(dependencyOutput); while (matcher.find()) { if (matcher.groupCount() == 4) { final String groupId = matcher.group(1); final String artifactId = matcher.group(2); final String version = matcher.group(4); final Dependency d = new Dependency() { @Override public String groupId() { return groupId; } @Override public String artifactId() { return artifactId; } @Override public String version() { return version; } }; res.add(d); } } Collections.reverse(res); return res; } private static void replaceVersion(final File pomFile, final String newVersion) { try { final List<String> lines = new ArrayList<String>(); final BufferedReader in = new BufferedReader(new FileReader(pomFile)); String line = in.readLine(); boolean found = false; while (line != null) { if (!found && line.contains("<version>")) { lines.add(" <version>" + newVersion + "</version>"); found = true; } else { lines.add(line); } line = in.readLine(); } in.close(); final PrintWriter out = new PrintWriter(pomFile); for (final String l : lines) { out.println(l); } out.close(); } catch (final IOException ex) { throw new RuntimeException(ex); } } private static Dependency retrieveDependency(final File pomFile) { try { final byte[] pomBytes = Files.readAllBytes(FileSystems.getDefault().getPath(pomFile.getAbsolutePath())); final String pom = new String(pomBytes, "UTF-8"); final String groupId; final String artifactId; final String version; { final Pattern pattern = Pattern.compile("<groupId>([^<]*)</groupId>"); final Matcher matcher = pattern.matcher(pom); matcher.find(); groupId = matcher.group(1); } { final Pattern pattern = Pattern.compile("<artifactId>([^<]*)</artifactId>"); final Matcher matcher = pattern.matcher(pom); matcher.find(); artifactId = matcher.group(1); } { final Pattern pattern = Pattern.compile("<version>([^<]*)</version>"); final Matcher matcher = pattern.matcher(pom); matcher.find(); version = matcher.group(1); } return new Dependency() { @Override public String version() { return version; } @Override public String groupId() { return groupId; } @Override public String artifactId() { return artifactId; } }; } catch (final IOException ex) { throw new RuntimeException(ex); } } public static String getVersion(final File projectDir) { for (final File file : projectDir.listFiles()) { if (file.getName().equals("pom.xml")) { return retrieveDependency(file).version(); } } throw new RuntimeException("No pom.xml found in project dir " + projectDir); } public static Dependency getMavenDependency(final File projectDir) { for (final File file : projectDir.listFiles()) { if (file.getName().equals("pom.xml")) { return retrieveDependency(file); } } throw new RuntimeException("No pom.xml found in project dir " + projectDir); } public static void setVersion(final File projectDir, final String version) { for (final File file : projectDir.listFiles()) { if (file.getName().equals("pom.xml")) { replaceVersion(file, version); return; } } throw new RuntimeException("No pom.xml found in project dir " + projectDir); } public static List<File> getProjects(final File rootDir) { return Collect.getLeafDirectoriesRecursively(rootDir, new LeafCheck() { @Override public boolean isLeaf(final File f) { if (!f.isDirectory()) { return false; } return f.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { return pathname.getName().equals("pom.xml"); } }).length > 0; } }); } public static void replaceDependency(final File projectDir, final Dependency oldDependency, final Dependency newDependency) { final FileItem pom = FilesJre.wrap(projectDir).get("pom.xml"); if (!pom.exists()) { throw new IllegalArgumentException("Specified directory does not contain a pom.xml file: " + projectDir); } } }
package de.prob2.ui.groovy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.scene.control.ContextMenu; import javafx.scene.control.TextArea; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; public class GroovyConsole extends TextArea { private int charCounterInLine = 0; private int currentPosInLine = 0; private final KeyCode[] rest = {KeyCode.ESCAPE,KeyCode.SCROLL_LOCK,KeyCode.PAUSE,KeyCode.NUM_LOCK,KeyCode.INSERT,KeyCode.CONTEXT_MENU,KeyCode.CAPS}; private List<String> instructions; private int posInList = -1; private int numberOfInstructions = 0; private String currentLine =""; private GroovyInterpreter interpreter; public GroovyConsole() { super(); this.setContextMenu(new ContextMenu()); this.instructions = new ArrayList<String>(); this.appendText("Prob 2.0 Groovy Console \n >"); setListeners(); } public void setInterpreter(GroovyInterpreter interpreter) { this.interpreter = interpreter; } @Override public void paste() { if(this.getLength() - this.getCaretPosition() > charCounterInLine) { goToLastPos(); } int oldlength = this.getText().length(); int posOfEnter = this.getText().lastIndexOf("\n"); super.paste(); int diff = this.getText().length() - oldlength; currentLine = this.getText().substring(posOfEnter + 3, this.getText().length()); charCounterInLine += diff; currentPosInLine += diff; correctPosInLine(); } @Override public void copy() { super.copy(); correctPosInLine(); goToLastPos(); } @Override public void cut() { super.cut(); correctPosInLine(); } private void correctPosInLine() { if(charCounterInLine > 0) { charCounterInLine currentPosInLine } } @Override public void selectForward() { //do nothing, but stay at correct position if(currentPosInLine != charCounterInLine) { currentPosInLine } } @Override public void selectBackward() { //do nothing, but stay at correct position if(currentPosInLine != 0) { currentPosInLine++; } } /*@Override public void selectPositionCaret(int pos) { super.selectPositionCaret(pos); this.setScrollTop(Double.MAX_VALUE); }*/ //Enter (One Instruction -> more than 1 Line) //Arrow Keys: Left and Right private void setListeners() { this.addEventFilter(KeyEvent.ANY, e-> { if(e.getCode() == KeyCode.Z && (e.isShortcutDown() || e.isAltDown())) { e.consume(); return; } }); this.addEventFilter(MouseEvent.ANY, e-> { if(e.getButton() == MouseButton.PRIMARY) { if(this.getLength() - this.getCaretPosition() < charCounterInLine) { currentPosInLine = charCounterInLine - (this.getLength() - this.getCaretPosition()); } } }); this.setOnKeyPressed(e-> { if(e.getCode().isArrowKey()) { handleArrowKeys(e); this.setScrollTop(Double.MAX_VALUE); return; } if(e.getCode().isNavigationKey()) { e.consume(); return; } if(e.getCode().equals(KeyCode.BACK_SPACE) || e.getCode().equals(KeyCode.DELETE)) { handleDeletion(e); return; } if(e.getCode().equals(KeyCode.ENTER)) { handleEnter(e); return; } if(!e.getCode().isFunctionKey() && !e.getCode().isMediaKey() && !e.getCode().isModifierKey()) { handleInsertChar(e); return; } if(handleRest(e)) { return; } }); } private void goToLastPos() { this.positionCaret(this.getLength()); currentPosInLine = charCounterInLine; } private void handleInsertChar(KeyEvent e) { if(e.getText().equals("") || (!(e.isShortcutDown() || e.isAltDown()) && (this.getLength() - this.getCaretPosition()) > charCounterInLine)) { goToLastPos(); if(e.getText().equals("")) { e.consume(); return; } } if((e.isShortcutDown() || e.isAltDown())) { e.consume(); return; } currentLine = new StringBuilder(currentLine).insert(currentPosInLine, e.getText()).toString(); charCounterInLine++; currentPosInLine++; posInList = instructions.size() - 1; } private void handleEnter(KeyEvent e) { charCounterInLine = 0; currentPosInLine = 0; e.consume(); if(instructions.size() == 0) { instructions.add(currentLine); numberOfInstructions++; } else { //add Instruction if last Instruction is not "", otherwise replace it String lastinstruction = instructions.get(instructions.size()-1); if(!(lastinstruction.equals(""))) { instructions.add(currentLine); numberOfInstructions++; } else if(!currentLine.equals("")) { instructions.set(instructions.size() - 1, currentLine); } } posInList = instructions.size() - 1; currentLine = ""; this.appendText("\n" + interpreter.exec(instructions.get(posInList))); this.appendText("\n >"); } private void handleArrowKeys(KeyEvent e) { if(e.getCode().equals(KeyCode.LEFT)) { handleLeft(e); } else if(e.getCode().equals(KeyCode.UP) || e.getCode().equals(KeyCode.DOWN)) { boolean needReturn; if(e.getCode().equals(KeyCode.UP)) { needReturn = handleUp(e); } else { needReturn = handleDown(e); } if(needReturn) { return; } setTextAfterArrowKey(); } else if(e.getCode().equals(KeyCode.RIGHT)) { handleRight(e); } } private boolean handleUp(KeyEvent e) { e.consume(); if(posInList == -1) { return true; } if(posInList == instructions.size() - 1) { String lastinstruction = instructions.get(instructions.size()-1); if(!lastinstruction.equals("")) { if(!lastinstruction.equals(currentLine)) { if(posInList == instructions.size() - 1) { instructions.add(currentLine); setTextAfterArrowKey(); return true; } else { instructions.set(numberOfInstructions, currentLine); } } } else { instructions.set(instructions.size() - 1, currentLine); } } posInList = Math.max(posInList - 1, 0); return false; } private boolean handleDown(KeyEvent e) { e.consume(); if(posInList == instructions.size() - 1) { return true; } posInList = Math.min(posInList+1, instructions.size() - 1); return false; } private void handleLeft(KeyEvent e) { //handleLeft if(currentPosInLine > 0 && this.getLength() - this.getCaretPosition() <= charCounterInLine) { currentPosInLine = Math.max(currentPosInLine - 1, 0); } else { e.consume(); } } private void handleRight(KeyEvent e) { //handleRight if(currentPosInLine < charCounterInLine && this.getLength() - this.getCaretPosition() <= charCounterInLine) { currentPosInLine++; } else { e.consume(); } } private void setTextAfterArrowKey() { int posOfEnter = this.getText().lastIndexOf("\n"); this.setText(this.getText().substring(0, posOfEnter + 3)); currentLine = instructions.get(posInList); charCounterInLine = currentLine.length(); currentPosInLine = charCounterInLine; this.appendText(currentLine); } private boolean handleRest(KeyEvent e) { if(Arrays.asList(rest).contains(e.getCode())) { e.consume(); return true; } return false; } private void handleDeletion(KeyEvent e) { boolean needReturn = false; if(!this.getSelectedText().equals("") || this.getLength() - this.getCaretPosition() > charCounterInLine || (e.isShortcutDown() || e.isAltDown())) { e.consume(); return; } if(e.getCode().equals(KeyCode.BACK_SPACE)) { needReturn = handleBackspace(e); if(needReturn) { return; } } else { needReturn = handleDelete(e); if(needReturn) { return; } } updateTextAreaAfterDeletion(); } private boolean handleBackspace(KeyEvent e) { if(currentPosInLine > 0) { currentPosInLine = Math.max(currentPosInLine - 1, 0); charCounterInLine = Math.max(charCounterInLine - 1, 0); } else { e.consume(); return true; } return false; } private boolean handleDelete(KeyEvent e) { if(currentPosInLine < charCounterInLine) { charCounterInLine = Math.max(charCounterInLine - 1, 0); } else if(currentPosInLine == charCounterInLine) { return true; } return false; } private void updateTextAreaAfterDeletion() { int posOfEnter = this.getText().lastIndexOf("\n"); currentLine = this.getText().substring(posOfEnter + 3, posOfEnter + 3 + currentPosInLine); currentLine += this.getText().substring(posOfEnter+ 4 + currentPosInLine, this.getText().length()); } }
package edu.jhu.gm.inf; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import edu.jhu.gm.model.DenseFactor; import edu.jhu.gm.model.ExplicitFactor; import edu.jhu.gm.model.Factor; import edu.jhu.gm.model.FactorGraph; import edu.jhu.gm.model.FactorGraph.FgEdge; import edu.jhu.gm.model.FactorGraph.FgNode; import edu.jhu.gm.model.GlobalFactor; import edu.jhu.gm.model.Var; import edu.jhu.gm.model.VarSet; import edu.jhu.prim.util.math.FastMath; import edu.jhu.util.Timer; /** * Loopy belief propagation inference algorithm. * * @author mgormley * */ public class BeliefPropagation implements FgInferencer { private static final Logger log = Logger.getLogger(BeliefPropagation.class); public interface FgInferencerFactory { FgInferencer getInferencer(FactorGraph fg); boolean isLogDomain(); } public static class BeliefPropagationPrm implements FgInferencerFactory { public BpScheduleType schedule = BpScheduleType.TREE_LIKE; public int maxIterations = 100; public double timeoutSeconds = Double.POSITIVE_INFINITY; public BpUpdateOrder updateOrder = BpUpdateOrder.PARALLEL; //public final FactorGraph fg; public boolean logDomain = true; /** Whether to normalize the messages after sending. */ public boolean normalizeMessages = true; public boolean cacheFactorBeliefs = false; public BeliefPropagationPrm() { } public FgInferencer getInferencer(FactorGraph fg) { return new BeliefPropagation(fg, this); } public boolean isLogDomain() { return logDomain; } } public enum BpScheduleType { /** Send messages from a root to the leaves and back. */ TREE_LIKE, /** Send messages in a random order. */ RANDOM } public enum BpUpdateOrder { /** Send each message in sequence according to the schedule. */ SEQUENTIAL, /** Create all messages first. Then send them all at the same time. */ PARALLEL }; /** * A container class for messages and properties of an edge in a factor * graph. * * @author mgormley * */ public static class Messages { /** The current message. */ public DenseFactor message; /** The pending messge. */ public DenseFactor newMessage; /** Constructs a message container, initializing the messages to the uniform distribution. */ public Messages(FgEdge edge, boolean logDomain, boolean normalizeMessages) { // Initialize messages to the (possibly unnormalized) uniform // distribution in case we want to run parallel BP. double initialValue = logDomain ? 0.0 : 1.0; // Every message to/from a variable will be a factor whose domain is // that variable only. Var var = edge.getVar(); message = new DenseFactor(new VarSet(var), initialValue); newMessage = new DenseFactor(new VarSet(var), initialValue); if (normalizeMessages) { // Normalize the initial messages. if (logDomain) { message.logNormalize(); newMessage.logNormalize(); } else { message.normalize(); newMessage.normalize(); } } } } private final BeliefPropagationPrm prm; private final FactorGraph fg; /** A container of messages each edge in the factor graph. Indexed by edge id. */ private final Messages[] msgs; private BpSchedule sched; private List<FgEdge> order; private DenseFactor[] factorBeliefCache; public BeliefPropagation(FactorGraph fg, BeliefPropagationPrm prm) { this.prm = prm; this.fg = fg; this.msgs = new Messages[fg.getNumEdges()]; this.factorBeliefCache = new DenseFactor[fg.getNumFactors()]; if (prm.updateOrder == BpUpdateOrder.SEQUENTIAL) { // Cache the order if this is a sequential update. if (prm.schedule == BpScheduleType.TREE_LIKE) { sched = new BfsBpSchedule(fg); } else if (prm.schedule == BpScheduleType.RANDOM) { sched = new RandomBpSchedule(fg); } else { throw new RuntimeException("Unknown schedule type: " + prm.schedule); } order = sched.getOrder(); } } /** * For debugging. Remove later. */ public Messages[] getMessages() { return msgs; } /** @inheritDoc */ @Override public void run() { Timer timer = new Timer(); timer.start(); // Initialization. for (int i=0; i<msgs.length; i++) { // TODO: consider alternate initializations. msgs[i] = new Messages(fg.getEdge(i), prm.logDomain, prm.normalizeMessages); } // Reset the global factors. for (Factor factor : fg.getFactors()) { if (factor instanceof GlobalFactor) { ((GlobalFactor)factor).reset(); } } if (prm.cacheFactorBeliefs) { // Initialize factor beliefs for(FgNode node : fg.getNodes()) { if(node.isFactor() && !(node.getFactor() instanceof GlobalFactor)) { Factor f = node.getFactor(); DenseFactor fBel = new DenseFactor(f.getVars()); int c = f.getVars().calcNumConfigs(); for(int i=0; i<c; i++) fBel.setValue(i, f.getUnormalizedScore(i)); for(FgEdge v2f : node.getInEdges()) { DenseFactor vBel = msgs[v2f.getId()].message; if(prm.logDomain) fBel.add(vBel); else fBel.prod(vBel); } factorBeliefCache[f.getId()] = fBel; } } } // Message passing. for (int iter=0; iter < prm.maxIterations; iter++) { if (timer.totSec() > prm.timeoutSeconds) { break; } if (prm.updateOrder == BpUpdateOrder.SEQUENTIAL) { for (FgEdge edge : order) { createMessage(edge, iter); sendMessage(edge); } } else if (prm.updateOrder == BpUpdateOrder.PARALLEL) { for (FgEdge edge : fg.getEdges()) { createMessage(edge, iter); } for (FgEdge edge : fg.getEdges()) { sendMessage(edge); } } else { throw new RuntimeException("Unsupported update order: " + prm.updateOrder); } } timer.stop(); } public void clear() { Arrays.fill(msgs, null); } /** * Creates a message and stores it in the "pending message" slot for this edge. * @param edge The directed edge for which the message should be created. * @param iter The iteration number. */ protected void createMessage(FgEdge edge, int iter) { int edgeId = edge.getId(); Var var = edge.getVar(); Factor factor = edge.getFactor(); if (!edge.isVarToFactor() && factor instanceof GlobalFactor) { log.trace("Creating messages for global factor."); // Since this is a global factor, we pass the incoming messages to it, // and efficiently marginalize over the variables. The current setup is // create all the messages from this factor to its variables, but only // once per iteration. GlobalFactor globalFac = (GlobalFactor) factor; globalFac.createMessages(edge.getParent(), msgs, prm.logDomain, prm.normalizeMessages, iter); // The messages have been set, so just return. return; } else { // Since this is not a global factor, we send messages in the normal way, which // in the case of a factor to variable message requires enumerating all possible // variable configurations. DenseFactor msg = msgs[edgeId].newMessage; // Initialize the message to all ones (zeros in log-domain) since we are "multiplying". msg.set(prm.logDomain ? 0.0 : 1.0); if (edge.isVarToFactor()) { // Message from variable v* to factor f*. // Compute the product of all messages received by v* except for the // one from f*. getProductOfMessages(edge.getParent(), msg, edge.getChild()); } else { // Message from factor f* to variable v*. // Compute the product of all messages received by f* (each // of which will have a different domain) with the factor f* itself. // Exclude the message going out to the variable, v*. DenseFactor prod; if(prm.cacheFactorBeliefs && !(factor instanceof GlobalFactor)) { // we are computing f->v, which is the product of a bunch of factor values and v->f messages // we can cache this product and remove the v->f message that would have been excluded from the product DenseFactor remove = msgs[edge.getOpposing().getId()].message; DenseFactor from = factorBeliefCache[factor.getId()]; prod = new DenseFactor(from); if(prm.logDomain) prod.subBP(remove); else prod.divBP(remove); assert !prod.containsBadValues(prm.logDomain) : "prod from cached beliefs = " + prod; } else { // fall back on normal way of computing messages without caching prod = new DenseFactor(factor.getVars()); // Set the initial values of the product to those of the sending factor. int numConfigs = prod.getVars().calcNumConfigs(); for (int c = 0; c < numConfigs; c++) { prod.setValue(c, factor.getUnormalizedScore(c)); } getProductOfMessages(edge.getParent(), prod, edge.getChild()); } // Marginalize over all the assignments to variables for f*, except // for v*. if (prm.logDomain) { msg = prod.getLogMarginal(new VarSet(var), false); } else { msg = prod.getMarginal(new VarSet(var), false); } } assert (msg.getVars().equals(new VarSet(var))); if (prm.normalizeMessages) { if (prm.logDomain) { msg.logNormalize(); } else { msg.normalize(); } } // normalize and logNormalize already check for NaN else assert !msg.containsBadValues(prm.logDomain) : "msg = " + msg; // Set the final message in case we created a new object. msgs[edgeId].newMessage = msg; } } /** * Computes the product of all messages being sent to a node, optionally * excluding messages sent from another node. * * Upon completion, prod will contain the product of all incoming messages * to node, except for the message from exclNode if specified, times the * factor given in prod. * * @param node * The node to which all the messages are being sent. * @param prod * An input factor with which the product will (destructively) be * taken. * @param exclNode * If null, the product of all messages will be taken. If * non-null, any message sent from exclNode to node will be * excluded from the product. */ protected void getProductOfMessages(FgNode node, DenseFactor prod, FgNode exclNode) { for (FgEdge nbEdge : node.getInEdges()) { if (nbEdge.getParent() == exclNode) { // Don't include the receiving variable. continue; } // Get message from neighbor to factor. DenseFactor nbMsg = msgs[nbEdge.getId()].message; // The neighbor messages have a different domain, but addition // should still be well defined. if (prm.logDomain) { prod.add(nbMsg); } else { prod.prod(nbMsg); } assert !prod.containsBadValues(prm.logDomain) : "prod = " + prod; } } /** Gets the product of messages (as in getProductOfMessages()) and then normalizes. */ protected void getProductOfMessagesNormalized(FgNode node, DenseFactor prod, FgNode exclNode) { getProductOfMessages(node, prod, exclNode); if (prm.logDomain) { prod.logNormalize(); } else { prod.normalize(); } } /** * Sends the message that is currently "pending" for this edge. This just * copies the message in the "pending slot" to the "message slot" for this * edge. * * @param edge The edge over which the message should be sent. */ protected void sendMessage(FgEdge edge) { int edgeId = edge.getId(); Messages ec = msgs[edgeId]; // Just swap the pointers to the current message and the new message, so // that we don't have to create a new factor object. DenseFactor oldMessage = ec.message; ec.message = ec.newMessage; ec.newMessage = oldMessage; assert !ec.message.containsBadValues(prm.logDomain) : "ec.message = " + ec.message; // update factor beliefs if(prm.cacheFactorBeliefs && edge.isVarToFactor() && !(edge.getFactor() instanceof GlobalFactor)) { Factor f = edge.getFactor(); DenseFactor update = factorBeliefCache[f.getId()]; if(prm.isLogDomain()) { update.subBP(oldMessage); update.add(ec.message); } else { update.divBP(oldMessage); update.prod(ec.message); } } if (log.isTraceEnabled()) { log.trace("Message sent: " + ec.message); } } /** @inheritDoc */ @Override public DenseFactor getMarginals(VarSet varSet) { // We could implement this method, but it will be slow since we'll have // to find a factor that contains all of these variables. // For now we just throw an exception. throw new RuntimeException("not implemented"); } protected DenseFactor getMarginals(Var var, FgNode node) { DenseFactor prod = new DenseFactor(new VarSet(var), prm.logDomain ? 0.0 : 1.0); // Compute the product of all messages sent to this variable. getProductOfMessagesNormalized(node, prod, null); return prod; } protected DenseFactor getMarginals(Factor factor, FgNode node) { if (factor instanceof GlobalFactor) { log.warn("Getting marginals of a global factor is not supported." + " This will require exponential space to store the resulting factor." + " This should only be used for testing."); } DenseFactor prod = new DenseFactor(BruteForceInferencer.safeGetDenseFactor(factor)); // Compute the product of all messages sent to this factor. getProductOfMessagesNormalized(node, prod, null); return prod; } /** @inheritDoc * Note this method is slow compared to querying by id, and requires an extra hashmap lookup. */ @Override public DenseFactor getMarginals(Var var) { FgNode node = fg.getNode(var); return getMarginals(var, node); } /** @inheritDoc * Note this method is slow compared to querying by id, and requires an extra hashmap lookup. */ @Override public DenseFactor getMarginals(Factor factor) { FgNode node = fg.getNode(factor); return getMarginals(factor, node); } /** @inheritDoc */ @Override public DenseFactor getMarginalsForVarId(int varId) { FgNode node = fg.getVarNode(varId); return getMarginals(node.getVar(), node); } /** @inheritDoc */ @Override public DenseFactor getMarginalsForFactorId(int factorId) { FgNode node = fg.getFactorNode(factorId); return getMarginals(node.getFactor(), node); } /** @inheritDoc */ @Override public double getPartition() { if (prm.schedule == BpScheduleType.TREE_LIKE && prm.normalizeMessages == false) { // Special case which only works on non-loopy graphs with the two pass schedule and // no renormalization of messages. // The factor graph's overall partition function is the product of the // partition functions for each connected component. double partition = prm.logDomain ? 0.0 : 1.0; for (FgNode node : fg.getConnectedComponents()) { if (!node.isVar()) { if (node.getOutEdges().size() == 0) { // This is an empty factor that makes no contribution to the partition function. continue; } else { // Get a variable node in this connected component. node = node.getOutEdges().get(0).getChild(); assert(node.isVar()); } } double nodePartition = getPartitionFunctionAtVarNode(node); if (prm.logDomain) { partition += nodePartition; } else { partition *= nodePartition; } } assert !Double.isNaN(partition); return partition; } if (!prm.logDomain) { return Math.exp(-getBetheFreeEnergy()); } else { return - getBetheFreeEnergy(); } } /** * Computes the Bethe free energy of the factor graph. For acyclic graphs, * this is equal to -log(Z) where Z is the exact partition function. For * loopy graphs it can be used as an approximation. */ protected double getBetheFreeEnergy() { // G_{Bethe} = \sum_a \sum_{x_a} - b(x_a) ln \chi(x_a) // + \sum_a \sum_{x_a} b(x_a) ln b(x_a) // + \sum_i (n_i - 1) \sum_{x_i} b(x_i) ln b(x_i) // = \sum_a \sum_{x_a} b(x_a) ln (b(x_a) / \chi(x_a)) // + \sum_i (n_i - 1) \sum_{x_i} b(x_i) ln b(x_i) // where n_i is the number of neighbors of the variable x_i, // b(x_a) and b(x_i) are normalized distributions and x_a is // the set of variables participating in factor a. double semiringZero = prm.logDomain ? Double.NEGATIVE_INFINITY : 0.0; double bethe = 0.0; Set<Class<?>> ignoredClasses = new HashSet<Class<?>>(); for (int a=0; a<fg.getFactors().size(); a++) { Factor f = fg.getFactors().get(a); if (f instanceof ExplicitFactor) { int numConfigs = f.getVars().calcNumConfigs(); DenseFactor beliefs = getMarginalsForFactorId(a); for (int c=0; c<numConfigs; c++) { double chi_c = ((ExplicitFactor) f).getValue(c); // Since we want multiplication by 0 to always give 0 (not the case for Double.POSITIVE_INFINITY or Double.NaN. if (beliefs.getValue(c) != semiringZero) { if (prm.logDomain) { bethe += FastMath.exp(beliefs.getValue(c)) * (beliefs.getValue(c) - chi_c); } else { bethe += beliefs.getValue(c) * FastMath.log(beliefs.getValue(c) / chi_c); } } } } else { bethe += ((GlobalFactor) f).getExpectedLogBelief(fg.getFactorNode(a), msgs, prm.logDomain); } } for (int i=0; i<fg.getVars().size(); i++) { Var v = fg.getVars().get(i); int numNeighbors = fg.getVarNode(i).getOutEdges().size(); DenseFactor beliefs = getMarginalsForVarId(i); double sum = 0.0; for (int c=0; c<v.getNumStates(); c++) { if (beliefs.getValue(c) != semiringZero) { if (prm.logDomain) { sum += FastMath.exp(beliefs.getValue(c)) * beliefs.getValue(c); } else { sum += beliefs.getValue(c) * FastMath.log(beliefs.getValue(c)); } } } bethe -= (numNeighbors - 1) * sum; } for (Class<?> clazz : ignoredClasses) { log.warn("Bethe free energy value is INVALID. Returning NaN instead. Ignoring factor for Bethe free energy computation: " + clazz); return Double.NaN; } assert !Double.isNaN(bethe); return bethe; } /** * FOR TESTING ONLY. * Gets the partition function for the connected component containing the given node. */ // TODO: This should be package private or protected. It is exposed for testing only. public double getPartitionFunctionAtVarNode(FgNode node) { // We just return the normalizing constant for the marginals of any variable. if (!node.isVar()) { throw new IllegalArgumentException("Node must be a variable node."); } Var var = node.getVar(); DenseFactor prod = new DenseFactor(new VarSet(var), prm.logDomain ? 0.0 : 1.0); // Compute the product of all messages sent to this node. getProductOfMessages(node, prod, null); if (prm.logDomain) { return prod.getLogSum(); } else { return prod.getSum(); } } @Override public boolean isLogDomain() { return prm.logDomain; } }
package hu.progtech.setcardgame.bl; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleStringProperty; /** * Score class represents a score and player pair with additional data about the player's points. */ public class Score { /** * The name of the player. */ private SimpleStringProperty name; /** * The number of Sets the player found in the current round. */ private int numberOfSetsFound; /** * The number of Hints the player used in the current round. */ private int numberOfHintsUsed; /** * The time it took the player to earn this score. */ private long timeUsed; /** * The actual score of the player. */ private SimpleDoubleProperty score; /** * Initialises a newly created Score object. */ public Score() { this.name = new SimpleStringProperty(); this.score = new SimpleDoubleProperty(); } /** * Constructs a new Score by setting the name and score of the player. * @param name The name of the player * @param score The score of the player */ public Score(String name, double score) { this.name = new SimpleStringProperty(name); this.score = new SimpleDoubleProperty(score); } /** * Constructs a new Score by setting the name of the player and the data to calculate the actual score. * @param name The name of the player * @param numberOfSetsFound The number of Sets the player found in the current round * @param numberOfHintsUsed The number of hints the player used in the current round * @param timeUsed The time it took the player to earn this score */ public Score(String name, int numberOfSetsFound, int numberOfHintsUsed, int timeUsed) { this.name = new SimpleStringProperty(name); this.numberOfSetsFound = numberOfSetsFound; this.numberOfHintsUsed = numberOfHintsUsed; this.timeUsed = timeUsed; } /** * Calculates the actual score based on the number of Sets the player found and the number of hints the player used and the time it took the player to earn this score. */ public void calculateScore() { score = new SimpleDoubleProperty(numberOfSetsFound*1000.0-numberOfHintsUsed*900.0-timeUsed/1000); } /** * Returns the number of Sets the player found in the current round. * @return The number of Sets the player found in the current round */ public int getNumberOfSetsFound() { return numberOfSetsFound; } /** * Sets the number of Sets the player found in the current round. * @param numberOfSetsFound The number of Sets the player found in the current round */ public void setNumberOfSetsFound(int numberOfSetsFound) { this.numberOfSetsFound = numberOfSetsFound; } /** * Returns the number of hints the player used in the current round. * @return The number of hints the player used in the current round */ public int getNumberOfHintsUsed() { return numberOfHintsUsed; } /** * Sets the number of hints the player used in the current round. * @param numberOfHintsUsed The number of hints the player used in the current round */ public void setNumberOfHintsUsed(int numberOfHintsUsed) { this.numberOfHintsUsed = numberOfHintsUsed; } /** * Returns the time it took the player to earn this score. * @return The time it took the player to earn this score */ public long getTimeUsed() { return timeUsed; } /** * Sets the time it took the player to earn this score. * @param timeUsed The time it took the player to earn this score */ public void setTimeUsed(long timeUsed) { this.timeUsed = timeUsed; } /** * Returns the name of the player. * @return The name of the player */ public String getName() { return name.get(); } /** * Sets the name of the player. * @param name The name of the player */ public void setName(String name) { this.name.set(name); } /** * Returns the actual points the player got in the current round. * @return The points the player got in the current round */ public double getScore() { return score.get(); } /** * Sets the score of the player. * @param score The points the player got in the current round */ public void setScore(double score) { this.score.set(score); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Score score1 = (Score) o; if (Double.compare(score1.getScore(), getScore()) != 0) return false; return getName() != null ? getName().equals(score1.getName()) : score1.getName() == null; } @Override public int hashCode() { int result; long temp; result = getName() != null ? getName().hashCode() : 0; temp = Double.doubleToLongBits(getScore()); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { return name + ":" + score; } }
package imagej.patcher; import java.awt.GraphicsEnvironment; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Map; import java.util.jar.Attributes.Name; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Encapsulates an ImageJ 1.x "instance". * <p> * This class is a partner to the {@link LegacyClassLoader}, intended to make * sure that the ImageJ 1.x contained in a given class loader is patched and can * be accessed conveniently. * </p> * * @author "Johannes Schindelin" */ public class LegacyEnvironment { final private boolean headless; final private LegacyInjector injector; private Throwable initializationStackTrace; private ClassLoader loader; private Method setOptions, run, runMacro, runPlugIn, main; private Field _hooks; /** * Constructs a new legacy environment. * * @param loader the {@link ClassLoader} to use for loading the (patched) * ImageJ 1.x classes; if {@code null}, a {@link LegacyClassLoader} * is constructed. * @param headless whether to patch in support for headless operation * (compatible only with "well-behaved" plugins, i.e. plugins that do * not use graphical components directly) * @throws ClassNotFoundException */ public LegacyEnvironment(final ClassLoader loader, final boolean headless) throws ClassNotFoundException { this(loader, headless, new LegacyInjector()); } LegacyEnvironment(final ClassLoader loader, final boolean headless, final LegacyInjector injector) throws ClassNotFoundException { this.headless = headless; this.loader = loader; this.injector = injector; } private boolean isInitialized() { return _hooks != null; } private synchronized void initialize() { if (isInitialized()) return; initializationStackTrace = new Throwable("Initialized here:"); if (loader != null) { injector.injectHooks(loader, headless); } try { this.loader = loader != null ? loader : new LegacyClassLoader(headless, injector); final Class<?> ij = this.loader.loadClass("ij.IJ"); final Class<?> imagej = this.loader.loadClass("ij.ImageJ"); final Class<?> macro = this.loader.loadClass("ij.Macro"); _hooks = ij.getField("_hooks"); setOptions = macro.getMethod("setOptions", String.class); run = ij.getMethod("run", String.class, String.class); runMacro = ij.getMethod("runMacro", String.class, String.class); runPlugIn = ij.getMethod("runPlugIn", String.class, String.class); main = imagej.getMethod("main", String[].class); } catch (final Exception e) { throw new RuntimeException("Found incompatible ij.IJ class", e); } // TODO: if we want to allow calling IJ#run(ImagePlus, String, String), we // will need a data translator } private void ensureUninitialized() { if (isInitialized()) { final StringWriter string = new StringWriter(); final PrintWriter writer = new PrintWriter(string); initializationStackTrace.printStackTrace(writer); writer.close(); throw new RuntimeException( "LegacyEnvironment was already initialized:\n\n" + string.toString().replaceAll("(?m)^", "\t")); } } public void disableIJ1PluginDirs() { ensureUninitialized(); injector.disableIJ1PluginDirsHandling(); } /** * Adds the class path of a given {@link ClassLoader} to the plugin class * loader. * <p> * This method is intended to be used in unit tests as well as interactive * debugging from inside an Integrated Development Environment where the * plugin's classes are not available inside a {@code .jar} file. * </p> * <p> * At the moment, the only supported parameters are {@link URLClassLoader}s. * </p> * * @param fromClassLoader the class path donor */ public void addPluginClasspath(final ClassLoader fromClassLoader) { if (fromClassLoader == null) return; initialize(); for (ClassLoader loader = fromClassLoader; loader != null; loader = loader.getParent()) { if (loader == this.loader || loader == this.loader.getParent()) { break; } if (!(loader instanceof URLClassLoader)) { if (loader != fromClassLoader) continue; throw new IllegalArgumentException( "Cannot add class path from ClassLoader of type " + fromClassLoader.getClass().getName()); } for (final URL url : ((URLClassLoader) loader).getURLs()) { if (!"file".equals(url.getProtocol())) { throw new RuntimeException("Not a file URL! " + url); } addPluginClasspath(new File(url.getPath())); final String path = url.getPath(); if (path.matches(".*/target/surefire/surefirebooter[0-9]*\\.jar")) try { final JarFile jar = new JarFile(path); final Manifest manifest = jar.getManifest(); if (manifest != null) { final String classPath = manifest.getMainAttributes().getValue(Name.CLASS_PATH); if (classPath != null) { for (final String element : classPath.split(" +")) try { final URL url2 = new URL(element); if (!"file".equals(url2.getProtocol())) continue; addPluginClasspath(new File(url2.getPath())); } catch (final MalformedURLException e) { e.printStackTrace(); } } } } catch (final IOException e) { System.err .println("Warning: could not add plugin class path due to "); e.printStackTrace(); } } } } /** * Adds extra elements to the class path of ImageJ 1.x' plugin class loader. * <p> * The typical use case for a {@link LegacyEnvironment} is to run specific * plugins in an encapsulated environment. However, in the case of multiple * one wants to use multiple legacy environments with separate sets of plugins * enabled, it becomes impractical to pass the location of the plugins' * {@code .jar} files via the {@code plugins.dir} system property (because of * threading issues). * </p> * <p> * In other cases, the plugins' {@code .jar} files are not located in a single * directory, or worse: they might be contained in a directory among * {@code .jar} files one might <i>not</i> want to add to the plugin class * loader's class path. * </p> * <p> * This method addresses that need by allowing to add individual {@code .jar} * files to the class path of the plugin class loader and ensuring that their * {@code plugins.config} files are parsed. * </p> * * @param classpathEntries the class path entries containing ImageJ 1.x * plugins */ public void addPluginClasspath(final File... classpathEntries) { initialize(); try { final LegacyHooks hooks = (LegacyHooks) loader.loadClass("ij.IJ").getField("_hooks").get(null); for (final File file : classpathEntries) { hooks._pluginClasspath.add(file); } } catch (final Exception e) { throw new RuntimeException(e); } } /** * Sets the macro options. * <p> * Both {@link #run(String, String)} and {@link #runMacro(String, String)} * take an argument that is typically recorded by the macro recorder. For * {@link #runPlugIn(String, String)}, however, only the {@code arg} parameter * that is to be passed to the plugins {@code run()} or {@code setup()} method * can be specified. For those use cases where one wants to call a plugin * class directly, but still provide macro options, this method is the * solution. * </p> * * @param options the macro options to use for the next call to * {@link #runPlugIn(String, String)} */ public void setMacroOptions(final String options) { try { setOptions.invoke(null, options); } catch (final Exception e) { throw new RuntimeException(e); } } /** * Runs {@code IJ.run(command, options)} in the legacy environment. * * @param command the command to run * @param options the options to pass to the command */ public void run(final String command, final String options) { initialize(); final Thread thread = Thread.currentThread(); final ClassLoader savedLoader = thread.getContextClassLoader(); thread.setContextClassLoader(loader); try { run.invoke(null, command, options); } catch (final Exception e) { throw new RuntimeException(e); } finally { thread.setContextClassLoader(savedLoader); } } /** * Runs {@code IJ.runMacro(macro, arg)} in the legacy environment. * * @param macro the macro code to run * @param arg an optional argument (which can be retrieved in the macro code * via {@code getArgument()}) */ public void runMacro(final String macro, final String arg) { initialize(); final Thread thread = Thread.currentThread(); final String savedName = thread.getName(); thread.setName("Run$_" + savedName); final ClassLoader savedLoader = thread.getContextClassLoader(); thread.setContextClassLoader(loader); try { runMacro.invoke(null, macro, arg); } catch (final Exception e) { throw new RuntimeException(e); } finally { thread.setName(savedName); thread.setContextClassLoader(savedLoader); } } /** * Runs {@code IJ.runPlugIn(className, arg)} in the legacy environment. * * @param className the plugin class to run * @param arg an optional argument (which get passed to the {@code run()} or * {@code setup()} method of the plugin) */ public Object runPlugIn(final String className, final String arg) { initialize(); final Thread thread = Thread.currentThread(); final String savedName = thread.getName(); thread.setName("Run$_" + savedName); final ClassLoader savedLoader = thread.getContextClassLoader(); thread.setContextClassLoader(loader); try { return runPlugIn.invoke(null, className, arg); } catch (final Exception e) { throw new RuntimeException(e); } finally { thread.setName(savedName); thread.setContextClassLoader(savedLoader); } } /** * Runs {@code ImageJ.main(args)} in the legacy environment. * * @param args the arguments to pass to the main() method */ public void main(final String... args) { initialize(); Thread.currentThread().setContextClassLoader(loader); try { main.invoke(null, (Object) args); } catch (final Exception e) { throw new RuntimeException(e); } } /** * Gets the class loader containing the ImageJ 1.x classes used in this legacy * environment. * * @return the class loader */ public ClassLoader getClassLoader() { initialize(); return loader; } /** * Gets the ImageJ 1.x menu structure as a map */ public Map<String, String> getMenuStructure() { initialize(); try { final LegacyHooks hooks = (LegacyHooks) _hooks.get(null); return hooks.getMenuStructure(); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException(e); } } /** * Launches a fully-patched, self-contained ImageJ 1.x. * * @throws ClassNotFoundException */ public static LegacyEnvironment getPatchedImageJ1() throws ClassNotFoundException { final boolean headless = GraphicsEnvironment.isHeadless(); return new LegacyEnvironment(new LegacyClassLoader(headless), headless); } }
package jme3_ext_spatial_explorer; import java.io.File; import java.lang.reflect.Field; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import org.controlsfx.control.PropertySheet; import org.controlsfx.control.action.Action; import org.controlsfx.glyphfont.FontAwesome; import org.controlsfx.glyphfont.GlyphFont; import org.controlsfx.glyphfont.GlyphFontRegistry; import com.jme3.app.SimpleApplication; import com.jme3.app.StatsAppState; import com.jme3.asset.AssetManager; import com.jme3.bounding.BoundingBox; import com.jme3.export.binary.BinaryExporter; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.ColorRGBA; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.SceneGraphVisitorAdapter; import com.jme3.scene.Spatial; import com.jme3.scene.control.AbstractControl; import com.jme3.scene.debug.Arrow; import com.jme3.scene.debug.Grid; import com.jme3.scene.debug.WireBox; import com.jme3.scene.debug.WireFrustum; import com.jme3.shadow.ShadowUtil; import com.sun.javafx.application.PlatformImpl; import com.sun.javafx.css.StyleManager; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.scene.control.TreeItem; import javafx.stage.FileChooser; // TODO add helper to displayDebug and displayFrustum of AbstractShadowRenderer (a SceneProcessor) // TODO add helper to list SceneProcessor and display Properties public class Helper { private static AtomicBoolean initialized = new AtomicBoolean(false); private static String FontAwesome4 = "FontAwesome"; public static void dump(Node node, String prefix) { List<Spatial> children = node.getChildren(); System.out.printf("%s %s (%d)\n", prefix, node.getName(), children.size()); prefix = (prefix.length() == 0)? " +--": ("\t"+ prefix); for (Spatial sp : children) { if (sp instanceof Node) dump((Node) sp, prefix); else System.out.printf("%s %s [%s]\n", prefix, sp.getName(), sp.getClass().getName()); } } public static void initJfx() { //new JFXPanel(); // Note that calling PlatformImpl.startup more than once is OK //if (!initialized.get()) { PlatformImpl.startup(() -> { Helper.initJfxStyle(); }); } @SuppressWarnings({"rawtypes", "unchecked"}) public static void initJfxStyle() { //use reflection because sun.util.logging.PlatformLogger.Level is not always available if (initialized.getAndSet(true)){ // already initialized return; } try { //com.sun.javafx.Logging.getCSSLogger().setLevel(sun.util.logging.PlatformLogger.Level.SEVERE); Class<Enum> e = (Class<Enum>)Class.forName("sun.util.logging.PlatformLogger$Level"); Object o = Class.forName("com.sun.javafx.Logging").getMethod("getCSSLogger").invoke(null); o.getClass().getMethod("setLevel", e).invoke(o, Enum.valueOf(e, "SEVERE")); } catch(ClassNotFoundException exc) { // ignore } catch(Exception exc) { exc.printStackTrace(); } GlyphFont f = new FontAwesome(Helper.class.getResourceAsStream("/Interface/Fonts/fontawesome-webfont-4.4.0.ttf")); GlyphFontRegistry.register(f); // StyleManager.getInstance().addUserAgentStylesheet(Thread.currentThread().getContextClassLoader().getResource( "com/sun/javafx/scene/control/skin/modena/modena.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(GlyphFont.class.getResource("glyphfont.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(CommandLinksDialog.class.getResource("commandlink.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(Dialogs.class.getResource("dialogs.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(Wizard.class.getResource("wizard.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(CustomTextField.class.getResource("customtextfield.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(CustomTextField.class.getResource("autocompletion.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(SpreadsheetView.class.getResource("spreadsheet.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("breadcrumbbar.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("gridview.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("info-overlay.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("listselectionview.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("masterdetailpane.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("notificationpane.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("notificationpopup.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("plusminusslider.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("popover.bss").toExternalForm()); StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("propertysheet.css").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("rangeslider.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("rating.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("segmentedbutton.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("snapshot-view.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("statusbar.bss").toExternalForm()); // StyleManager.getInstance().addUserAgentStylesheet(PropertySheet.class.getResource("taskprogressview.bss").toExternalForm()); } public static Node makeScene(SimpleApplication app) { Node scene = new Node("_referential"); AssetManager assetManager = app.getAssetManager(); scene.attachChild(makeGrid(Vector3f.ZERO, 10, ColorRGBA.Blue, assetManager)); scene.attachChild(makeCoordinateAxes(Vector3f.ZERO, assetManager)); return scene; } public static Spatial makeGrid(Vector3f pos, int size, ColorRGBA color, AssetManager assetManager){ Geometry g = makeShape("_grid", new Grid(size, size, 1.0f), color, assetManager, true); g.center().move(pos); return g; } public static Spatial makeCoordinateAxes(Vector3f pos, AssetManager assetManager){ Node b = new Node("_axis"); b.setLocalTranslation(pos); Geometry arrow = makeShape("x", new Arrow(Vector3f.UNIT_X), ColorRGBA.Red, assetManager, true); arrow.getMaterial().getAdditionalRenderState().setLineWidth(4); // make arrow thicker b.attachChild(arrow); arrow = makeShape("y", new Arrow(Vector3f.UNIT_Y), ColorRGBA.Green, assetManager, true); arrow.getMaterial().getAdditionalRenderState().setLineWidth(4); // make arrow thicker b.attachChild(arrow); arrow = makeShape("z", new Arrow(Vector3f.UNIT_Z), ColorRGBA.Blue, assetManager, true); arrow.getMaterial().getAdditionalRenderState().setLineWidth(4); // make arrow thicker b.attachChild(arrow); return b; } public static Geometry makeShape(String name, Mesh shape, ColorRGBA color, AssetManager assetManager, boolean wireframe){ Geometry g = new Geometry(name, shape); Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat.getAdditionalRenderState().setWireframe(wireframe); mat.setColor("Color", color); g.setMaterial(mat); return g; } public static Action makeAction(String tooltip, FontAwesome.Glyph g, Consumer<ActionEvent> eventHandler) { initJfx(); Action action = new Action("", eventHandler); GlyphFont fontAwesome = GlyphFontRegistry.font(FontAwesome4); action.setGraphic(fontAwesome.create(g).size(14)); action.setLongText(tooltip); return action; } @SuppressWarnings("unchecked") public static void registerAction_Refresh(SpatialExplorer se) { se.treeItemActions.add(new Action("Refresh", (evt) -> { TreeItem<Spatial> treeItem = (TreeItem<Spatial>)evt.getSource(); se.update(treeItem.getValue(), treeItem); })); } @SuppressWarnings("unchecked") public static void registerAction_ShowLocalAxis(SpatialExplorer se, SimpleApplication app) { //Spatial axis = app.getRootNode().getChild("axis"); Spatial axis = makeCoordinateAxes(Vector3f.ZERO, app.getAssetManager()); axis.setQueueBucket(Bucket.Translucent); for(Spatial s : ((Node)axis).getChildren()) { ((Geometry)s).getMaterial().getAdditionalRenderState().setDepthTest(false); } axis.setName("localAxis"); AbstractControl axisSync = new AbstractControl() { @Override protected void controlUpdate(float tpf) { if (axis.getParent() == null) { app.getRootNode().attachChild(axis); } if (axis != getSpatial() && axis != getSpatial().getParent()) { axis.setLocalTransform(getSpatial().getWorldTransform()); } } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } }; se.treeItemActions.add(new Action("Show Local Axis", (evt) -> { app.enqueue(()->{ Spatial target = ((TreeItem<Spatial>)evt.getSource()).getValue(); if (target != axisSync.getSpatial()) { if (axisSync.getSpatial() != null) { axisSync.getSpatial().removeControl(axisSync); } target.addControl(axisSync); } return null; }); })); } @SuppressWarnings("unchecked") public static void registerAction_SaveAsJ3O(SpatialExplorer se, SimpleApplication app) { FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("jMonkeyEngine Object (*.j3o)", "*.j3o") ); se.treeItemActions.add(new Action("Save as .j3o", (evt) -> { System.out.println("target : " + evt.getTarget()); File f0 = fileChooser.showSaveDialog( null // ((MenuItem)evt.getTarget()).getGraphic().getScene().getWindow() // ((MenuItem)evt.getTarget()).getParentPopup() ); if (f0 != null) { File f = (f0.getName().endsWith(".j3o"))? f0 : new File(f0.getParentFile(), f0.getName() + ".j3o"); app.enqueue(()->{ Spatial target = ((TreeItem<Spatial>)evt.getSource()).getValue(); new BinaryExporter().save(target, f); return null; }); } })); } @SuppressWarnings("unchecked") public static void registerAction_ShowWireframe(SpatialExplorer se, SimpleApplication app) { se.treeItemActions.add(new Action("Show Wireframe", (evt) -> { Spatial target = ((TreeItem<Spatial>)evt.getSource()).getValue(); app.enqueue(() -> { target.breadthFirstTraversal(new SceneGraphVisitorAdapter(){ public void visit(Geometry geom) { RenderState r = geom.getMaterial().getAdditionalRenderState(); boolean wireframe = false; try { Field f = r.getClass().getDeclaredField("wireframe"); f.setAccessible(true); wireframe = (Boolean) f.get(r); } catch(Exception exc) { exc.printStackTrace(); } r.setWireframe(!wireframe); } }); return null; }); })); } @SuppressWarnings("unchecked") public static void registerAction_ShowBound(SpatialExplorer se, SimpleApplication app) { Material matModel = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); matModel.setColor("Color", ColorRGBA.Orange); Material matWorld = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); matWorld.setColor("Color", ColorRGBA.Red); se.treeItemActions.add(new Action("Show Bounds", (evt) -> { Spatial target = ((TreeItem<Spatial>)evt.getSource()).getValue(); app.enqueue(() -> { target.breadthFirstTraversal(new SceneGraphVisitorAdapter(){ public void visit(Geometry geom) { ShowBoundsControl ctrl = geom.getControl(ShowBoundsControl.class); if (ctrl != null) { geom.removeControl(ctrl); } else { geom.addControl(new ShowBoundsControl(matModel, matWorld)); } } }); return null; }); })); } @SuppressWarnings("unchecked") public static void registerAction_Remove(SpatialExplorer se, SimpleApplication app) { se.treeItemActions.add(new Action("Remove", (evt) -> { TreeItem<Spatial> treeItem = ((TreeItem<Spatial>)evt.getSource()); Spatial target = treeItem.getValue(); app.enqueue(() -> { if (target.getParent() != null) { target.removeFromParent(); Platform.runLater(() ->{ se.update(treeItem.getParent().getValue(), treeItem.getParent()); }); } return null; }); })); } public static void registerBarAction_SceneInWireframe(SpatialExplorer se, SimpleApplication app) { WireProcessor p = new WireProcessor(app.getAssetManager()); se.barActions.add(makeAction("Scene In Wireframe", FontAwesome.Glyph.DIAMOND, (evt) -> { app.enqueue(() -> { if (app.getViewPort().getProcessors().contains(p)) { app.getViewPort().removeProcessor(p); } else { app.getViewPort().addProcessor(p); } return null; }); })); } public static void registerBarAction_ShowStats(SpatialExplorer se, SimpleApplication app) { se.barActions.add(makeAction("Show Stats", FontAwesome.Glyph.ALIGN_LEFT, (evt) -> { app.enqueue(() -> { StatsAppState s = app.getStateManager().getState(StatsAppState.class); if (s == null) { s = new StatsAppState(); app.getStateManager().attach(s); s.setDisplayStatView(true); s.setDisplayFps(false); } else { boolean v = true; try { Field f = s.getClass().getDeclaredField("showStats"); f.setAccessible(true); v = (Boolean) f.get(s); } catch(Exception exc) { exc.printStackTrace(); } s.setDisplayStatView(!v); } return null; }); })); } public static void registerBarAction_ShowFps(SpatialExplorer se, SimpleApplication app) { se.barActions.add(makeAction("Show FPS", FontAwesome.Glyph.DASHBOARD, (evt) -> { app.enqueue(() -> { StatsAppState s = app.getStateManager().getState(StatsAppState.class); if (s == null) { s = new StatsAppState(); app.getStateManager().attach(s); s.setDisplayStatView(false); s.setDisplayFps(true); } else { boolean v = true; try { Field f = s.getClass().getDeclaredField("showFps"); f.setAccessible(true); v = (Boolean) f.get(s); } catch(Exception exc) { exc.printStackTrace(); } s.setDisplayFps(!v); } return null; }); })); } public static void registerBarAction_ShowFrustums(SpatialExplorer se, SimpleApplication app) { se.barActions.add(makeAction("Show Frustums", FontAwesome.Glyph.VIDEO_CAMERA, (evt) -> { app.enqueue(() -> { Node grp = (Node) app.getRootNode().getChild("_frustums"); if (grp != null) { grp.removeFromParent(); } else { grp = new Node("_frustums"); app.getRootNode().attachChild(grp); Set<Camera> cameras = new HashSet<>(); for(ViewPort vp : app.getRenderManager().getMainViews()) { Camera cam = vp.getCamera(); if (!cameras.contains(cam)) { grp.attachChild(createFrustum(cam, app.getAssetManager())); cameras.add(cam); } } } return null; }); })); } public static Geometry createFrustum(Camera cam, AssetManager assetManager){ Vector3f[] pts = new Vector3f[8]; for(int i = 0; i < pts.length; i++) pts[i] = new Vector3f(); ShadowUtil.updateFrustumPoints2(cam, pts); WireFrustum frustum = new WireFrustum(pts); Geometry frustumMdl = new Geometry("_frustum."+cam.getName(), frustum); frustumMdl.setCullHint(Spatial.CullHint.Never); frustumMdl.setShadowMode(ShadowMode.Off); frustumMdl.setMaterial(new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md")); frustumMdl.getMaterial().setColor("Color", ColorRGBA.Brown); frustumMdl.addControl(new AbstractControl() { @Override protected void controlUpdate(float tpf) { ShadowUtil.updateFrustumPoints2(cam, pts); frustum.update(pts); } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } }); return frustumMdl; } public static void setupSpatialExplorerWithAll(SimpleApplication app) { app.enqueue(() -> { AppStateSpatialExplorer ase = new AppStateSpatialExplorer(); SpatialExplorer se = ase.spatialExplorer; Helper.registerAction_Refresh(se); Helper.registerAction_ShowLocalAxis(se, app); Helper.registerAction_ShowWireframe(se, app); Helper.registerAction_ShowBound(se, app); Helper.registerAction_SaveAsJ3O(se, app); Helper.registerAction_Remove(se, app); Helper.registerBarAction_ShowFps(se, app); Helper.registerBarAction_ShowStats(se, app); Helper.registerBarAction_SceneInWireframe(se, app); Helper.registerBarAction_ShowFrustums(se, app); Actions4Animation.registerAllActions(se, app); Actions4Bullet.registerAllActions(se, app); app.getStateManager().attach(ase); return null; }); } public static class ShowBoundsControl extends AbstractControl { final WireBox mwbx = new WireBox(); final Geometry mgeo = new Geometry("", mwbx); final Transform mt = new Transform(); final WireBox wwbx = new WireBox(); final Geometry wgeo = new Geometry("", mwbx); final Transform wt = new Transform(); ShowBoundsControl(Material matModel, Material matWorld) { mgeo.setMaterial(matModel); mgeo.setCullHint(Spatial.CullHint.Never); mgeo.setShadowMode(ShadowMode.Off); wgeo.setMaterial(matWorld); wgeo.setCullHint(Spatial.CullHint.Never); wgeo.setShadowMode(ShadowMode.Off); } @Override public void setSpatial(Spatial s) { super.setSpatial(s); if (s != null) { Node root = s.getParent(); for(;root.getParent() != null; root = root.getParent()); mgeo.setName("_bounds.model." + s.getName()); root.attachChild(mgeo); wgeo.setName("_bounds.world." + s.getName()); root.attachChild(wgeo); } else { wgeo.removeFromParent(); mgeo.removeFromParent(); } } @Override protected void controlUpdate(float tpf) { Geometry geom = (Geometry) getSpatial(); if (geom != null) { // world BoundingBox wbb = (BoundingBox) geom.getWorldBound(); //TODO use WireBox.makeGeometry ? //wwbx.fromBoundingBox(wbb); wwbx.updatePositions(wbb.getXExtent(), wbb.getYExtent(), wbb.getZExtent()); wt.loadIdentity(); wt.setTranslation(wbb.getCenter()); wgeo.setLocalTransform(wt); // model BoundingBox mbb = (BoundingBox) geom.getModelBound(); //TODO use WireBox.makeGeometry ? mwbx.updatePositions(mbb.getXExtent(), mbb.getYExtent(), mbb.getZExtent()); mt.loadIdentity(); mt.setTranslation(mbb.getCenter()); mt.combineWithParent(geom.getWorldTransform()); mgeo.setLocalTransform(mt); } } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } } }
package killrvideo.service; import static killrvideo.utils.ExceptionUtils.mergeStackTrace; import java.util.Optional; import javax.annotation.PostConstruct; import javax.inject.Inject; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.MappingManager; import killrvideo.entity.Schema; import killrvideo.entity.TagsByLetter; import killrvideo.entity.VideoByTag; import killrvideo.utils.FutureUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.datastax.driver.core.PagingState; import io.grpc.Status; import io.grpc.stub.StreamObserver; import killrvideo.search.SearchServiceGrpc.AbstractSearchService; import killrvideo.search.SearchServiceOuterClass.GetQuerySuggestionsRequest; import killrvideo.search.SearchServiceOuterClass.GetQuerySuggestionsResponse; import killrvideo.search.SearchServiceOuterClass.SearchVideosRequest; import killrvideo.search.SearchServiceOuterClass.SearchVideosResponse; import killrvideo.validation.KillrVideoInputValidator; @Service public class SearchService extends AbstractSearchService { private static final Logger LOGGER = LoggerFactory.getLogger(SearchService.class); @Inject Mapper<VideoByTag> videosByTagMapper; @Inject Mapper<TagsByLetter> tagsByLetterMapper; @Inject MappingManager manager; @Inject KillrVideoInputValidator validator; private Session session; private String tagsByLetterTableName; private String videosByTagTableName; private PreparedStatement searchVideos_getVideosByTagPrepared; private PreparedStatement getQuerySuggestions_getTagsPrepared; @PostConstruct public void init() { this.session = manager.getSession(); tagsByLetterTableName = tagsByLetterMapper.getTableMetadata().getName(); videosByTagTableName = videosByTagMapper.getTableMetadata().getName(); searchVideos_getVideosByTagPrepared = session.prepare( QueryBuilder .select() .all() .from(Schema.KEYSPACE, videosByTagTableName) .where(QueryBuilder.eq("tag", QueryBuilder.bindMarker())) ); getQuerySuggestions_getTagsPrepared = session.prepare( QueryBuilder .select() .from(Schema.KEYSPACE, tagsByLetterTableName) .where(QueryBuilder.eq("first_letter", QueryBuilder.bindMarker())) .and(QueryBuilder.gte("tag", QueryBuilder.bindMarker())) ); } @Override public void searchVideos(SearchVideosRequest request, StreamObserver<SearchVideosResponse> responseObserver) { LOGGER.debug("Start searching video by tag"); if (!validator.isValid(request, responseObserver)) { return; } final Optional<String> pagingState = Optional .ofNullable(request.getPagingState()) .filter(StringUtils::isNotBlank); BoundStatement statement = searchVideos_getVideosByTagPrepared.bind() .setString("tag", request.getQuery()); statement.setFetchSize(request.getPageSize()); //:TODO Figure out more streamlined way to do this with Optional and java 8 lambda if (pagingState.isPresent()) { statement.setPagingState(PagingState.fromString(pagingState.get())); } FutureUtils.buildCompletableFuture(videosByTagMapper.mapAsync(session.executeAsync(statement))) .handle((videos, ex) -> { if (videos != null) { final SearchVideosResponse.Builder builder = SearchVideosResponse.newBuilder(); builder.setQuery(request.getQuery()); int remaining = videos.getAvailableWithoutFetching(); for (VideoByTag video : videos) { builder.addVideos(video.toResultVideoPreview()); if (--remaining == 0) { break; } } Optional.ofNullable(videos.getExecutionInfo().getPagingState()) .map(PagingState::toString) .ifPresent(builder::setPagingState); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); LOGGER.debug("End searching video by tag"); } else if (ex != null) { LOGGER.error("Exception when searching video by tag : " + mergeStackTrace(ex)); responseObserver.onError(Status.INTERNAL.withCause(ex).asRuntimeException()); } return videos; }); } @Override public void getQuerySuggestions(GetQuerySuggestionsRequest request, StreamObserver<GetQuerySuggestionsResponse> responseObserver) { LOGGER.debug("Start getting query suggestions by tag"); if (!validator.isValid(request, responseObserver)) { return; } BoundStatement statement = getQuerySuggestions_getTagsPrepared.bind() .setString("first_letter", request.getQuery().substring(0, 1)) .setString("tag", request.getQuery()); statement.setFetchSize(request.getPageSize()); FutureUtils.buildCompletableFuture(tagsByLetterMapper.mapAsync(session.executeAsync(statement))) .handle((tags, ex) -> { if (tags != null) { final GetQuerySuggestionsResponse.Builder builder = GetQuerySuggestionsResponse.newBuilder(); int remaining = tags.getAvailableWithoutFetching(); for (TagsByLetter tag : tags) { builder.addSuggestions(tag.getTag()); if (--remaining == 0) { break; } } builder.setQuery(request.getQuery()); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); LOGGER.debug("End getting query suggestions by tag"); } else if (ex != null) { LOGGER.error("Exception getting query suggestions by tag : " + mergeStackTrace(ex)); responseObserver.onError(Status.INTERNAL.withCause(ex).asRuntimeException()); } return tags; }); } }
package org.basex.gui.view.tree; import static org.basex.gui.GUIConstants.*; import java.awt.Color; import java.awt.Graphics; import java.awt.Transparency; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.util.LinkedList; import java.util.ListIterator; import javax.swing.SwingUtilities; import org.basex.core.Context; import org.basex.data.Data; import org.basex.data.Nodes; import org.basex.gui.GUIConstants; import org.basex.gui.GUIProp; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXPopup; import org.basex.gui.view.View; import org.basex.gui.view.ViewData; import org.basex.gui.view.ViewNotifier; import org.basex.gui.view.ViewRect; import org.basex.util.IntList; import org.basex.util.Token; public final class TreeView extends View implements TreeViewOptions { /** TreeBorders Object, contains cached pre values and borders. */ private TreeSubtree sub; /** TreeRects Object, contains cached rectangles. */ private TreeRects tr; /** Current font height. */ private int fontHeight; /** Current mouse position x. */ private int mousePosX = -1; /** Current mouse position y. */ private int mousePosY = -1; /** Window width. */ private int wwidth = -1; /** Window height. */ private int wheight = -1; /** Current Image of visualization. */ private BufferedImage treeImage; /** Notified focus flag. */ private boolean refreshedFocus; /** Distance between the levels. */ private int levelDistance; /** Image of the current marked nodes. */ private BufferedImage markedImage; /** If something is selected. */ private boolean selection; /** The selection rectangle. */ private ViewRect selectRect; /** The node height. */ private int nodeHeight; /** Top margin. */ private int topMargin; /** Distance between multiple trees. */ private double treedist; /** Currently focused rectangle. */ private TreeRect frect; /** Level of currently focused rectangle. */ private int flv = -1; /** Focused root number. */ private int frn; /** Focused pre. */ private int fpre; /** New tree initialization. */ private byte paintType; /** Array with current root nodes. */ private int[] roots; /** Real big rectangle. */ private boolean rbr; /** If something is in focus. */ private boolean inFocus; /** * Default constructor. * @param man view manager */ public TreeView(final ViewNotifier man) { super(TREEVIEW, null, man); new BaseXPopup(this, GUIConstants.POPUP); } @Override public void refreshContext(final boolean more, final boolean quick) { paintType = PAINT_NEW_CONTEXT; repaint(); } @Override public void refreshFocus() { refreshedFocus = true; repaint(); } @Override public void refreshInit() { if(!visible()) return; paintType = PAINT_NEW_INIT; repaint(); } @Override public void refreshLayout() { paintType = PAINT_NEW_WINDOW_SIZE; repaint(); } @Override public void refreshMark() { markNodes(); refreshedFocus = true; repaint(); } @Override public void refreshUpdate() { repaint(); } @Override public boolean visible() { final boolean v = gui.prop.is(GUIProp.SHOWTREE); if(!v) { sub = null; tr = null; paintType = PAINT_NEW_INIT; } return v; } @Override public void visible(final boolean v) { gui.prop.set(GUIProp.SHOWTREE, v); } @Override protected boolean db() { return true; } @Override public void paintComponent(final Graphics g) { final Context c = gui.context; final Data data = c.data; if(data == null) return; super.paintComponent(g); gui.painting = true; // timer // final Performance perf = new Performance(); // perf.initTimer(); // initializes sizes smooth(g); g.setFont(font); fontHeight = g.getFontMetrics().getHeight(); roots = gui.context.current.nodes; if(paintType == PAINT_NEW_INIT) { sub = new TreeSubtree(data); tr = new TreeRects(gui.prop); } if(paintType == PAINT_NEW_INIT || paintType == PAINT_NEW_CONTEXT) sub.generateBorders(c); if(paintType == PAINT_NEW_INIT || paintType == PAINT_NEW_CONTEXT || paintType == PAINT_NEW_WINDOW_SIZE || paintType == -1 && windowSizeChanged()) { treedist = tr.generateRects(sub, g, c, getWidth()); rbr = treedist == -1; markedImage = null; setLevelDistance(); createNewMainImage(); if(gui.context.marked.size() > 0) markNodes(); } g.drawImage(treeImage, 0, 0, getWidth(), getHeight(), this); if(selection) { if(selectRect != null) { // draw selection final int x = selectRect.w < 0 ? selectRect.x + selectRect.w : selectRect.x; final int y = selectRect.h < 0 ? selectRect.y + selectRect.h : selectRect.y; final int w = Math.abs(selectRect.w); final int h = Math.abs(selectRect.h); g.setColor(colormark1); g.drawRect(x, y, w, h); } markNodes(); } if(markedImage != null) g.drawImage(markedImage, 0, 0, getWidth(), getHeight(), this); // highlights the focused node inFocus = focus(); if(inFocus) { int focused = gui.context.focused; if(tr.isBigRectangle(sub, frn, flv)) { final int f = getMostSizedNode(data, frn, flv, frect, focused); if(f >= 0) focused = f; } highlightNode(g, frn, flv, frect, focused, -1, DRAW_HIGHLIGHT); if(SHOW_EXTRA_INFO) { g.setColor(new Color(0xeeeeee)); g.fillRect(0, getHeight() - fontHeight - 6, getWidth(), fontHeight + 6); final Data d = gui.context.data; final int k = d.kind(focused); final int s = d.size(focused, k); final int as = d.attSize(focused, k); g.setColor(Color.BLACK); g.drawString("pre: " + focused + " level: " + flv + " level-size: " + sub.getLevelSize(frn, flv) + " node-size: " + (s - as) + " node: " + Token.string(ViewData.tag(gui.prop, d, focused)), 2, getHeight() - 6); } } paintType = -1; gui.painting = false; } /** * Creates new image and draws rectangles in it. */ private void createNewMainImage() { treeImage = createImage(); final Graphics tg = treeImage.getGraphics(); final int rl = roots.length; tg.setFont(font); smooth(tg); if(!rbr) { for(int rn = 0; rn < rl; ++rn) { final int h = sub.getSubtreeHeight(rn); for(int lv = 0; lv < h; ++lv) { final boolean br = tr.isBigRectangle(sub, rn, lv); final TreeRect[] lr = tr.getTreeRectsPerLevel(rn, lv); for(int i = 0; i < lr.length; ++i) { final TreeRect r = lr[i]; final int pre = sub.getPrePerIndex(rn, lv, i); drawRectangle(tg, rn, lv, r, pre, DRAW_RECTANGLE); } if(br) { final TreeRect r = lr[0]; final int ww = r.x + r.w - 1; final int x = r.x + 1; drawBigRectSquares(tg, lv, x, ww, 4); } } if(SHOW_CONN_MI) { final TreeRect rr = tr.getTreeRectPerIndex(rn, 0, 0); highlightDescendants(tg, rn, 0, rr, roots[rn], getRectCenter(rr), DRAW_CONN); } } } else { drawRealBigRectangle(tg, DRAW_CONN); } } /** * Returns subtree-height of real big rectangles. * @param px pixel position * @return height */ private int getRealBigRectangleHeight(final int px) { final int p = getRealBigRectRootsPerPixel(); int pp = px / 2 * p; int maxHeight = 0; for(int i = pp; i < pp + p; ++i) { final int h = sub.getSubtreeHeight(i); if(h > maxHeight) maxHeight = h; } return maxHeight; } /** * Returns number of roots per pixel in real big rects. * @return number of roots */ private int getRealBigRectRootsPerPixel() { final int rl = roots.length; final double w = getWidth() / 4; // final double overhead = rl % w; return (int) (rl / w); } /** * Draws real big rectangles. * @param g graphics reference * @param t type */ private void drawRealBigRectangle(final Graphics g, final byte t) { final int w = getWidth(); g.setColor(getColorPerLevel(0, false)); g.drawRect(0, getYperLevel(0), w, nodeHeight); drawBigRectSquares(g, 0, 0, w, 4); for(int px = 0; px < w; px += 2) { final int maxHeight = getRealBigRectangleHeight(px); for(int i = 1; i < maxHeight; ++i) { final int y = getYperLevel(i); g.setColor(getColorPerLevel(i, false)); g.drawLine(px, y, px, y + nodeHeight); // draws line connection final int yy = getYperLevel(i - 1); final Color c = getConnectionColor(t); g.setColor(c); g.drawLine(px, yy + nodeHeight, px, y); } } } /** * Draws the squares inside big rectangles. * @param g graphics reference * @param lv level * @param x x-coordinate * @param w width * @param ss square-size */ private void drawBigRectSquares(final Graphics g, final int lv, final int x, final int w, final int ss) { int xx = x; final int y = getYperLevel(lv); int nh = nodeHeight; g.setColor(GUIConstants.back); while(nh > 0) { nh = nh - ss; while(nh < 0) nh++; g.drawLine(xx, y + nh, w, y + nh); } while(xx < w) { xx = xx + ss - 1 < w ? xx + ss : xx + ss - 1; g.drawLine(xx, y, xx, y + nodeHeight); } } /** * Return boolean if position is marked or not. * @param x x-coordinate * @param y y-coordinate * @return position is marked or not */ private boolean isMarked(final int x, final int y) { if(markedImage != null) { final int h = markedImage.getHeight(); final int w = markedImage.getWidth(); if(y > h || y < 0 || x > w || x < 0) return false; final int marc = markedImage.getRGB(x, y); return colormark1.getRGB() == marc || colormarkA.getRGB() == marc; } return false; } /** * Draws Rectangles. * @param g graphics reference * @param rn root * @param lv level * @param r rectangle * @param pre pre * @param t type */ private void drawRectangle(final Graphics g, final int rn, final int lv, final TreeRect r, final int pre, final byte t) { final int y = getYperLevel(lv); final int h = nodeHeight; final boolean br = tr.isBigRectangle(sub, rn, lv); boolean txt = !br && fontHeight <= h; boolean fill = false; boolean border = false; final int xx = r.x; final int ww = r.w; final boolean marked = isMarked(xx, y); Color borderColor = null; Color fillColor = null; Color textColor = Color.BLACK; switch(t) { case DRAW_RECTANGLE: borderColor = getColorPerLevel(lv, false); fillColor = getColorPerLevel(lv, true); txt = txt & DRAW_NODE_TEXT; border = BORDER_RECTANGLES; fill = FILL_RECTANGLES; break; case DRAW_HIGHLIGHT: borderColor = color6; final int alpha = 0xDD000000; final int rgb = GUIConstants.COLORCELL.getRGB(); fillColor = new Color(rgb + alpha, true); if(h > 4) border = true; fill = !br && !marked; break; case DRAW_MARK: borderColor = h > 2 && r.w > 4 ? colormarkA : colormark1; fillColor = colormark1; border = true; fill = true; break; case DRAW_DESCENDANTS: final int alphaD = 0xDD000000; final int rgbD = COLORS[6].getRGB(); fillColor = new Color(rgbD + alphaD, true); borderColor = COLORS[8]; textColor = Color.WHITE; fill = !marked; border = true; if(h < 4) { fillColor = SMALL_SPACE_COLOR; borderColor = fillColor; txt = false; } break; case DRAW_PARENT: fillColor = COLORS[6]; textColor = Color.WHITE; fill = !br && !marked; border = !br; if(h < 4) { fillColor = SMALL_SPACE_COLOR; borderColor = COLORS[8]; txt = false; } break; } if(border) { g.setColor(borderColor); g.drawRect(xx, y, ww, h); } if(fill) { g.setColor(fillColor); g.fillRect(xx + 1, y + 1, ww - 1, h - 1); } if(txt && (fill || !FILL_RECTANGLES)) { g.setColor(textColor); drawRectangleText(g, rn, lv, r, pre); } } /** * Draws text into rectangle. * @param g graphics reference * @param rn root * @param lv level * @param r rectangle * @param pre pre */ private void drawRectangleText(final Graphics g, final int rn, final int lv, final TreeRect r, final int pre) { String s = Token.string(tr.getText(gui.context, rn, pre)).trim(); if(r.w < BaseXLayout.width(g, s) && r.w < BaseXLayout.width(g, "..".concat(s.substring(s.length() - 1))) + MIN_TXT_SPACE) return; final int x = r.x; final int y = getYperLevel(lv); final int rm = x + (int) (r.w / 2f); int tw = BaseXLayout.width(g, s); if(tw > r.w) { s = s.concat(".."); while((tw = BaseXLayout.width(g, s)) + MIN_TXT_SPACE > r.w && s.length() > 3) { s = s.substring(0, (s.length() - 2) / 2).concat(".."); } } final int yy = (int) (y + (nodeHeight + fontHeight - 4) / 2d); g.drawString(s, (int) (rm - tw / 2d + BORDER_PADDING), yy); } /** * Returns draw Color. * @param l the current level * @param fill if true it returns fill color, rectangle color else * @return draw color */ private Color getColorPerLevel(final int l, final boolean fill) { final int till = l < CHANGE_COLOR_TILL ? l : CHANGE_COLOR_TILL; return fill ? COLORS[till] : COLORS[till + 2]; } /** * Marks nodes inside the dragged selection. */ private void markSelektedNodes() { final int x = selectRect.w < 0 ? selectRect.x + selectRect.w : selectRect.x; final int y = selectRect.h < 0 ? selectRect.y + selectRect.h : selectRect.y; final int w = Math.abs(selectRect.w); final int h = Math.abs(selectRect.h); final int t = y + h; final int size = sub.getMaxSubtreeHeight(); final IntList list = new IntList(); for(int r = 0; r < roots.length; ++r) { for(int i = 0; i < size; ++i) { final int yL = getYperLevel(i); if(i < sub.getSubtreeHeight(r) && (yL >= y || yL + nodeHeight >= y) && (yL <= t || yL + nodeHeight <= t)) { final TreeRect[] rlv = tr.getTreeRectsPerLevel(r, i); final int s = sub.getLevelSize(r, i); if(tr.isBigRectangle(sub, r, i)) { final TreeRect mRect = rlv[0]; int sPrePos = (int) (s * x / (double) mRect.w); int ePrePos = (int) (s * (x + w) / (double) mRect.w); if(sPrePos < 0) sPrePos = 0; if(ePrePos >= s) ePrePos = s - 1; while(sPrePos++ < ePrePos) list.add(sub.getPrePerIndex(r, i, sPrePos)); } else { for(int j = 0; j < s; ++j) { final TreeRect rect = rlv[j]; if(rect.contains(x, w)) list.add(sub.getPrePerIndex(r, i, j)); } } } } } gui.notify.mark(new Nodes(list.toArray(), gui.context.data), this); } /** * Creates a new translucent BufferedImage. * @return new translucent BufferedImage */ private BufferedImage createImage() { return new BufferedImage(Math.max(1, getWidth()), Math.max(1, getHeight()), Transparency.TRANSLUCENT); } /** * Highlights the marked nodes. */ private void markNodes() { markedImage = createImage(); final Graphics mg = markedImage.getGraphics(); smooth(mg); mg.setFont(font); final int[] mark = gui.context.marked.nodes; if(mark.length == 0) return; int rn = 0; while(rn < roots.length) { final LinkedList<Integer> marklink = new LinkedList<Integer>(); for(int i = 0; i < mark.length; ++i) marklink.add(i, mark[i]); for(int lv = 0; lv < sub.getSubtreeHeight(rn); ++lv) { final int y = getYperLevel(lv); final ListIterator<Integer> li = marklink.listIterator(); // TODO if(rbr) return; if(tr.isBigRectangle(sub, rn, lv)) { while(li.hasNext()) { final int pre = li.next(); final TreeRect rect = tr.searchRect(sub, rn, lv, pre); final int ix = sub.getPreIndex(rn, lv, pre); if(ix > -1) { li.remove(); final int x = (int) (rect.w * ix / (double) sub.getLevelSize(rn, lv)); mg.setColor(colormark1); mg.fillRect(rect.x + x, y, 2, nodeHeight + 1); } } } else { while(li.hasNext()) { final int pre = li.next(); final TreeRect rect = tr.searchRect(sub, rn, lv, pre); if(rect != null) { li.remove(); drawRectangle(mg, rn, lv, rect, pre, DRAW_MARK); } } } } rn++; } } /** * Returns position inside big rectangle. * @param rn root * @param lv level * @param pre pre * @param r rectangle * @return position */ private int getBigRectPosition(final int rn, final int lv, final int pre, final TreeRect r) { final int idx = sub.getPreIndex(rn, lv, pre); final double ratio = idx / (double) sub.getLevelSize(rn, lv); return r.x + (int) Math.round((r.w - 1) * ratio) + 1; } /** * Draws node inside big rectangle. * @param g the graphics reference * @param rn root * @param lv level * @param r rectangle * @param pre pre * @return node center */ private int drawNodeInBigRectangle(final Graphics g, final int rn, final int lv, final TreeRect r, final int pre) { final int y = getYperLevel(lv); final int np = getBigRectPosition(rn, lv, pre, r); g.setColor(nodeHeight < 4 ? SMALL_SPACE_COLOR : COLORS[7]); g.drawLine(np, y, np, y + nodeHeight); return np; } /** * Draws parent connection. * @param g the graphics reference * @param lv level * @param r rectangle * @param px parent x * @param brx bigrect x */ private void drawParentConnection(final Graphics g, final int lv, final TreeRect r, final int px, final int brx) { final int y = getYperLevel(lv); g.setColor(COLORS[7]); g.drawLine(px, getYperLevel(lv + 1) - 1, brx == -1 ? (2 * r.x + r.w) / 2 : brx, y + nodeHeight + 1); } /** * Highlights nodes. * @param g the graphics reference * @param rn root * @param pre pre * @param r rectangle to highlight * @param lv level * @param px parent's x value * @param t highlight type */ private void highlightNode(final Graphics g, final int rn, final int lv, final TreeRect r, final int pre, final int px, final byte t) { if(lv == -1) return; final boolean br = tr.isBigRectangle(sub, rn, lv); final boolean isRoot = roots[rn] == pre; final int height = sub.getSubtreeHeight(rn); final Data d = gui.context.data; final int k = d.kind(pre); final int size = d.size(pre, k); // rectangle center int rc = -1; if(br) { rc = drawNodeInBigRectangle(g, rn, lv, r, pre); } else { drawRectangle(g, rn, lv, r, pre, t); rc = getRectCenter(r); } // draw parent node connection if(px > -1 && MIN_NODE_DIST_CONN <= levelDistance) drawParentConnection(g, lv, r, px, rc); // if there are ancestors draw them if(!isRoot) { final int par = d.parent(pre, k); final int lvp = lv - 1; final TreeRect parRect = tr.searchRect(sub, rn, lvp, par); if(parRect == null) return; highlightNode(g, rn, lvp, parRect, par, rc, DRAW_PARENT); } // if there are descendants draw them if((t == DRAW_CONN || t == DRAW_HIGHLIGHT) && size > 1 && lv + 1 < height) highlightDescendants( g, rn, lv, r, pre, rc, t); // draws node text if(t == DRAW_HIGHLIGHT) drawThumbnails(g, rn, lv, pre, r, isRoot); } /** * Draws thumbnails. * @param g the graphics reference * @param rn root * @param lv level * @param pre pre * @param r rect * @param isRoot is root node? */ private void drawThumbnails(final Graphics g, final int rn, final int lv, final int pre, final TreeRect r, final boolean isRoot) { final int x = r.x; final int y = getYperLevel(lv); final int h = nodeHeight; final String s = Token.string(tr.getText(gui.context, rn, pre)); final int w = BaseXLayout.width(g, s); g.setColor(COLORS[8]); if(isRoot) { g.fillRect(x, y + h, w + 2, fontHeight + 2); g.setColor(COLORS[6]); g.drawRect(x - 1, y + h + 1, w + 3, fontHeight + 1); g.setColor(Color.WHITE); g.drawString(s, r.x + 1, (int) (y + h + (float) fontHeight) - 2); } else { g.fillRect(r.x, y - fontHeight, w + 2, fontHeight); g.setColor(COLORS[6]); g.drawRect(r.x - 1, y - fontHeight - 1, w + 3, fontHeight + 1); g.setColor(Color.WHITE); g.drawString(s, r.x + 1, (int) (y - h / (float) fontHeight) - 2); } } /** * Highlights descendants. * @param g the graphics reference * @param rn root * @param lv level * @param r rectangle to highlight * @param pre pre * @param px parent's x value * @param t highlight type */ private void highlightDescendants(final Graphics g, final int rn, final int lv, final TreeRect r, final int pre, final int px, final byte t) { // System.out.println(rn + " " + pre +" " + lv + " "); final Data d = gui.context.current.data; final boolean br = tr.isBigRectangle(sub, rn, lv); if(!br && t != DRAW_CONN) drawRectangle(g, rn, lv, r, pre, t); final int lvd = lv + 1; final TreeBorder[] sbo = sub.subtree(d, pre); if(sub.getSubtreeHeight(rn) >= lvd && sbo.length >= 2) { final boolean brd = tr.isBigRectangle(sub, rn, lvd); if(brd) { drawBigRectDescendants(g, rn, lvd, sbo, px, t); } else { final TreeBorder bo = sbo[1]; final TreeBorder bos = sub.getTreeBorder(rn, lvd); // System.out.println("###\npre " + pre + " rn:" + rn + " lv:" + lv // + "\nbo-start:" + bo.start + " bos-start:" + bos.start // + " bo-size:" + bo.size + " bos-size:" + bos.size + " bo - bos: " // + (bo.start - bos.start) + " cs: " + cs + "\n final int start = bo.start >= bos.start ? bo.start - bos.start : bo.start; for(int j = 0; j < bo.size; ++j) { final int dp = sub.getPrePerIndex(rn, lvd, j + start); final TreeRect dr = tr.getTreeRectPerIndex(rn, lvd, j + start); if(SHOW_DESCENDANTS_CONN && levelDistance >= MIN_NODE_DIST_CONN) drawDescendantsConn( g, lvd, dr, px, t); highlightDescendants(g, rn, lvd, dr, dp, getRectCenter(dr), t == DRAW_CONN ? DRAW_CONN : DRAW_DESCENDANTS); } } } // private void highlightDescendants(final Graphics g, final int rn, // final int pre, final TreeRect r, final int l, // final int px, final byte t) { // final Data d = gui.context.current.data; // if(!cache.isBigRectangle(rn, l) && t != DRAW_CONN) drawRectangle(g, rn, // r, pre, t); // final int lv = l + 1; // final TreeBorder[] sbo = cache.generateSubtreeBorders(d, pre); // if(cache.getHeight(rn) <= lv || sbo.length < 2) return; // final int parc = px == -1 ? (2 * r.x + r.w) / 2 : px; // if(cache.isBigRectangle(rn, lv)) { // drawBigRectDescendants(g, rn, lv, sbo, parc, t); // } else { // final TreeBorder bo = sbo[1]; // final TreeBorder bos = cache.getTreeBorder(rn, lv); // for(int j = 0; j < bo.size; ++j) { // final int pi = cache.getPrePerIndex(bo, j); // // if(gui.context.current.nodes[0] > 0) System.out.println("rn:" + rn // // + " lv:" + lv + " bo-size:" + bo.size + " bo-start:" + (bo.start) // // + " bos-start:" + bos.start); // final int start = bo.start >= bos.start ? bo.start - bos.start // : bo.start; // final TreeRect sr = cache.getTreeRectPerIndex(rn, lv, j + start); // if(SHOW_DESCENDANTS_CONN && levelDistance >= MIN_NODE_DIST_CONN) { // drawDescendantsConn(g, lv, sr, parc, t); // highlightDescendants(g, rn, pi, sr, lv, -1, t == DRAW_CONN ? DRAW_CONN // : DRAW_DESCENDANTS); } /** * Returns rectangle center. * @param r TreeRect * @return center */ private int getRectCenter(final TreeRect r) { return (2 * r.x + r.w) / 2; } /** * Draws descendants for big rectangles. * @param g graphics reference * @param rn root * @param lv level * @param subt subtree * @param parc parent center * @param t type */ private void drawBigRectDescendants(final Graphics g, final int rn, final int lv, final TreeBorder[] subt, final int parc, final byte t) { int lvv = lv; int cen = parc; int i; for(i = 1; i < subt.length && tr.isBigRectangle(sub, rn, lvv); i++) { final TreeBorder bos = sub.getTreeBorder(rn, lvv); final TreeBorder bo = subt[i]; final TreeRect r = tr.getTreeRectPerIndex(rn, lvv, 0); final int start = bo.start - bos.start; final double sti = start / (double) bos.size; final double eni = (start + bo.size) / (double) bos.size; final int df = r.x + (int) (r.w * sti); final int dt = r.x + (int) (r.w * eni); final int ww = Math.max(dt - df, 2); if(MIN_NODE_DIST_CONN <= levelDistance) drawDescendantsConn(g, lvv, new TreeRect(df, ww), cen, t); cen = (2 * df + ww) / 2; switch(t) { case DRAW_CONN: break; default: final int rgb = COLORS[7].getRGB(); final int alpha = 0x33000000; g.setColor(nodeHeight < 4 ? SMALL_SPACE_COLOR : new Color( rgb + alpha, false)); if(nodeHeight > 2) { g.drawRect(df, getYperLevel(lvv) + 1, ww, nodeHeight - 2); } else { g.drawRect(df, getYperLevel(lvv), ww, nodeHeight); } } if(lvv + 1 < sub.getSubtreeHeight(rn) && !tr.isBigRectangle(sub, rn, lvv + 1)) { final Data d = gui.context.current.data; for(int j = start; j < start + bo.size; ++j) { final int pre = sub.getPrePerIndex(rn, lvv, j); final int pos = getBigRectPosition(rn, lvv, pre, r); final int k = d.kind(pre); final int s = d.size(pre, k); if(s > 1) highlightDescendants(g, rn, lvv, r, pre, pos, t == DRAW_HIGHLIGHT || t == DRAW_DESCENDANTS ? DRAW_DESCENDANTS : DRAW_CONN); } } lvv++; } } /** * Returns connection color. * @param t type * @return color */ private Color getConnectionColor(final byte t) { int alpha; int rgb; Color c; switch(t) { case DRAW_CONN: alpha = 0x20000000; rgb = COLORS[4].getRGB(); c = new Color(rgb + alpha, true); break; default: case DRAW_DESCENDANTS: alpha = 0x60000000; rgb = COLORS[8].getRGB(); c = new Color(rgb + alpha, true); break; } return c; } /** * Draws descendants connection. * @param g graphics reference * @param lv level * @param r TreeRect * @param parc parent center * @param t type */ private void drawDescendantsConn(final Graphics g, final int lv, final TreeRect r, final int parc, final byte t) { final int pary = getYperLevel(lv - 1) + nodeHeight; final int prey = getYperLevel(lv) - 1; final int boRight = r.x + r.w + BORDER_PADDING - 2; final int boLeft = r.x + BORDER_PADDING; final int boTop = prey + 1; final Color c = getConnectionColor(t); if(SHOW_3D_CONN) { final int boBottom = prey + nodeHeight + 1; final int parmx = r.x + (int) ((boRight - boLeft) / 2d); final int dis = 0x111111; final int alpha = 0x20000000; final int rgb = COLORS[4].getRGB(); final Color ca = new Color(rgb + alpha - dis, false); final Color cb = new Color(rgb + alpha + dis, false); // g.setColor(new Color(0x444444, false)); g.setColor(cb); // g.setColor(new Color(0x666666, false)); g.drawPolygon(new int[] { parc, boRight, boRight}, new int[] { pary, boBottom, boTop}, 3); // g.setColor(new Color(0x666666, false)); g.drawPolygon(new int[] { parc, boLeft, boLeft}, new int[] { pary, boBottom, boTop}, 3); g.setColor(c); // g.setColor(new Color(0x555555, false)); g.drawPolygon(new int[] { parc, boLeft, boRight}, new int[] { pary, boTop, boTop}, 3); g.setColor(Color.BLACK); if(parmx < parc) g.drawLine(boRight, boBottom, parc, pary); else if(parmx > parc) g.drawLine(boLeft, boBottom, parc, pary); // g.setColor(cb); // // g.setColor(new Color(0x666666, false)); // g.drawLine(boRight, boTop, parc, pary); // g.drawLine(boLeft, boTop, parc, pary); } else { g.setColor(c); if(boRight - boLeft > 2) { g.fillPolygon(new int[] { parc, boRight, boLeft}, new int[] { pary, boTop, boTop}, 3); } else { g.drawLine((boRight + boLeft) / 2, boTop, parc, pary); } } } /** * Finds rectangle at cursor position. * @return focused rectangle */ private boolean focus() { if(refreshedFocus) { if(rbr) return false; final int pre = gui.context.focused; for(int r = 0; r < roots.length; ++r) { for(int i = 0; i < sub.getSubtreeHeight(r); ++i) { if(tr.isBigRectangle(sub, r, i)) { final int index = sub.getPreIndex(r, i, pre); if(index > -1) { frn = r; frect = tr.getTreeRectsPerLevel(r, i)[0]; flv = i; refreshedFocus = false; return true; } } else { final TreeRect rect = tr.searchRect(sub, r, i, pre); if(rect != null) { frn = r; frect = rect; flv = i; refreshedFocus = false; return true; } } } } } else { final int lv = getLevelPerY(mousePosY); if(rbr) { // final int ms = mousePosX / 2; // final int rts = getRealBigRectRootNum() * ms; } else { final int rn = frn = getTreePerX(mousePosX); final int h = sub.getSubtreeHeight(rn); if(lv < 0 || h < 0 || lv >= h) return false; final TreeRect[] rL = tr.getTreeRectsPerLevel(rn, lv); for(int i = 0; i < rL.length; ++i) { final TreeRect r = rL[i]; if(r.contains(mousePosX)) { frect = r; flv = lv; int pre = -1; // if multiple pre values, then approximate pre value if(tr.isBigRectangle(sub, rn, lv)) { pre = tr.getPrePerXPos(sub, rn, lv, mousePosX); } else { pre = sub.getPrePerIndex(rn, lv, i); } fpre = pre; gui.notify.focus(pre, this); refreshedFocus = false; return true; } } } } refreshedFocus = false; return false; } /** * Returns the y-axis value for a given level. * @param level the level * @return the y-axis value */ private int getYperLevel(final int level) { return level * nodeHeight + level * levelDistance + topMargin; } /** * Determines tree number. * @param x x-axis value * @return tree number */ private int getTreePerX(final int x) { return (int) (x / treedist); } /** * Determines the level of a y-axis value. * @param y the y-axis value * @return the level if inside a node rectangle, -1 else */ private int getLevelPerY(final int y) { final double f = (y - topMargin) / ((float) levelDistance + nodeHeight); final double b = nodeHeight / (float) (levelDistance + nodeHeight); return f <= (int) f + b ? (int) f : -1; } /** * Sets optimal distance between levels. */ private void setLevelDistance() { final int h = getHeight() - BOTTOM_MARGIN; int lvs = 0; for(int i = 0; i < roots.length; ++i) { final int th = sub.getSubtreeHeight(i); if(th > lvs) lvs = th; } nodeHeight = MAX_NODE_HEIGHT; int lD; while((lD = (int) ((h - lvs * nodeHeight) / (double) (lvs - 1))) < (nodeHeight <= BEST_NODE_HEIGHT ? MIN_LEVEL_DISTANCE : BEST_LEVEL_DISTANCE) && nodeHeight >= MIN_NODE_HEIGHT) nodeHeight levelDistance = lD < MIN_LEVEL_DISTANCE ? MIN_LEVEL_DISTANCE : lD > MAX_LEVEL_DISTANCE ? MAX_LEVEL_DISTANCE : lD; final int ih = (int) ((h - (levelDistance * (lvs - 1) + lvs * nodeHeight)) / 2d); topMargin = ih < TOP_MARGIN ? TOP_MARGIN : ih; } /** * Returns true if window-size has changed. * @return window-size has changed */ private boolean windowSizeChanged() { if(wwidth > -1 && wheight > -1 && getHeight() == wheight && getWidth() == wwidth) return false; wheight = getHeight(); wwidth = getWidth(); return true; } /** * Returns number of hit nodes. * @param rn root * @param lv level * @param r rectangle * @return size */ private int getHitBigRectNodesNum(final int rn, final int lv, final TreeRect r) { final int w = r.w; final int ls = sub.getLevelSize(rn, lv); return Math.max(ls / Math.max(w, 1), 1); } /** * Returns most sized node. * @param d the data reference * @param rn root * @param lv level * @param r rectangle * @param p pre * @return deepest node pre */ private int getMostSizedNode(final Data d, final int rn, final int lv, final TreeRect r, final int p) { final int size = getHitBigRectNodesNum(rn, lv, r); final int idx = sub.getPreIndex(rn, lv, p); if(idx < 0) return -1; int dpre = -1; int si = 0; for(int i = 0; i < size; ++i) { final int pre = sub.getPrePerIndex(rn, lv, i + idx); final int k = d.kind(pre); final int s = d.size(pre, k); if(s > si) { si = s; dpre = pre; } } return dpre; } @Override public void mouseMoved(final MouseEvent e) { if(gui.updating) return; super.mouseMoved(e); // refresh mouse focus mousePosX = e.getX(); mousePosY = e.getY(); repaint(); } @Override public void mouseClicked(final MouseEvent e) { final boolean left = SwingUtilities.isLeftMouseButton(e); final boolean right = !left; if(!right && !left || frect == null) return; if(left && inFocus) { if(flv >= sub.getSubtreeHeight(frn)) return; if(tr.isBigRectangle(sub, frn, flv)) { final Nodes ns = new Nodes(gui.context.data); final int sum = getHitBigRectNodesNum(frn, flv, frect); final int fix = sub.getPreIndex(frn, flv, fpre); final int[] m = new int[sum]; for(int i = 0; i < sum; ++i) { m[i] = sub.getPrePerIndex(frn, flv, i + fix); } ns.union(m); gui.notify.mark(ns, null); } else { gui.notify.mark(0, null); } if(e.getClickCount() > 1) { gui.notify.context(gui.context.marked, false, this); refreshContext(false, false); } } } @Override public void mouseWheelMoved(final MouseWheelEvent e) { if(gui.updating || gui.context.focused == -1) return; if(e.getWheelRotation() > 0) gui.notify.context(new Nodes( gui.context.focused, gui.context.data), false, null); else gui.notify.hist(false); } @Override public void mouseDragged(final MouseEvent e) { if(gui.updating || e.isShiftDown()) return; if(!selection) { selection = true; selectRect = new ViewRect(); selectRect.x = e.getX(); selectRect.y = e.getY(); selectRect.h = 1; selectRect.w = 1; } else { final int x = e.getX(); final int y = e.getY(); selectRect.w = x - selectRect.x; selectRect.h = y - selectRect.y; } markSelektedNodes(); repaint(); } @Override public void mouseReleased(final MouseEvent e) { if(gui.updating || gui.painting) return; selection = false; repaint(); } }
package org.cboard.jdbc; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang.StringUtils; import org.cboard.cache.CacheManager; import org.cboard.cache.HeapCacheManager; import org.cboard.dataprovider.AggregateProvider; import org.cboard.dataprovider.DataProvider; import org.cboard.dataprovider.annotation.DatasourceParameter; import org.cboard.dataprovider.annotation.ProviderName; import org.cboard.dataprovider.annotation.QueryParameter; import org.cboard.dataprovider.config.AggConfig; import org.cboard.dataprovider.config.DimensionConfig; import org.cboard.dataprovider.config.ValueConfig; import org.cboard.dataprovider.result.AggregateResult; import org.cboard.dataprovider.result.ColumnIndex; import org.cboard.exception.CBoardException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import javax.sql.DataSource; import java.sql.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; @ProviderName(name = "jdbc") public class JdbcDataProvider extends DataProvider implements AggregateProvider { private static final Logger LOG = LoggerFactory.getLogger(JdbcDataProvider.class); @Value("${dataprovider.resultLimit:200000}") private int resultLimit; @DatasourceParameter(label = "{{'DATAPROVIDER.JDBC.DRIVER'|translate}}", type = DatasourceParameter.Type.Input, order = 1) private String DRIVER = "driver"; @DatasourceParameter(label = "{{'DATAPROVIDER.JDBC.JDBCURL'|translate}}", type = DatasourceParameter.Type.Input, order = 2) private String JDBC_URL = "jdbcurl"; @DatasourceParameter(label = "{{'DATAPROVIDER.JDBC.USERNAME'|translate}}", type = DatasourceParameter.Type.Input, order = 3) private String USERNAME = "username"; @DatasourceParameter(label = "{{'DATAPROVIDER.JDBC.PASSWORD'|translate}}", type = DatasourceParameter.Type.Password, order = 4) private String PASSWORD = "password"; @DatasourceParameter(label = "{{'DATAPROVIDER.JDBC.POOLEDCONNECTION'|translate}}", type = DatasourceParameter.Type.Checkbox, order = 5) private String POOLED = "pooled"; @QueryParameter(label = "{{'DATAPROVIDER.JDBC.SQLTEXT'|translate}}", type = QueryParameter.Type.TextArea, order = 1) private String SQL = "sql"; private static final CacheManager<Map<String, Integer>> typeCahce = new HeapCacheManager<>(); private static final ConcurrentMap<String, DataSource> datasourceMap = new ConcurrentHashMap<>(); private String getKey(Map<String, String> dataSource, Map<String, String> query) { return Hashing.md5().newHasher().putString(JSONObject.toJSON(dataSource).toString() + JSONObject.toJSON(query).toString(), Charsets.UTF_8).hash().toString(); } public String[][] getData(Map<String, String> dataSource, Map<String, String> query) throws Exception { LOG.debug("Execute JdbcDataProvider.getData() Start!"); String sql = getAsSubQuery(query.get(SQL)); List<String[]> list = null; LOG.info("SQL String: " + sql); try (Connection con = getConnection(dataSource)) { Statement ps = con.createStatement(); ResultSet rs = ps.executeQuery(sql); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); list = new LinkedList<>(); String[] row = new String[columnCount]; for (int i = 0; i < columnCount; i++) { row[i] = metaData.getColumnLabel(i + 1); } list.add(row); int resultCount = 0; while (rs.next()) { resultCount++; if (resultCount > resultLimit) { throw new CBoardException("Cube result count is greater than limit " + resultLimit); } row = new String[columnCount]; for (int j = 0; j < columnCount; j++) { row[j] = rs.getString(j + 1); } list.add(row); } } catch (Exception e) { LOG.error("ERROR:" + e.getMessage()); throw new Exception("ERROR:" + e.getMessage(), e); } return list.toArray(new String[][]{}); } /** * Convert the sql text to subquery string: * remove blank line * remove end semicolon ; * * @param rawQueryText * @return */ private String getAsSubQuery(String rawQueryText) { String deletedBlankLine = rawQueryText.replaceAll("(?m)^[\\s\t]*\r?\n", "").trim(); return deletedBlankLine.endsWith(";") ? deletedBlankLine.substring(0, deletedBlankLine.length() - 1) : deletedBlankLine; } private Connection getConnection(Map<String, String> dataSource) throws Exception { String usePool = dataSource.get(POOLED); String username = dataSource.get(USERNAME); String password = dataSource.get(PASSWORD); Connection conn = null; if (usePool != null && "true".equals(usePool)) { String key = Hashing.md5().newHasher().putString(JSONObject.toJSON(dataSource).toString(), Charsets.UTF_8).hash().toString(); DataSource ds = datasourceMap.get(key); if (ds == null) { synchronized (key.intern()) { ds = datasourceMap.get(key); if (ds == null) { Map<String, String> conf = new HashedMap(); conf.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, dataSource.get(DRIVER)); conf.put(DruidDataSourceFactory.PROP_URL, dataSource.get(JDBC_URL)); conf.put(DruidDataSourceFactory.PROP_USERNAME, dataSource.get(USERNAME)); if (StringUtils.isNotBlank(password)) { conf.put(DruidDataSourceFactory.PROP_PASSWORD, dataSource.get(PASSWORD)); } conf.put(DruidDataSourceFactory.PROP_INITIALSIZE, "3"); DruidDataSource druidDS = (DruidDataSource) DruidDataSourceFactory.createDataSource(conf); druidDS.setBreakAfterAcquireFailure(true); druidDS.setConnectionErrorRetryAttempts(5); datasourceMap.put(key, druidDS); } } } try { conn = ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); datasourceMap.remove(key); throw e; } return conn; } else { String driver = dataSource.get(DRIVER); String jdbcurl = dataSource.get(JDBC_URL); Class.forName(driver); Properties props = new Properties(); props.setProperty("user", username); if (StringUtils.isNotBlank(password)) { props.setProperty("password", password); } return DriverManager.getConnection(jdbcurl, props); } } @Override public String[][] queryDimVals(Map<String, String> dataSource, Map<String, String> query, String columnName, AggConfig config) throws Exception { String fsql = null; String exec = null; String sql = getAsSubQuery(query.get(SQL)); List<String> filtered = new ArrayList<>(); List<String> nofilter = new ArrayList<>(); if (config != null) { Stream<DimensionConfig> c = config.getColumns().stream(); Stream<DimensionConfig> r = config.getRows().stream(); Stream<DimensionConfig> f = config.getFilters().stream(); Stream<DimensionConfig> filters = Stream.concat(Stream.concat(c, r), f); Map<String, Integer> types = getColumnType(dataSource, query); Stream<DimensionConfigHelper> filterHelpers = filters.map(fe -> new DimensionConfigHelper(fe, types.get(fe.getColumnName()))); String whereStr = assembleSqlFilter(filterHelpers, "WHERE"); fsql = "SELECT __view__.%s FROM (%s) __view__ %s GROUP BY __view__.%s"; exec = String.format(fsql, columnName, sql, whereStr, columnName); LOG.info(exec); try (Connection connection = getConnection(dataSource); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(exec)) { while (rs.next()) { filtered.add(rs.getString(1)); } } catch (Exception e) { LOG.error("ERROR:" + e.getMessage()); throw new Exception("ERROR:" + e.getMessage(), e); } } fsql = "SELECT __view__.%s FROM (%s) __view__ GROUP BY __view__.%s"; exec = String.format(fsql, columnName, sql, columnName); LOG.info(exec); try (Connection connection = getConnection(dataSource); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(exec)) { while (rs.next()) { nofilter.add(rs.getString(1)); } } catch (Exception e) { LOG.error("ERROR:" + e.getMessage()); throw new Exception("ERROR:" + e.getMessage(), e); } return new String[][]{config == null ? nofilter.toArray(new String[]{}) : filtered.toArray(new String[]{}), nofilter.toArray(new String[]{})}; } /** * Parser a single filter configuration to sql syntax */ private Function<DimensionConfigHelper, String> filter2SqlCondtion = (config) -> { if (config.getValues().size() == 0) { return null; } switch (config.getFilterType()) { case "=": case "eq": return config.getColumnName() + " IN (" + IntStream.range(0, config.getValues().size()).boxed().map(i -> config.getValueStr(i)).collect(Collectors.joining(",")) + ")"; case "≠": case "ne": return config.getColumnName() + " NOT IN (" + IntStream.range(0, config.getValues().size()).boxed().map(i -> config.getValueStr(i)).collect(Collectors.joining(",")) + ")"; case ">": return config.getColumnName() + " > " + config.getValueStr(0); case "<": return config.getColumnName() + " < " + config.getValueStr(0); case "≥": return config.getColumnName() + " >= " + config.getValueStr(0); case "≤": return config.getColumnName() + " <= " + config.getValueStr(0); case "(a,b]": if (config.getValues().size() >= 2) { return "(" + config.getColumnName() + " > '" + config.getValueStr(0) + "' AND " + config.getColumnName() + " <= " + config.getValueStr(1) + ")"; } else { return null; } case "[a,b)": if (config.getValues().size() >= 2) { return "(" + config.getColumnName() + " >= " + config.getValueStr(0) + " AND " + config.getColumnName() + " < " + config.getValueStr(1) + ")"; } else { return null; } case "(a,b)": if (config.getValues().size() >= 2) { return "(" + config.getColumnName() + " > " + config.getValueStr(0) + " AND " + config.getColumnName() + " < " + config.getValueStr(1) + ")"; } else { return null; } case "[a,b]": if (config.getValues().size() >= 2) { return "(" + config.getColumnName() + " >= " + config.getValueStr(0) + " AND " + config.getColumnName() + " <= " + config.getValueStr(1) + ")"; } else { return null; } } return null; }; private String assembleSqlFilter(Stream<DimensionConfigHelper> filterStream, String prefix) { StringJoiner where = new StringJoiner("\nAND ", prefix + " ", ""); where.setEmptyValue(""); filterStream.map(filter2SqlCondtion).filter(e -> e != null).forEach(where::add); return where.toString(); } private String assembleAggValColumns(Stream<ValueConfig> selectStream) { StringJoiner columns = new StringJoiner(", ", "", " "); columns.setEmptyValue(""); selectStream.map(toSelect).filter(e -> e != null).forEach(columns::add); return columns.toString(); } private String assembleDimColumns(Stream<DimensionConfig> columnsStream) { StringJoiner columns = new StringJoiner(", ", "", " "); columns.setEmptyValue(""); columnsStream.map(g -> g.getColumnName()).distinct().filter(e -> e != null).forEach(columns::add); return columns.toString(); } private ResultSetMetaData getMetaData(String subQuerySql, Statement stat) throws Exception { ResultSetMetaData metaData; try { stat.setMaxRows(100); String fsql = "\nSELECT * FROM (\n%s\n) __view__ WHERE 1=0"; String sql = String.format(fsql, subQuerySql); LOG.info(sql); ResultSet rs = stat.executeQuery(sql); metaData = rs.getMetaData(); } catch (Exception e) { LOG.error("ERROR:" + e.getMessage()); throw new Exception("ERROR:" + e.getMessage(), e); } return metaData; } private Map<String, Integer> getColumnType(Map<String, String> dataSource, Map<String, String> query) throws Exception { Map<String, Integer> result = null; String key = getKey(dataSource, query); String subQuerySql = getAsSubQuery(query.get(SQL)); result = typeCahce.get(key); if (result != null) { return result; } else { try ( Connection connection = getConnection(dataSource); Statement stat = connection.createStatement() ) { ResultSetMetaData metaData = getMetaData(subQuerySql, stat); int columnCount = metaData.getColumnCount(); result = new HashedMap(); for (int i = 0; i < columnCount; i++) { result.put(metaData.getColumnLabel(i + 1), metaData.getColumnType(i + 1)); } typeCahce.put(key, result, 12 * 60 * 60 * 1000); return result; } } } @Override public String[] getColumn(Map<String, String> dataSource, Map<String, String> query) throws Exception { String subQuerySql = getAsSubQuery(query.get(SQL)); try ( Connection connection = getConnection(dataSource); Statement stat = connection.createStatement() ) { ResultSetMetaData metaData = getMetaData(subQuerySql, stat); int columnCount = metaData.getColumnCount(); String[] row = new String[columnCount]; for (int i = 0; i < columnCount; i++) { row[i] = metaData.getColumnLabel(i + 1); } return row; } } @Override public AggregateResult queryAggData(Map<String, String> dataSource, Map<String, String> query, AggConfig config) throws Exception { String exec = getQueryAggDataSql(dataSource, query, config); List<String[]> list = new LinkedList<>(); LOG.info(exec); try ( Connection connection = getConnection(dataSource); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(exec) ) { ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); while (rs.next()) { String[] row = new String[columnCount]; for (int j = 0; j < columnCount; j++) { row[j] = rs.getString(j + 1); } list.add(row); } } catch (Exception e) { LOG.error("ERROR:" + e.getMessage()); throw new Exception("ERROR:" + e.getMessage(), e); } // recreate a dimension stream Stream<DimensionConfig> dimStream = Stream.concat(config.getColumns().stream(), config.getRows().stream()); List<ColumnIndex> dimensionList = dimStream.map(ColumnIndex::fromDimensionConfig).collect(Collectors.toList()); dimensionList.addAll(config.getValues().stream().map(ColumnIndex::fromValueConfig).collect(Collectors.toList())); IntStream.range(0, dimensionList.size()).forEach(j -> dimensionList.get(j).setIndex(j)); String[][] result = list.toArray(new String[][]{}); return new AggregateResult(dimensionList, result); } private String getQueryAggDataSql(Map<String, String> dataSource, Map<String, String> query, AggConfig config) throws Exception { Stream<DimensionConfig> c = config.getColumns().stream(); Stream<DimensionConfig> r = config.getRows().stream(); Stream<DimensionConfig> f = config.getFilters().stream(); Stream<DimensionConfig> filters = Stream.concat(Stream.concat(c, r), f); Map<String, Integer> types = getColumnType(dataSource, query); Stream<DimensionConfigHelper> predicates = filters.map(fe -> new DimensionConfigHelper(fe, types.get(fe.getColumnName()))); Stream<DimensionConfig> dimStream = Stream.concat(config.getColumns().stream(), config.getRows().stream()); String dimColsStr = assembleDimColumns(dimStream); String aggColsStr = assembleAggValColumns(config.getValues().stream()); String whereStr = assembleSqlFilter(predicates, "WHERE"); String groupByStr = StringUtils.isBlank(dimColsStr) ? "" : "GROUP BY " + dimColsStr; StringJoiner selectColsStr = new StringJoiner(","); if (!StringUtils.isBlank(dimColsStr)) { selectColsStr.add(dimColsStr); } if (!StringUtils.isBlank(aggColsStr)) { selectColsStr.add(aggColsStr); } String subQuerySql = getAsSubQuery(query.get(SQL)); String fsql = "\nSELECT %s \n FROM (\n%s\n) __view__ \n %s \n %s"; String exec = String.format(fsql, selectColsStr, subQuerySql, whereStr, groupByStr); return exec; } @Override public String viewAggDataQuery(Map<String, String> dataSource, Map<String, String> query, AggConfig config) throws Exception { return getQueryAggDataSql(dataSource, query, config); } private Function<ValueConfig, String> toSelect = (config) -> { switch (config.getAggType()) { case "sum": return "SUM(__view__." + config.getColumn() + ") AS sum_" + config.getColumn(); case "avg": return "AVG(__view__." + config.getColumn() + ") AS avg_" + config.getColumn(); case "max": return "MAX(__view__." + config.getColumn() + ") AS max_" + config.getColumn(); case "min": return "MIN(__view__." + config.getColumn() + ") AS min_" + config.getColumn(); default: return "COUNT(__view__." + config.getColumn() + ") AS count_" + config.getColumn(); } }; private class DimensionConfigHelper extends DimensionConfig { private DimensionConfig config; private int type; public DimensionConfigHelper(DimensionConfig config, int type) { this.config = config; this.type = type; } public String getValueStr(int index) { switch (type) { case Types.VARCHAR: case Types.CHAR: case Types.NVARCHAR: case Types.NCHAR: case Types.CLOB: case Types.NCLOB: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.DATE: case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: return "'" + getValues().get(index) + "'"; default: return getValues().get(index); } } @Override public String getColumnName() { return config.getColumnName(); } @Override public void setColumnName(String columnName) { config.setColumnName(columnName); } @Override public String getFilterType() { return config.getFilterType(); } @Override public void setFilterType(String filterType) { config.setFilterType(filterType); } @Override public List<String> getValues() { return config.getValues(); } @Override public void setValues(List<String> values) { config.setValues(values); } } }
package org.cobbzilla.util.http; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.cobbzilla.util.collection.NameAndValue; import org.cobbzilla.util.string.StringUtil; import org.cobbzilla.util.system.CommandResult; import org.cobbzilla.util.system.CommandShell; import org.cobbzilla.util.system.Sleep; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION; import static org.apache.http.HttpHeaders.*; import static org.cobbzilla.util.daemon.ZillaRuntime.die; import static org.cobbzilla.util.daemon.ZillaRuntime.hexnow; import static org.cobbzilla.util.http.HttpContentTypes.contentType; import static org.cobbzilla.util.http.HttpMethods.*; import static org.cobbzilla.util.http.HttpStatusCodes.NO_CONTENT; import static org.cobbzilla.util.http.URIUtil.getFileExt; import static org.cobbzilla.util.io.FileUtil.getDefaultTempDir; import static org.cobbzilla.util.security.CryptStream.BUFFER_SIZE; import static org.cobbzilla.util.string.StringUtil.CRLF; import static org.cobbzilla.util.system.Sleep.sleep; import static org.cobbzilla.util.time.TimeUtil.DATE_FORMAT_LAST_MODIFIED; @Slf4j public class HttpUtil { public static Map<String, String> queryParams(URL url) throws UnsupportedEncodingException { return queryParams(url, StringUtil.UTF8); } public static Map<String, String> queryParams(URL url, String encoding) throws UnsupportedEncodingException { final Map<String, String> query_pairs = new LinkedHashMap<>(); final String query = url.getQuery(); final String[] pairs = query.split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); query_pairs.put(URLDecoder.decode(pair.substring(0, idx), encoding), URLDecoder.decode(pair.substring(idx + 1), encoding)); } return query_pairs; } public static InputStream getUrlInputStream(String url) throws IOException { return get(url); } public static InputStream get (String urlString) throws IOException { return get(urlString, null); } public static InputStream get (String urlString, Map<String, String> headers) throws IOException { return get(urlString, headers, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); return urlConnection.getInputStream(); } public static InputStream post (String urlString, InputStream data, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, POST, data, headers, headers2); } public static InputStream put (String urlString, InputStream data, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, PUT, data, headers, headers2); } public static InputStream upload (String urlString, String method, InputStream data, Map<String, String> headers, Map<String, String> headers2) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); urlConnection.setDoInput(true); final OutputStream upload = urlConnection.getOutputStream(); IOUtils.copyLarge(data, upload); return urlConnection.getInputStream(); } public static void addHeaders(HttpURLConnection urlConnection, Map<String, String> headers) { for (Map.Entry<String, String> h : headers.entrySet()) { urlConnection.setRequestProperty(h.getKey(), h.getValue()); } } public static HttpResponseBean upload (String url, File file, Map<String, String> headers) throws IOException { @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost method = new HttpPost(url); final FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", fileBody); method.setEntity(builder.build()); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { method.addHeader(new BasicHeader(header.getKey(), header.getValue())); } } @Cleanup final CloseableHttpResponse response = client.execute(method); final HttpResponseBean responseBean = new HttpResponseBean() .setEntityBytes(EntityUtils.toByteArray(response.getEntity())) .setHttpHeaders(response.getAllHeaders()) .setStatus(response.getStatusLine().getStatusCode()); return responseBean; } public static final int DEFAULT_RETRIES = 3; public static File url2file (String url) throws IOException { return url2file(url, null, DEFAULT_RETRIES); } public static File url2file (String url, String file) throws IOException { return url2file(url, file == null ? null : new File(file), DEFAULT_RETRIES); } public static File url2file (String url, File file) throws IOException { return url2file(url, file, DEFAULT_RETRIES); } public static File url2file (String url, File file, int retries) throws IOException { if (file == null) file = File.createTempFile("url2file-", getFileExt((url)), getDefaultTempDir()); IOException lastException = null; long sleep = 100; for (int i=0; i<retries; i++) { try { @Cleanup final InputStream in = get(url); @Cleanup final OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); lastException = null; break; } catch (IOException e) { lastException = e; sleep(sleep, "waiting to possibly retry after IOException: "+lastException); sleep *= 5; } } if (lastException != null) throw lastException; return file; } public static String url2string (String url) throws IOException { @Cleanup final InputStream in = get(url); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static HttpResponseBean getResponse(HttpRequestBean requestBean) throws IOException { final HttpClientBuilder clientBuilder = requestBean.initClientBuilder(HttpClients.custom()); @Cleanup final CloseableHttpClient client = clientBuilder.build(); return getResponse(requestBean, client); } public static HttpResponseBean getResponse(HttpRequestBean requestBean, HttpClient client) throws IOException { if (requestBean.hasStream()) return getStreamResponse(requestBean); final HttpResponseBean bean = new HttpResponseBean(); final HttpUriRequest request = initHttpRequest(requestBean); if (requestBean.hasHeaders()) { for (NameAndValue header : requestBean.getHeaders()) { request.setHeader(header.getName(), header.getValue()); } } final HttpResponse response = client.execute(request); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != NO_CONTENT && response.getEntity() != null) { bean.setContentLength(response.getEntity().getContentLength()); final Header contentType = response.getEntity().getContentType(); if (contentType != null) { bean.setContentType(contentType.getValue()); } @Cleanup final InputStream content = response.getEntity().getContent(); bean.setEntity(content); } return bean; } public static HttpResponseBean getStreamResponse(HttpRequestBean request) { if (!request.hasStream()) return die("getStreamResponse: request stream was not set"); try { final String boundary = hexnow(); request.withHeader(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); @Cleanup("disconnect") final HttpURLConnection connection = (HttpURLConnection) new URL(request.getUri()).openConnection(); connection.setDoOutput(true); connection.setRequestMethod(request.getMethod()); if (!request.hasContentLength() || (request.hasContentLength() && request.getContentLength() > BUFFER_SIZE)) { connection.setChunkedStreamingMode(BUFFER_SIZE); } for (NameAndValue header : request.getHeaders()) { connection.setRequestProperty(header.getName(), header.getValue()); } @Cleanup final OutputStream output = connection.getOutputStream(); @Cleanup final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, Charset.defaultCharset()), true); writer.append("--").append(boundary).append(CRLF); final String filename = request.getEntity(); addStreamHeader(writer, CONTENT_DISPOSITION, "form-data; name=\"file\"; filename=\""+ filename +"\""); addStreamHeader(writer, CONTENT_TYPE, contentType(filename)); writer.append(CRLF).flush(); IOUtils.copy(request.getEntityInputStream(), output); output.flush(); writer.append(CRLF); writer.append("--").append(boundary).append("--").append(CRLF).flush(); final HttpResponseBean response = new HttpResponseBean() .setStatus(connection.getResponseCode()) .setHttpHeaders(connection.getHeaderFields()); if (!request.discardResponseEntity()) { try { response.setEntity(connection.getInputStream()); } catch (IOException ioe) { response.setEntity(connection.getErrorStream()); } } return response; } catch (Exception e) { return die("getStreamResponse: "+e, e); } } private static PrintWriter addStreamHeader(PrintWriter writer, String name, String value) { writer.append(name).append(": ").append(value).append(CRLF); return writer; } public static HttpResponseBean getResponse(String urlString) throws IOException { final HttpResponseBean bean = new HttpResponseBean(); @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpResponse response = client.execute(new HttpGet(urlString.trim())); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getEntity() != null) { final Header contentType = response.getEntity().getContentType(); if (contentType != null) bean.setContentType(contentType.getValue()); bean.setContentLength(response.getEntity().getContentLength()); bean.setEntity(response.getEntity().getContent()); } return bean; } public static HttpUriRequest initHttpRequest(HttpRequestBean requestBean) { try { final HttpUriRequest request; switch (requestBean.getMethod()) { case HEAD: request = new HttpHead(requestBean.getUri()); break; case GET: request = new HttpGet(requestBean.getUri()); break; case POST: request = new HttpPost(requestBean.getUri()); break; case PUT: request = new HttpPut(requestBean.getUri()); break; case PATCH: request = new HttpPatch(requestBean.getUri()); break; case DELETE: request = new HttpDelete(requestBean.getUri()); break; default: return die("Invalid request method: " + requestBean.getMethod()); } if (requestBean.hasData() && request instanceof HttpEntityEnclosingRequestBase) { setData(requestBean.getEntity(), (HttpEntityEnclosingRequestBase) request); } return request; } catch (UnsupportedEncodingException e) { return die("initHttpRequest: " + e, e); } } private static void setData(Object data, HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { if (data == null) return; if (data instanceof String) { request.setEntity(new StringEntity((String) data)); } else if (data instanceof InputStream) { request.setEntity(new InputStreamEntity((InputStream) data)); } else { throw new IllegalArgumentException("Unsupported request entity type: "+data.getClass().getName()); } } public static String getContentType(HttpResponse response) { final Header contentTypeHeader = response.getFirstHeader(CONTENT_TYPE); return (contentTypeHeader == null) ? null : contentTypeHeader.getValue(); } public static boolean isOk(String url) { return isOk(url, URIUtil.getHost(url)); } public static boolean isOk(String url, String host) { final CommandLine command = new CommandLine("curl") .addArgument("--insecure") // since we are requested via the IP address, the cert will not match .addArgument("--header").addArgument("Host: " + host) // pass FQDN via Host header .addArgument("--silent") .addArgument("--location") // follow redirects .addArgument("--write-out").addArgument("%{http_code}") // just print status code .addArgument("--output").addArgument("/dev/null") // and ignore data .addArgument(url); try { final CommandResult result = CommandShell.exec(command); final String statusCode = result.getStdout(); return result.isZeroExitStatus() && statusCode != null && statusCode.trim().startsWith("2"); } catch (IOException e) { log.warn("isOk: Error fetching " + url + " with Host header=" + host + ": " + e); return false; } } public static boolean isOk(String url, String host, int maxTries, long sleepUnit) { long sleep = sleepUnit; for (int i = 0; i < maxTries; i++) { if (i > 0) { Sleep.sleep(sleep); sleep *= 2; } if (isOk(url, host)) return true; } return false; } public static HttpMeta getHeadMetadata(HttpRequestBean request) throws IOException { final HttpResponseBean headResponse = HttpUtil.getResponse(new HttpRequestBean(request).setMethod(HEAD)); if (!headResponse.isOk()) return die("HTTP HEAD response was not 200: "+headResponse); final HttpMeta meta = new HttpMeta(request.getUri()); final String lastModString = headResponse.getFirstHeaderValue(LAST_MODIFIED); if (lastModString != null) meta.setLastModified(DATE_FORMAT_LAST_MODIFIED.parseMillis(lastModString)); final String etag = headResponse.getFirstHeaderValue(ETAG); if (etag != null) meta.setEtag(etag); return meta; } public static final byte[] CHUNK_SEP = "\r\n".getBytes(); public static final int CHUNK_EXTRA_BYTES = 2 * CHUNK_SEP.length; public static final byte[] CHUNK_END = "0\r\n".getBytes(); public static byte[] makeHttpChunk(byte[] buffer, int bytesRead) { final byte[] httpChunkLengthBytes = Integer.toHexString(bytesRead).getBytes(); final byte[] httpChunk = new byte[bytesRead + httpChunkLengthBytes.length + CHUNK_EXTRA_BYTES]; System.arraycopy(httpChunkLengthBytes, 0, httpChunk, 0, httpChunkLengthBytes.length); System.arraycopy(buffer, 0, httpChunk, httpChunkLengthBytes.length, bytesRead); System.arraycopy(CHUNK_SEP, 0, httpChunk, httpChunkLengthBytes.length+bytesRead, CHUNK_SEP.length); return httpChunk; } }
package org.cobbzilla.util.yml; import com.github.mustachejava.DefaultMustacheFactory; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import java.io.*; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class YmlMerger { private static final Logger LOG = LoggerFactory.getLogger(YmlMerger.class); public static final DefaultMustacheFactory DEFAULT_MUSTACHE_FACTORY = new DefaultMustacheFactory(); private final Yaml yaml = new Yaml(); private final Map<String, Object> scope = new HashMap<String, Object>();; public YmlMerger() { init(System.getenv()); } public YmlMerger(Map<String, String> env) { init(env); } private void init(Map<String, String> env) { for (String varname : env.keySet()) { scope.put(varname, env.get(varname)); } } public Map<String, Object> merge(String[] files) throws IOException { Map<String, Object> mergedResult = new LinkedHashMap<String, Object>(); for (String file : files) { InputStream in = null; try { // read the file into a String in = new FileInputStream(file); final String entireFile = IOUtils.toString(in); // substitute variables final StringWriter writer = new StringWriter(entireFile.length() + 10); DEFAULT_MUSTACHE_FACTORY.compile(new StringReader(entireFile), "mergeyml_"+System.currentTimeMillis()).execute(writer, scope); // load the YML file final Map<String, Object> yamlContents = (Map<String, Object>) yaml.load(writer.toString()); // merge into results map merge_internal(mergedResult, yamlContents); LOG.info("loaded YML from "+file+": "+yamlContents); } finally { if (in != null) in.close(); } } return mergedResult; } private void merge_internal(Map<String, Object> mergedResult, Map<String, Object> yamlContents) { for (String key : yamlContents.keySet()) { Object yamlValue = yamlContents.get(key); if (yamlValue == null) { addToMergedResult(mergedResult, key, yamlValue); continue; } Object existingValue = mergedResult.get(key); if (existingValue != null) { if (yamlValue instanceof Map) { if (existingValue instanceof Map) { merge_internal((Map<String, Object>) existingValue, (Map<String, Object>) yamlValue); } else if (existingValue instanceof String) { throw new IllegalArgumentException("Cannot merge complex element into a simple element: "+key); } else { throw unknownValueType(key, yamlValue); } } else if (yamlValue instanceof String || yamlValue instanceof Boolean || yamlValue instanceof Double || yamlValue instanceof Integer) { LOG.info("overriding value of "+key+" with value "+yamlValue); addToMergedResult(mergedResult, key, yamlValue); } else { throw unknownValueType(key, yamlValue); } } else { if (yamlValue instanceof Map || yamlValue instanceof String || yamlValue instanceof Boolean|| yamlValue instanceof Integer|| yamlValue instanceof Double) { LOG.info("adding new key->value: "+key+"->"+yamlValue); addToMergedResult(mergedResult, key, yamlValue); } else { throw unknownValueType(key, yamlValue); } } } } private IllegalArgumentException unknownValueType(String key, Object yamlValue) { final String msg = "Cannot merge element of unknown type: " + key + ": " + yamlValue.getClass().getName(); LOG.error(msg); return new IllegalArgumentException(msg); } private Object addToMergedResult(Map<String, Object> mergedResult, String key, Object yamlValue) { return mergedResult.put(key, yamlValue); } public String mergeToString(String[] files) throws IOException { return toString(merge(files)); } public String toString(Map<String, Object> merged) { return yaml.dump(merged); } }
package org.hoby.nye.tym; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Vector; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.hoby.nye.tym.people.Donor; import org.hoby.nye.tym.people.JStaff; import org.hoby.nye.tym.people.Recipient; import org.hoby.nye.tym.people.Speaker; import org.hoby.nye.tym.people.Staff; import org.hoby.nye.tym.people.Student; import org.hoby.nye.tym.people.Writer; import org.hoby.nye.tym.utility.Address; import org.hoby.nye.tym.utility.ZipCode; public class ThankYouMatcher { private Workbook donors; private Workbook staff; private Workbook students; private Queue< Writer > studentList; private Map< Recipient, String > failed; public ThankYouMatcher() { donors = null; staff = null; students = null; studentList = new PriorityQueue<>(); failed = new HashMap<>(); } /** * * @param donorFile * @param staffFile * @param studentFile */ public void loadFiles( String donorFile, String staffFile, String studentFile ) { try( FileInputStream donorFis = new FileInputStream( donorFile ); FileInputStream staffFis = new FileInputStream( staffFile ); FileInputStream studentFis = new FileInputStream( studentFile ) ) { donors = WorkbookFactory.create( donorFis ); staff = WorkbookFactory.create( staffFis ); students = WorkbookFactory.create( studentFis ); } catch (FileNotFoundException fnfe) { System.err.println( "Couldn't find Excel file!"); fnfe.printStackTrace(); System.exit( -1 ); } catch (IOException ioe) { } catch (InvalidFormatException ife) { } } public void createMatchUps() { Vector < Recipient > donorList = new Vector<>(); // Read the Student information and populate the priority queue getStudentInfo(); // Read the Staff workbook, add all non-J-Staff to the donor list and add J-Staff to the student list //getStaffInfo( donorList ); /* * Read donor workbook pulling out information such name, organization, address, donor type, what was donated, and benefactor ( if one exists ) * If there is a benefactor, add this donor to their list and update the count of letters that student needs to write * If there is not a benefactor, add this donor to the list of donor that need letters */ getDonorInfo( donorList ); int count = 0; int priorCount = 0; for( Iterator< Recipient > it = donorList.iterator(); it.hasNext(); ) { /* * Needed to add the JStaff back into the PriorityQueue * Very inefficient since as the pairings go on, more polls will be needed * to get the first Student. Should overload the compareTo method to return MAX_INT */ Vector< Writer > storage = new Vector<>(); Recipient recipient = it.next(); Writer student = null; boolean invalidMatch; do { student = studentList.poll(); storage.add( student ); invalidMatch = student instanceof JStaff; if(!invalidMatch) { if (recipient instanceof Staff) { Staff staff = (Staff) recipient; if (staff.getPosition().contains("Facilitator") || staff.getPosition().contains("Junior Staff")) { String[] position = staff.getPosition().split(" "); Student ambassador = (Student) student; invalidMatch = (ambassador != null && !ambassador.getGroup().equals(position[0])); } else if (staff.getPosition().contains("Section Leader")) { String[] position = staff.getPosition().split(" "); Student ambassador = (Student) student; invalidMatch = (ambassador != null && !ambassador.getSection().equals(position[0])); } } } } while( invalidMatch ); student.addRecipient( recipient ); count++; if (count - priorCount != 1) { System.out.print(""); } priorCount=count; studentList.addAll( storage ); } /* * For each donor that hasn't already been assigned a student; poll the priority queue, add this donor to their list, update the count, offer the priority queue * For each speaker/panelist/judge; perform the same task * For each staff member; perform the same task */ writeMatches(); } public void writeMatches() { /* Write Excel spreadsheet with match information * Each row will be student information ( first, last, section, group ) followed by recipient information ( organization, first, last, address, donation/role/posistion ) */ // Create a new Workbook File xlsx = new File( "Thank-You-Matches.xlsx" ); if( !xlsx.exists() ) { try { xlsx.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Workbook wb = new XSSFWorkbook(); // Create a sheet for the match ups Sheet matchSheet = wb.createSheet( "Matches" ); // Create the header row and populate it Row header = matchSheet.createRow( 0 ); String[] headers = { "Student Name", "Student Section", "Student Group", "Donor Organization", "Donor Name", "Donor Address", "Donation", "Donation Information" }; for( int i = 0; i < headers.length; i++ ) { Cell cell = header.createCell( i ); cell.setCellValue( headers[i] ); } // Create and populate a row for each match up int rownum = 0; for( Iterator< Writer > it = studentList.iterator(); it.hasNext(); ) { // JStaff can be treated as a Student here because the needed information is stored in the Student super class of JStaff Student student = ( Student ) it.next(); // Create and populate a row for each recipient for( Iterator< Recipient > it2 = student.getRecipientList().iterator(); it2.hasNext(); ) { Row r = matchSheet.createRow( ++rownum ); r.createCell( 0 ).setCellValue( String.format( "%s %s", student.getFirstName(), student.getLastName() ) ); r.createCell( 1 ).setCellValue( student.getSection() ); r.createCell( 2 ).setCellValue( student.getGroup() ); Recipient recip = it2.next(); if( recip instanceof Donor) { Donor donor = ( Donor ) recip; r.createCell( 3 ).setCellValue( donor.getOrg() ); r.createCell( 4 ).setCellValue( String.format( "%s %s", donor.getFirstName(), donor.getLastName() ) ); Address address = donor.getAddress(); if( address == null ) { r.createCell( 5 ).setCellValue( "" ); } else { r.createCell( 5 ).setCellValue( String.format( "%s %n%s, %s %s", address.getLine1(), address.getCity(), address.getState(), address.getZip() ) ); } r.createCell( 6 ).setCellValue( donor.getDonorInfo() ); } else if( recip instanceof Speaker ) { Speaker speaker = ( Speaker ) recip; r.createCell( 3 ).setCellValue( "" ); r.createCell( 4 ).setCellValue( String.format( "%s %s", speaker.getFirstName(), speaker.getLastName() ) ); Address address = speaker.getAddress(); if( address == null ) { r.createCell( 5 ).setCellValue( "" ); } else { r.createCell( 5 ).setCellValue( String.format( "%s %n%s, %s %s", address.getLine1(), address.getCity(), address.getState(), address.getZip() ) ); } r.createCell( 6 ).setCellValue( speaker.getRole() ); } else if (recip instanceof Staff) { Staff staff = (Staff) recip; r.createCell( 3 ).setCellValue( "" ); r.createCell( 4 ).setCellValue( String.format( "%s %s", staff.getFirstName(), staff.getLastName() ) ); Address address = staff.getAddress(); if( address == null ) { r.createCell( 5 ).setCellValue( "" ); } else { r.createCell( 5 ).setCellValue( String.format( "%s %n%s, %s %s", address.getLine1(), address.getCity(), address.getState(), address.getZip() ) ); } r.createCell( 6 ).setCellValue( staff.getPosition() ); } } } // Create a sheet for the failed match ups Sheet failSheet = wb.createSheet( "Failures" ); header = failSheet.createRow( 0 ); headers = new String[] { "Donor Name", "Donor Organization", "Reason" }; for( int i = 0; i < headers.length; i++ ) { header.createCell( i ).setCellValue( headers[i] ); } // Create and populate a row for each failed match up rownum = 0; for( Iterator< Recipient > it = failed.keySet().iterator(); it .hasNext(); ) { Donor donor = ( Donor ) it.next(); String reason = failed.get( donor ); Row r = failSheet.createRow( ++rownum ); r.createCell( 0 ).setCellValue( String.format( "%s %s", donor.getFirstName(), donor.getLastName() ) ); r.createCell( 1 ).setCellValue( donor.getOrg() ); r.createCell( 2 ).setCellValue( reason ); } try ( FileOutputStream fos = new FileOutputStream( xlsx ) ) { wb.write( fos ); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void getStudentInfo() { // Get the sheet that contains the group assignments int assignmentIndex = students.getSheetIndex( "Group Assignments" ); Sheet assignmentSheet = students.getSheetAt( assignmentIndex ); // Get the column indexes for the information we need int firstIndex = -1; int lastIndex = -1; int colorIndex = -1; int groupIndex = -1; Row header = assignmentSheet.getRow( 0 ); int numCells = header.getPhysicalNumberOfCells(); for( int i = 0; i < numCells; i++ ) { Cell c = header.getCell( i ); if( c.getCellType() != Cell.CELL_TYPE_STRING ) { continue; } String value = c.getStringCellValue(); if( value.matches( ".*First.*" ) ) { firstIndex = c.getColumnIndex(); } else if( value.matches( ".*Last.*" ) ) { lastIndex = c.getColumnIndex(); } else if( value.matches( ".*Group.*") ) { groupIndex = c.getColumnIndex(); } else if( value.matches( ".*Color.*") ) { colorIndex = c.getColumnIndex(); } if( firstIndex >= 0 && lastIndex >= 0 && groupIndex >= 0 && colorIndex >= 0 ) { break; } } int numRows = assignmentSheet.getPhysicalNumberOfRows(); for( int i = 1; i < numRows; i++ ) { Row r = assignmentSheet.getRow( i ); if( r == null ) { continue; } Cell fCell = r.getCell( firstIndex ); if( fCell == null ) { continue; } String first = ( fCell.getCellType() == Cell.CELL_TYPE_STRING || fCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? fCell.getStringCellValue() : ""; Cell lCell = r.getCell( lastIndex ); if( lCell == null ) { continue; } String last = ( lCell.getCellType() == Cell.CELL_TYPE_STRING || lCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? lCell.getStringCellValue() : ""; Cell sCell = r.getCell( colorIndex ); if( sCell == null ) { continue; } String section = ( sCell.getCellType() == Cell.CELL_TYPE_STRING || sCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? sCell.getStringCellValue() : ""; Cell gCell = r.getCell( groupIndex ); if( gCell == null ) { continue; } String group = ( gCell.getCellType() == Cell.CELL_TYPE_STRING || gCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? gCell.getStringCellValue() : ""; if( ( first == "" && last == "" ) || group.equalsIgnoreCase( "x" ) ) { continue; } Student s = new Student( first, last, section, group ); studentList.add( s ); } } /** * * @return */ private void getDonorInfo( Vector< Recipient > donorList ) { String sheetName = null; // The Staff are on a sheet called Staff for( int i = 0; i < donors.getNumberOfSheets(); i++ ) { if( donors.getSheetName( i ).matches( ".*Staff.*" ) ) { sheetName = donors.getSheetName( i ); break; } } readStaff( donors.getSheet( sheetName ), donorList ); // The sponsors and donors are on a sheet called Donations for( int i = 0; i < donors.getNumberOfSheets(); i++ ) { if( donors.getSheetName( i ).matches( ".*Donations.*" ) ) { sheetName = donors.getSheetName( i ); break; } } readDonations( donors.getSheet( sheetName ), donorList ); // The speakers, judges, panelists, etc are on a sheet called Speakers for( int i = 0; i < donors.getNumberOfSheets(); i++ ) { if( donors.getSheetName( i ).matches( ".*Speakers.*" ) ) { sheetName = donors.getSheetName( i ); break; } } readSpeakers( donors.getSheet( sheetName ), donorList ); } private void readDonations( Sheet donorSheet, Vector< Recipient > donorList ) { int firstIndex = -1; int lastIndex = -1; int orgIndex = -1; int typeIndex = -1; int infoIndex = -1; int streetIndex = -1; int cityIndex = -1; int stateIndex = -1; int zipIndex = -1; int beneTypeIndex = -1; int beneFirstIndex = -1; int beneLastIndex = -1; int countIndex = -1; int donorCount = 0; Row header = donorSheet.getRow( 0 ); int numCells = header.getPhysicalNumberOfCells(); for( int i = 0; i < numCells; i++ ) { Cell c = header.getCell( i ); if( c.getCellType() != Cell.CELL_TYPE_STRING ) { continue; } String value = c.getStringCellValue(); if( value.matches( ".*Donor First.*" ) ) { firstIndex = c.getColumnIndex(); } else if( value.matches( ".*Donor Last.*" ) ) { lastIndex = c.getColumnIndex(); } else if( value.matches( ".*Donor Organization.*") ) { orgIndex = c.getColumnIndex(); } else if( value.matches( ".*Donor Type.*") ) { typeIndex = c.getColumnIndex(); } else if( value.matches( ".*Donation Info.*") ) { infoIndex = c.getColumnIndex(); } else if( value.matches( ".*Street.*" ) ) { streetIndex = c.getColumnIndex(); } else if( value.matches( ".*City.*") ) { cityIndex = c.getColumnIndex(); } else if( value.matches( ".*State.*") ) { stateIndex = c.getColumnIndex(); } else if( value.matches( ".*Zip.*") ) { zipIndex = c.getColumnIndex(); } else if( value.matches( ".*Beneficiary First.*") ) { beneFirstIndex = c.getColumnIndex(); } else if( value.matches( ".*Beneficiary Last.*") ) { beneLastIndex = c.getColumnIndex(); } else if( value.matches( ".*Beneficiary Type.*") ) { beneTypeIndex = c.getColumnIndex(); } else if( value.matches( ".*Letter Count.*") ) { countIndex = c.getColumnIndex(); } if( firstIndex >= 0 && lastIndex >= 0 && orgIndex >= 0 && typeIndex >= 0 && infoIndex >= 0) { if( streetIndex >= 0 && cityIndex >= 0 && stateIndex >= 0 && zipIndex >= 0 ) { if( beneTypeIndex >= 0 && beneFirstIndex >= 0 && beneLastIndex >=0 ) { if( countIndex >= 0 ) { break; } } } } } int numRows = donorSheet.getPhysicalNumberOfRows(); for( int i = 1; i < numRows; i++ ) { Row r = donorSheet.getRow( i ); if( r == null ) { continue; } // Get the address of the donor Address address = getAddress( r, streetIndex, cityIndex, stateIndex, zipIndex ); // Pull the other donor information String first = ""; Cell firstCell = r.getCell( firstIndex ); if( firstCell != null ) { first = firstCell.getStringCellValue(); } String last = ""; Cell lastCell = r.getCell( lastIndex ); if( lastCell != null ) { last = lastCell.getStringCellValue(); } String org = ""; Cell orgCell = r.getCell( orgIndex ); if( orgCell != null ) { org = orgCell.getStringCellValue(); } String type = ""; Cell typeCell = r.getCell( typeIndex ); if( typeCell != null ) { type = typeCell.getStringCellValue(); } String info = ""; Cell infoCell = r.getCell( infoIndex ); if( infoCell != null ) { info = infoCell.getStringCellValue(); } int count = 1; Cell countCell = r.getCell( countIndex ); if( countCell != null ) { count = (int)countCell.getNumericCellValue(); } if( first == "" && last == "" && org == "" ) { continue; } Donor donor = new Donor( first, last, org, type, "", info, address ); donorCount++; // If this donor sponsored a student or j-staff, add it String beneType = ""; Cell beneTypeCell = r.getCell( beneTypeIndex ); if( beneTypeCell != null ) { beneType = beneTypeCell.getStringCellValue(); } if( beneType.matches( "Ambassador" ) || beneType.matches( "Junior Staff" ) ) { String beneFirst = ""; Cell beneFirstCell = r.getCell( beneFirstIndex ); if( beneFirstCell != null ) { beneFirst = beneFirstCell.getStringCellValue(); } String beneLast = ""; Cell beneLastCell = r.getCell( beneLastIndex ); if( beneLastCell != null ) { beneLast = beneLastCell.getStringCellValue(); } if( beneFirst == "" || beneLast == "" ) { failed.put(donor, "Student information missing"); continue; } addMatch( beneFirst, beneLast, donor ); continue; } for( int j = 0; j < count; j++ ) { donorList.add(donor); } } System.out.println(donorCount); } private void readSpeakers( Sheet donorSheet, Vector< Recipient > donorList ) { int titleIndex = -1; int firstIndex = -1; int lastIndex = -1; int roleIndex = -1; int streetIndex = -1; int cityIndex = -1; int stateIndex = -1; int zipIndex = -1; int priorityIndex = -1; Row header = donorSheet.getRow( 0 ); int numCells = header.getPhysicalNumberOfCells(); for( int i = 0; i < numCells; i++ ) { Cell c = header.getCell( i ); if( c.getCellType() != Cell.CELL_TYPE_STRING ) { continue; } String value = c.getStringCellValue(); if( value.matches( ".*Title.*" ) ) { titleIndex = c.getColumnIndex(); } else if( value.matches( ".*First.*" ) ) { firstIndex = c.getColumnIndex(); } else if( value.matches( ".*Last.*" ) ) { lastIndex = c.getColumnIndex(); } else if( value.matches( ".*Role.*") ) { roleIndex = c.getColumnIndex(); } else if( value.matches( ".*Street.*" ) ) { streetIndex = c.getColumnIndex(); } else if( value.matches( ".*City.*") ) { cityIndex = c.getColumnIndex(); } else if( value.matches( ".*State.*") ) { stateIndex = c.getColumnIndex(); } else if( value.matches( ".*Zip.*") ) { zipIndex = c.getColumnIndex(); } else if( value.matches( ".*Letter Count.*") ) { priorityIndex = c.getColumnIndex(); } if( titleIndex >= 0 && firstIndex >= 0 && lastIndex >= 0 && roleIndex >= 0) { if( streetIndex >= 0 && cityIndex >= 0 && stateIndex >= 0 && zipIndex >= 0 ) { if( priorityIndex >= 0 ) { break; } } } } int numRows = donorSheet.getPhysicalNumberOfRows(); for( int i = 1; i < numRows; i++ ) { Row r = donorSheet.getRow( i ); if( r == null ) { continue; } // Get the address of the donor Address address = getAddress( r, streetIndex, cityIndex, stateIndex, zipIndex ); // Pull the other donor information String title = ""; Cell titleCell = r.getCell( titleIndex ); if( titleCell != null ) { title = titleCell.getStringCellValue(); } String first = ""; Cell firstCell = r.getCell( firstIndex ); if( firstCell != null ) { first = firstCell.getStringCellValue(); } String last = ""; Cell lastCell = r.getCell( lastIndex ); if( lastCell != null ) { last = lastCell.getStringCellValue(); } String role = ""; Cell roleCell = r.getCell( roleIndex ); if( roleCell != null ) { role = roleCell.getStringCellValue(); } int count = 1; Cell countCell = r.getCell( priorityIndex ); if( countCell != null ) { count = (int)countCell.getNumericCellValue(); } if( first == "" && last == "" ) { continue; } Speaker speaker = new Speaker( title, first, last, role, address ); for( int j = 0; j < count; j++ ) { donorList.add(speaker); } } } private void readStaff( Sheet staffSheet, Vector< Recipient > donorList ) { // Get the column indexes for the information we need int firstIndex = -1; int lastIndex = -1; int colorIndex = -1; int groupIndex = -1; int roleIndex = -1; int streetIndex = -1; int cityIndex = -1; int stateIndex = -1; int zipIndex = -1; int priorityIndex = -1; Row header = staffSheet.getRow( 0 ); int numCells = header.getPhysicalNumberOfCells(); for( int i = 0; i < numCells; i++ ) { Cell c = header.getCell( i ); if( c.getCellType() != Cell.CELL_TYPE_STRING ) { continue; } String value = c.getStringCellValue(); if( value.matches( ".*First.*" ) ) { firstIndex = c.getColumnIndex(); } else if( value.matches( ".*Last.*" ) ) { lastIndex = c.getColumnIndex(); } else if( value.matches( ".*Group.*") ) { groupIndex = c.getColumnIndex(); } else if( value.matches( ".*Color.*") ) { colorIndex = c.getColumnIndex(); } else if( value.matches( ".*Role.*") ) { roleIndex = c.getColumnIndex(); } else if( value.matches( ".*Street.*" ) ) { streetIndex = c.getColumnIndex(); } else if( value.matches( ".*City.*") ) { cityIndex = c.getColumnIndex(); } else if( value.matches( ".*State.*") ) { stateIndex = c.getColumnIndex(); } else if( value.matches( ".*Zip.*") ) { zipIndex = c.getColumnIndex(); } else if( value.matches( ".*Letter Count.*") ) { priorityIndex = c.getColumnIndex(); } if( firstIndex >= 0 && lastIndex >= 0 && groupIndex >= 0 && colorIndex >= 0 && roleIndex >= 0 ) { if( streetIndex >= 0 && cityIndex >= 0 && stateIndex >= 0 && zipIndex >= 0 ) { if( priorityIndex >= 0 ) { break; } } } } int numRows = staffSheet.getPhysicalNumberOfRows(); for( int i = 1; i < numRows; i++ ) { Row r = staffSheet.getRow( i ); if( r == null ) { continue; } Cell fCell = r.getCell( firstIndex ); if( fCell == null ) { continue; } String first = ( fCell.getCellType() == Cell.CELL_TYPE_STRING || fCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? fCell.getStringCellValue() : ""; Cell lCell = r.getCell( lastIndex ); if( lCell == null ) { continue; } String last = ( lCell.getCellType() == Cell.CELL_TYPE_STRING || lCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? lCell.getStringCellValue() : ""; Cell sCell = r.getCell( colorIndex ); if( sCell == null ) { continue; } String section = ( sCell.getCellType() == Cell.CELL_TYPE_STRING || sCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? sCell.getStringCellValue() : ""; Cell gCell = r.getCell( groupIndex ); if( gCell == null ) { continue; } String group = ( gCell.getCellType() == Cell.CELL_TYPE_STRING || gCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? gCell.getStringCellValue() : ""; Cell rCell = r.getCell( roleIndex ); if( rCell == null ) { continue; } String role = ( rCell.getCellType() == Cell.CELL_TYPE_STRING || rCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? rCell.getStringCellValue() : ""; Cell pCell = r.getCell( priorityIndex ); if( pCell == null ) { continue; } int priority = ( pCell.getCellType() == Cell.CELL_TYPE_NUMERIC || pCell.getCellType() == Cell.CELL_TYPE_FORMULA ) ? (int) pCell.getNumericCellValue() : 1; if( first == "" && last == "" ) { continue; } Address address = getAddress( r, streetIndex, cityIndex, stateIndex, zipIndex ); Staff s; if( role.matches( "Section Leader") ) { s = new Staff( first, last, String.format( "%s %s", section, role ), address ); } else if( role.matches( "Facilitator" ) ) { s = new Staff( first, last, String.format( "%s %s", group, role ), address ); } else if( role.matches( "J-Staff") || role.matches( "Junior Staff") || role.matches( "J Staff") ) { studentList.add( new JStaff( first, last, section, group ) ); s = new Staff( first, last, String.format( "%s %s", group, role ), address ); } else { s = new Staff( first, last, role, address ); } for( int j = 0; j < priority; j++ ) { donorList.add(s); } } } /** * * @param row * @param streetIndex * @param cityIndex * @param stateIndex * @param zipIndex * @return */ private Address getAddress( Row row, int streetIndex, int cityIndex, int stateIndex, int zipIndex ) { Cell streetCell = row.getCell( streetIndex ); if( streetCell == null ) { return null; } String street = streetCell.getCellType() == Cell.CELL_TYPE_STRING || streetCell.getCellType() == Cell.CELL_TYPE_FORMULA ? streetCell.getStringCellValue() : ""; Cell cityCell = row.getCell( cityIndex ); if( cityCell == null ) { return null; } String city = cityCell.getCellType() == Cell.CELL_TYPE_STRING || cityCell.getCellType() == Cell.CELL_TYPE_FORMULA ? cityCell.getStringCellValue() : ""; Cell stateCell = row.getCell( stateIndex ); if( stateCell == null ) { return null; } String state = stateCell.getCellType() == Cell.CELL_TYPE_STRING || stateCell.getCellType() == Cell.CELL_TYPE_FORMULA ? stateCell.getStringCellValue() : ""; ZipCode zip = null; Cell zipCell = row.getCell( zipIndex ); if( zipCell == null ) { return null; } if( zipCell.getCellType() == Cell.CELL_TYPE_STRING || zipCell.getCellType() == Cell.CELL_TYPE_FORMULA ) { zip = new ZipCode(zipCell.getStringCellValue()); } else if( zipCell.getCellType() == Cell.CELL_TYPE_NUMERIC ) { zip = new ZipCode((int)zipCell.getNumericCellValue()); } return new Address( street, city, state, zip ); } /** * * @param firstName * @param lastName */ private void addMatch( String firstName, String lastName, Recipient r ) { for( Iterator<Writer> it = studentList.iterator(); it.hasNext(); ) { Student s = ( Student ) it.next(); if( s.getFirstName().matches( firstName ) && s.getLastName().matches( lastName ) ) { s.addRecipient( r ); return; } } failed.put( r, String.format( "Couldn't find %s %s in the group matchings", firstName, lastName ) ); } /** * @param args */ public static void main(String[] args) { if( args.length < 6 ) { System.err.println( "Not enough arguments provided!"); System.err.println( "Usage: java -jar thankyou.jar --donorFile <donor.xls> --staffFile <staff.xls> --studentFile <student.xls>"); System.exit( -1 ); } String donorFile = null; String staffFile = null; String studentFile = null; for( int i = 0; i < 6; i += 2 ) { if( args[i].matches("--staffFile") ) { staffFile = args[i+1]; continue; } if( args[i].matches("--studentFile") ) { studentFile = args[i+1]; continue; } if( args[i].matches("--donorFile") ) { donorFile = args[i+1]; continue; } } if( staffFile == null || studentFile == null || donorFile == null ) { System.err.println( "Required argument missing!"); System.err.println( "Usage: java -jar thankyou.jar --donorFile <donor.xls> --staffFile <staff.xls> --studentFile <student.xls>"); System.exit( -1 ); } ThankYouMatcher tym = new ThankYouMatcher(); tym.loadFiles(donorFile, staffFile, studentFile); tym.createMatchUps(); } }
package org.lantern; import java.net.InetSocketAddress; import java.security.NoSuchAlgorithmException; import java.util.concurrent.Executors; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.ssl.SslHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handler that relays traffic to another proxy. */ public class GaeProxyRelayHandler extends SimpleChannelUpstreamHandler { private final Logger log = LoggerFactory.getLogger(getClass()); private volatile long messagesReceived = 0L; private final InetSocketAddress proxyAddress; private Channel outboundChannel; private Channel inboundChannel; private final ProxyStatusListener proxyStatusListener; private final ClientSocketChannelFactory clientSocketChannelFactory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); /** * Creates a new relayer to a proxy. * * @param proxyAddress The address of the proxy. * @param clientSocketChannelFactory The factory for creating socket * channels to the proxy. * @param proxyStatusListener The class to notify of changes in the proxy * status. */ public GaeProxyRelayHandler(final InetSocketAddress proxyAddress, final ProxyStatusListener proxyStatusListener) { this.proxyAddress = proxyAddress; this.proxyStatusListener = proxyStatusListener; } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent me) { messagesReceived++; log.info("Received {} total messages", messagesReceived); final Object msg = me.getMessage(); log.info("Msg is "+msg); final HttpRequest request = (HttpRequest)msg; final String uri = request.getUri(); final String proxyHost = "freelantern.appspot.com"; final String proxyBaseUri = "https://" + proxyHost; if (!uri.startsWith(proxyBaseUri)) { request.setHeader("Host", proxyHost); final String scheme = uri.substring(0, uri.indexOf(':')); final String rest = uri.substring(scheme.length() + 3); final String proxyUri = proxyBaseUri + "/" + scheme + "/" + rest; log.debug("proxyUri: " + proxyUri); request.setUri(proxyUri); } else { log.info("NOT MODIFYING URI -- ALREADY HAS FREELANTERN"); } this.outboundChannel.write(request); } @Override public void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e) { if (this.outboundChannel != null) { log.error("Outbound channel already assigned?"); } this.inboundChannel = e.getChannel(); inboundChannel.setReadable(false); // Start the connection attempt. final ClientBootstrap cb = new ClientBootstrap(this.clientSocketChannelFactory); final ChannelPipeline pipeline = cb.getPipeline(); try { log.info("Creating SSL engine"); final SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); pipeline.addLast("ssl", new SslHandler(engine)); } catch (final NoSuchAlgorithmException nsae) { log.error("Could not create default SSL context"); } pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("handler", new OutboundHandler(e.getChannel())); final ChannelFuture cf = cb.connect(this.proxyAddress); this.outboundChannel = cf.getChannel(); cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection attempt succeeded: // Begin to accept incoming traffic. inboundChannel.setReadable(true); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); proxyStatusListener.onCouldNotConnect(proxyAddress); } } }); } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) { log.info("Got inbound channel closed. Closing outbound."); LanternUtils.closeOnFlush(this.outboundChannel); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { log.error("Caught exception on INBOUND channel", e.getCause()); LanternUtils.closeOnFlush(this.inboundChannel); } private static class OutboundHandler extends SimpleChannelUpstreamHandler { private final Logger log = LoggerFactory.getLogger(getClass()); private final Channel inboundChannel; OutboundHandler(final Channel inboundChannel) { this.inboundChannel = inboundChannel; } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final ChannelBuffer msg = (ChannelBuffer) e.getMessage(); inboundChannel.write(msg); } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { LanternUtils.closeOnFlush(inboundChannel); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { log.error("Caught exception on OUTBOUND channel", e.getCause()); LanternUtils.closeOnFlush(e.getChannel()); } } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.AbstractIOUtils; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan * */ public class MetaCreator { private static AnnotationDB annotationDB; // Cached temporal resources for clean after deployment private TmpResources tmpResources; private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, AbstractIOUtils> aggregateds = new HashMap<String, AbstractIOUtils>(); private Map<URL, ArchiveData> archivesURLs; private Map<String, URL> classOwnersURL; private Map<URL, DeployData> realURL; private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { LOCK.lock(); try { if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } } finally { LOCK.unlock(); } } return creator; } private void configure(URL[] archives) { if (configuration == null && CollectionUtils.available(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationDB getAnnotationDB() { return annotationDB; } public Map<String, AbstractIOUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { AbstractIOUtils ioUtils = AbstractIOUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } AbstractIOUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = AbstractIOUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.available(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (CollectionUtils.available(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { scannerLock.lock(); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new HashMap<URL, ArchiveData>(); if (CollectionUtils.available(archives)) { realURL = new HashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationDB = new AnnotationDB(); annotationDB.setScanFieldAnnotations(Boolean.FALSE); annotationDB.setScanParameterAnnotations(Boolean.FALSE); annotationDB.setScanMethodAnnotations(Boolean.FALSE); annotationDB.scanArchives(fullArchives); Set<String> beanNames = annotationDB.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationDB.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (CollectionUtils.available(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); scannerLock.unlock(); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (CollectionUtils.notAvailable(paths) && CollectionUtils.available(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (CollectionUtils.available(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = scannerLock.tryLock(); while (ObjectUtils.notTrue(locked)) { locked = scannerLock.tryLock(); } if (locked) { try { if (CollectionUtils.available(realURL)) { realURL.clear(); realURL = null; } if (CollectionUtils.available(aggregateds)) { aggregateds.clear(); } if (ObjectUtils.available(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (ObjectUtils.available(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { scannerLock.unlock(); } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author levan * */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (ObjectUtils.available(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationFinder; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan Tsinadze * @since 0.0.45-SNAPSHOT */ public class MetaCreator { // Annotation scanner implementation for scanning at startup private AnnotationFinder annotationFinder; // Cached temporal resources for clean after deployment private TmpResources tmpResources; // Checks if needed await for EJB deployments private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, ArchiveUtils> aggregateds = new WeakHashMap<String, ArchiveUtils>(); // Caches archive by URL for deployment private Map<URL, ArchiveData> archivesURLs; // Caches class file URLs by class names private Map<String, URL> classOwnersURL; // Caches deployment data meta information for file URL instance private Map<URL, DeployData> realURL; // Class loader for each deployment private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } /** * Initializes {@link MetaCreator} instance if it is not cached yet * * @return {@link MetaCreator} */ private static MetaCreator initCreator() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } return creator; } /** * Gets cached {@link MetaCreator} instance if such not exists creates new * * @return {@link MetaCreator} */ private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { // Locks to provide singularity of MetaCreator instance ObjectUtils.lock(LOCK); try { creator = initCreator(); } finally { ObjectUtils.unlock(LOCK); } } return creator; } /** * Gets {@link Configuration} instance for passed {@link URL} array of * archives * * @param archives */ private void configure(URL[] archives) { if (configuration == null && CollectionUtils.valid(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationFinder getAnnotationFinder() { return annotationFinder; } public Map<String, ArchiveUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { ArchiveUtils ioUtils = ArchiveUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } ArchiveUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = ArchiveUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.valid(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (CollectionUtils.valid(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { ObjectUtils.lock(scannerLock); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new WeakHashMap<URL, ArchiveData>(); if (CollectionUtils.valid(archives)) { realURL = new WeakHashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationFinder = new AnnotationFinder(); annotationFinder.setScanFieldAnnotations(Boolean.FALSE); annotationFinder.setScanParameterAnnotations(Boolean.FALSE); annotationFinder.setScanMethodAnnotations(Boolean.FALSE); annotationFinder.scanArchives(fullArchives); Set<String> beanNames = annotationFinder.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationFinder.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (CollectionUtils.valid(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); ObjectUtils.unlock(scannerLock); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (CollectionUtils.invalid(paths) && CollectionUtils.valid(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (CollectionUtils.valid(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked)) { // Tries to lock for avoid concurrent modification locked = ObjectUtils.tryLock(scannerLock); if (locked) { try { if (CollectionUtils.valid(realURL)) { realURL.clear(); realURL = null; } if (CollectionUtils.valid(aggregateds)) { aggregateds.clear(); } if (CollectionUtils.valid(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (CollectionUtils.valid(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { ObjectUtils.unlock(scannerLock); } } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author Levan Tsinadze * @since 0.0.45-SNAPSHOT */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } /** * Configures persistence for cached properties * * @return {@link Map}<code><Object, Object></code> */ private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (CollectionUtils.valid(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * To add remote control check * * @param remoteControl * @return {@link Builder} */ public Builder setRemoteControl(boolean remoteControl) { Configuration.setRemoteControl(remoteControl); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan * @since 0.0.45-SNAPSHOT */ public class MetaCreator { // Annotation scanner implementation for scanning at atartup private static AnnotationDB annotationDB; // Cached temporal resources for clean after deployment private TmpResources tmpResources; private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, ArchiveUtils> aggregateds = new WeakHashMap<String, ArchiveUtils>(); private Map<URL, ArchiveData> archivesURLs; private Map<String, URL> classOwnersURL; private Map<URL, DeployData> realURL; private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { // Locks to provide singularity of MetaCreator instance ObjectUtils.lock(LOCK); try { if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } } finally { ObjectUtils.unlock(LOCK); } } return creator; } private void configure(URL[] archives) { if (configuration == null && CollectionUtils.valid(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationDB getAnnotationDB() { return annotationDB; } public Map<String, ArchiveUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { ArchiveUtils ioUtils = ArchiveUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } ArchiveUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = ArchiveUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.valid(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (CollectionUtils.valid(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { ObjectUtils.lock(scannerLock); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new WeakHashMap<URL, ArchiveData>(); if (CollectionUtils.valid(archives)) { realURL = new WeakHashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationDB = new AnnotationDB(); annotationDB.setScanFieldAnnotations(Boolean.FALSE); annotationDB.setScanParameterAnnotations(Boolean.FALSE); annotationDB.setScanMethodAnnotations(Boolean.FALSE); annotationDB.scanArchives(fullArchives); Set<String> beanNames = annotationDB.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationDB.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (CollectionUtils.valid(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); ObjectUtils.unlock(scannerLock); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (CollectionUtils.invalid(paths) && CollectionUtils.valid(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (CollectionUtils.valid(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked)) { // Tries to lock for avoid concurrent modification locked = ObjectUtils.tryLock(scannerLock); if (locked) { try { if (CollectionUtils.valid(realURL)) { realURL.clear(); realURL = null; } if (CollectionUtils.valid(aggregateds)) { aggregateds.clear(); } if (CollectionUtils.valid(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (CollectionUtils.valid(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { ObjectUtils.unlock(scannerLock); } } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author levan * */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (CollectionUtils.valid(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * To add remote control check * @param remoteControl * @return {@link Builder} */ public Builder setRemoteControl(boolean remoteControl) { Configuration.setRemoteControl(remoteControl); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }
package org.neo4j.examples.socnet; import org.neo4j.graphalgo.GraphAlgoFactory; import org.neo4j.graphalgo.PathFinder; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.helpers.collection.IterableWrapper; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; public class Person { static final String NAME = "person_name"; static final RelationshipType FRIEND = DynamicRelationshipType.withName( "FRIEND" ); private final Node underlyingNode; Person( Node personNode ) { this.underlyingNode = personNode; } protected Node getUnderlyingNode() { return underlyingNode; } public String getName() { return (String) underlyingNode.getProperty( NAME ); } @Override public int hashCode() { return underlyingNode.hashCode(); } @Override public boolean equals( Object o ) { if ( o instanceof Person ) { return underlyingNode.equals( ( (Person) o ).getUnderlyingNode() ); } return false; } @Override public String toString() { return "Person[" + getName() + "]"; } public void addFriend( Person otherPerson ) { Transaction tx = underlyingNode.getGraphDatabase().beginTx(); try { if ( this.equals( otherPerson ) ) { // ignore return; } Relationship friendRel = getFriendRelationshipTo( otherPerson ); if ( friendRel == null ) { underlyingNode.createRelationshipTo( otherPerson.getUnderlyingNode(), FRIEND ); } tx.success(); } finally { tx.finish(); } } public Iterable<Person> getFriends() { return new IterableWrapper<Person, Relationship>( underlyingNode.getRelationships( FRIEND ) ) { @Override protected Person underlyingObjectToObject( Relationship friendRel ) { return new Person( friendRel.getOtherNode( underlyingNode ) ); } }; } public void removeFriend( Person otherPerson ) { Transaction tx = underlyingNode.getGraphDatabase().beginTx(); try { if ( this.equals( otherPerson ) ) { // ignore return; } Relationship friendRel = getFriendRelationshipTo( otherPerson ); if ( friendRel != null ) { friendRel.delete(); } tx.success(); } finally { tx.finish(); } } private Relationship getFriendRelationshipTo( Person otherPerson ) { Node otherNode = otherPerson.getUnderlyingNode(); for ( Relationship rel : underlyingNode.getRelationships( FRIEND ) ) { if ( rel.getOtherNode( underlyingNode ).equals( otherNode ) ) { return rel; } } return null; } public Iterable<Person> getFriendsOfFriends() { // return all my friends and their friends using new traversal API TraversalDescription travDesc = Traversal.description().depthFirst().relationships( FRIEND ).uniqueness( Uniqueness.NODE_GLOBAL ).prune( Traversal.pruneAfterDepth( 2 ) ).filter( Traversal.returnAllButStartNode() ); /* // old traverser api would be something like: Traverser trav = underlyingNode.traverse( Order.DEPTH_FIRST, new StopEvaluator() { public boolean isStopNode( TraversalPosition currentPos ) { return currentPos.depth() == 2; } }, ReturnableEvaluator.ALL_BUT_START_NODE, FRIEND, Direction.BOTH ); */ return new IterableWrapper<Person, Path>( travDesc.traverse( underlyingNode ) ) { @Override protected Person underlyingObjectToObject( Path path ) { return new Person( path.endNode() ); } }; } public Iterable<Person> getPersonsFromMeTo( Person otherPerson, int maxDepth ) { // use graph algo to calculate a shortest path PathFinder<Path> finder = GraphAlgoFactory.shortestPath( Traversal.expanderForTypes( FRIEND, Direction.BOTH ), maxDepth ); Path path = finder.findSinglePath( underlyingNode, otherPerson.getUnderlyingNode() ); return new IterableWrapper<Person,Node>( path.nodes() ) { @Override protected Person underlyingObjectToObject( Node node ) { return new Person( node ); } }; } }
package org.nutz.weixin.bean; public enum WxEventType { subscribe, unsubscribe, SCAN, LOCATION, /** * * * <pre> * clickevent * keykey * </pre> */ CLICK, /** * URL * * <pre> * viewURL * * </pre> */ VIEW, TEMPLATESENDJOBFINISH, // , iPhone5.4.1+, Android5.4+ /** * * * <pre> * * URLURL * </pre> */ scancode_push, scancode_waitmsg, /** * * * <pre> * * * </pre> */ pic_sysphoto, pic_photo_or_album, /** * * * <pre> * * * </pre> */ pic_weixin, /** * * * <pre> * * * </pre> */ location_select, MASSSENDJOBFINISH, card_pass_check, card_pass_not_check, user_get_card,user_del_card,user_consume_card, user_pay_from_pay_cell,user_view_card, user_enter_session_from_card,update_member_card, card_sku_remind,card_pay_order, }
package org.testng.internal; import org.testng.CommandLineArgs; import org.testng.collections.Lists; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Pattern; public class PackageUtils { private static String[] s_testClassPaths; /** * * @param packageName * @return The list of all the classes inside this package * @throws IOException */ public static String[] findClassesInPackage(String packageName, List<String> included, List<String> excluded) throws IOException { String packageOnly = packageName; boolean recursive = false; if (packageName.endsWith(".*")) { packageOnly = packageName.substring(0, packageName.lastIndexOf(".*")); recursive = true; } List<String> vResult = Lists.newArrayList(); String packageDirName = packageOnly.replace('.', '/'); Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if(!matchTestClasspath(url, packageDirName, recursive)) { continue; } if ("file".equals(protocol)) { findClassesInDirPackage(packageOnly, included, excluded, URLDecoder.decode(url.getFile(), "UTF-8"), recursive, vResult); } else if ("jar".equals(protocol)) { JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile(); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); if (idx != -1) { packageName = name.substring(0, idx).replace('/', '.'); } Utils.log("PackageUtils", 4, "Package name is " + packageName); if ((idx != -1) || recursive) { //it's not inside a deeper dir if (name.endsWith(".class") && !entry.isDirectory()) { String className = name.substring(packageName.length() + 1, name.length() - 6); Utils.log("PackageUtils", 4, "Found class " + className + ", seeing it if it's included or excluded"); includeOrExcludeClass(packageName, className, included, excluded, vResult); } } } } } } String[] result = vResult.toArray(new String[vResult.size()]); return result; } private static String[] getTestClasspath() { if (null != s_testClassPaths) { return s_testClassPaths; } String testClasspath = System.getProperty(CommandLineArgs.TEST_CLASSPATH); if (null == testClasspath) { return null; } String[] classpathFragments= Utils.split(testClasspath, File.pathSeparator); s_testClassPaths= new String[classpathFragments.length]; for(int i= 0; i < classpathFragments.length; i++) { String path= null; if(classpathFragments[i].toLowerCase().endsWith(".jar") || classpathFragments[i].toLowerCase().endsWith(".zip")) { path= classpathFragments[i] + "!/"; } else { if(classpathFragments[i].endsWith(File.separator)) { path= classpathFragments[i]; } else { path= classpathFragments[i] + "/"; } } s_testClassPaths[i]= path.replace('\\', '/'); } return s_testClassPaths; } /** * @param url * @return */ private static boolean matchTestClasspath(URL url, String lastFragment, boolean recursive) { String[] classpathFragments= getTestClasspath(); if(null == classpathFragments) { return true; } String protocol = url.getProtocol(); String fileName= null; try { fileName= URLDecoder.decode(url.getFile(), "UTF-8"); } catch(UnsupportedEncodingException ueex) { ; // ignore. should never happen } for(String classpathFrag: classpathFragments) { String path= classpathFrag + lastFragment; int idx= fileName.indexOf(path); if((idx == -1) || (idx > 0 && fileName.charAt(idx-1) != '/')) { continue; } if(fileName.endsWith(classpathFrag + lastFragment) || (recursive && fileName.charAt(idx + path.length()) == '/')) { return true; } } return false; } private static void findClassesInDirPackage(String packageName, List<String> included, List<String> excluded, String packagePath, final boolean recursive, List<String> classes) { File dir = new File(packagePath); if (!dir.exists() || !dir.isDirectory()) { return; } File[] dirfiles = dir.listFiles(new FileFilter() { @Override public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")) || (file.getName().endsWith(".groovy")); } }); Utils.log("PackageUtils", 4, "Looking for test classes in the directory: " + dir); for (File file : dirfiles) { if (file.isDirectory()) { findClassesInDirPackage(makeFullClassName(packageName, file.getName()), included, excluded, file.getAbsolutePath(), recursive, classes); } else { String className = file.getName().substring(0, file.getName().lastIndexOf(".")); Utils.log("PackageUtils", 4, "Found class " + className + ", seeing it if it's included or excluded"); includeOrExcludeClass(packageName, className, included, excluded, classes); } } } private static String makeFullClassName(String pkg, String cls) { return pkg.length() > 0 ? pkg + "." + cls : cls; } private static void includeOrExcludeClass(String packageName, String className, List<String> included, List<String> excluded, List<String> classes) { if (isIncluded(className, included, excluded)) { Utils.log("PackageUtils", 4, "... Including class " + className); classes.add(makeFullClassName(packageName, className)); } else { Utils.log("PackageUtils", 4, "... Excluding class " + className); } } /** * @return true if name should be included. */ private static boolean isIncluded(String name, List<String> included, List<String> excluded) { boolean result = false; // If no includes nor excludes were specified, return true. if (included.size() == 0 && excluded.size() == 0) { result = true; } else { boolean isIncluded = PackageUtils.find(name, included); boolean isExcluded = PackageUtils.find(name, excluded); if (isIncluded && !isExcluded) { result = true; } else if (isExcluded) { result = false; } else { result = included.size() == 0; } } return result; } private static boolean find(String name, List<String> list) { for (String regexpStr : list) { if (Pattern.matches(regexpStr, name)) return true; } return false; } }
package org.trancecode.collection; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Maps; import java.util.Map; import java.util.Map.Entry; import org.trancecode.lang.TcObjects; /** * Utility methods related to {@link Map}. * * @author Herve Quiroz */ public final class TcMaps { private TcMaps() { // No instantiation } public static <K, V> Map<K, V> newSmallWriteOnceMap() { // TODO return Maps.newLinkedHashMap(); } public static <K, V> Map<K, V> merge(final Map<K, V> map1, final Map<? extends K, ? extends V> map2) { final Builder<K, V> builder = ImmutableMap.builder(); return builder.putAll(map1).putAll(map2).build(); } public static <K, V> Map<K, V> copyAndPut(final Map<K, V> map, final K key, final V value) { Preconditions.checkNotNull(map); Preconditions.checkNotNull(key); if (map instanceof ImmutableMap && TcObjects.equals(map.get(key), value)) { return map; } final Builder<K, V> builder = ImmutableMap.builder(); return builder.putAll(map).put(key, value).build(); } public static <K, V> V get(final Map<K, V> map, final K key, final V defaultValue) { if (map.containsKey(key)) { return map.get(key); } return defaultValue; } public static <K, V> Map<K, V> fromEntries(final Iterable<Entry<K, V>> entries) { final Function<Entry<K, V>, K> keyFunction = MapFunctions.getKey(); final Function<Entry<K, V>, V> valueFunction = MapFunctions.getValue(); final Map<K, Entry<K, V>> intermediate = Maps.uniqueIndex(entries, keyFunction); return Maps.transformValues(intermediate, valueFunction); } }
package jolie; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import jolie.lang.Constants; import jolie.net.SessionMessage; import jolie.process.Process; import jolie.process.TransformationReason; import jolie.runtime.ExitingException; import jolie.runtime.FaultException; import jolie.runtime.InputOperation; import jolie.runtime.Value; import jolie.runtime.VariablePath; import jolie.runtime.VariablePathBuilder; import jolie.runtime.correlation.CorrelationSet; import jolie.util.Pair; /** * An ExecutionThread representing a session, equipped * with a dedicated state and message queue. * @author Fabrizio Montesi */ public class SessionThread extends ExecutionThread { private class SessionMessageFuture implements Future< SessionMessage > { private final Lock lock; private final Condition condition; private SessionMessage sessionMessage = null; private boolean isDone = false; private boolean isCancelled = false; public SessionMessageFuture() { lock = new ReentrantLock(); condition = lock.newCondition(); } public boolean cancel( boolean mayInterruptIfRunning ) { lock.lock(); try { if ( !isDone ) { this.sessionMessage = null; isDone = true; isCancelled = true; condition.signalAll(); } } finally { lock.unlock(); } return true; } public SessionMessage get( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException { try { lock.lock(); if ( !isDone ) { if ( !condition.await( timeout, unit ) ) { throw new TimeoutException(); } } } finally { lock.unlock(); } return sessionMessage; } public SessionMessage get() throws InterruptedException { try { lock.lock(); if ( !isDone ) { condition.await(); } } finally { lock.unlock(); } return sessionMessage; } public boolean isCancelled() { return isCancelled; } public boolean isDone() { return isDone; } protected void setResult( SessionMessage sessionMessage ) { lock.lock(); try { if ( !isDone ) { this.sessionMessage = sessionMessage; isDone = true; condition.signalAll(); } } finally { lock.unlock(); } } } private class SessionMessageNDFuture extends SessionMessageFuture { private final String[] operationNames; public SessionMessageNDFuture( String[] operationNames ) { super(); this.operationNames = operationNames; } @Override protected void setResult( SessionMessage sessionMessage ) { for( String operationName : operationNames ) { if ( operationName.equals( sessionMessage.message().operationName() ) == false ) { Deque< SessionMessageFuture > waitersList = messageWaiters.get( operationName ); if ( waitersList != null ) { waitersList.remove( this ); } } } super.setResult( sessionMessage ); } } private final jolie.State state; private final List< SessionListener > listeners = new LinkedList< SessionListener >(); protected final Map< CorrelationSet, Deque< SessionMessage > > messageQueues = new HashMap< CorrelationSet, Deque< SessionMessage > >(); protected final Deque< SessionMessage > uncorrelatedMessageQueue = new LinkedList< SessionMessage >(); private final Map< String, Deque< SessionMessageFuture > > messageWaiters = new HashMap< String, Deque< SessionMessageFuture > >(); private final static VariablePath typeMismatchPath; private final static VariablePath ioExceptionPath; static { typeMismatchPath = new VariablePathBuilder( false ) .add( "main", 0 ) .add( Constants.TYPE_MISMATCH_FAULT_NAME, 0 ) .toVariablePath(); ioExceptionPath = new VariablePathBuilder( false ) .add( "main", 0 ) .add( Constants.IO_EXCEPTION_FAULT_NAME, 0 ) .add( "stackTrace", 0 ) .toVariablePath(); } /** * Creates and returns a default list of handlers, initialized * with default fault handlers for built-in faults like, e.g., TypeMismatch. * @param interpreter the <code>Interpreter</code> in which the returned map will be used * @return a newly created default list of handlers */ public static List< Pair< String, Process > > createDefaultFaultHandlers( final Interpreter interpreter ) { final List< Pair< String, Process > > instList = new ArrayList< Pair< String, Process > >(); instList.add( new Pair< String, Process >( Constants.TYPE_MISMATCH_FAULT_NAME, new Process() { public void run() throws FaultException, ExitingException { interpreter.logWarning( typeMismatchPath.getValue().strValue() ); } public Process clone( TransformationReason reason ) { return this; } public boolean isKillable() { return true; } } ) ); instList.add( new Pair< String, Process >( Constants.IO_EXCEPTION_FAULT_NAME, new Process() { public void run() throws FaultException, ExitingException { interpreter.logWarning( ioExceptionPath.getValue().strValue() ); } public Process clone( TransformationReason reason ) { return this; } public boolean isKillable() { return true; } } ) ); return instList; } private SessionThread( Process process, ExecutionThread parent, jolie.State state ) { super( process, parent ); this.state = state; initMessageQueues(); } public SessionThread( Process process, jolie.State state, ExecutionThread parent ) { super( parent.interpreter(), process ); this.state = state; for( Scope s : parent.scopeStack ) { scopeStack.push( s.clone() ); } initMessageQueues(); } public boolean isInitialisingThread() { return false; } /** * Registers a <code>SessionListener</code> for receiving events from this * session. * @param listener the <code>SessionListener</code> to register */ public void addSessionListener( SessionListener listener ) { listeners.add( listener ); } /** * Constructs a SessionThread with a fresh State. * @param interpreter the Interpreter this thread must refer to * @param process the Process this thread has to execute */ public SessionThread( Interpreter interpreter, Process process ) { super( interpreter, process ); state = new jolie.State(); initMessageQueues(); } private void initMessageQueues() { for( CorrelationSet cset : interpreter().correlationSets() ) { messageQueues.put( cset, new LinkedList< SessionMessage >() ); } } /** * Constructs a SessionThread cloning another ExecutionThread, copying the * State and Scope stack of the parent. * * @param process the Process this thread has to execute * @param parent the ExecutionThread to copy * @param notifyProc the CorrelatedProcess to notify when this session expires * @see CorrelatedProcess */ public SessionThread( Process process, ExecutionThread parent ) { super( process, parent ); initMessageQueues(); assert( parent != null ); state = parent.state().clone(); for( Scope s : parent.scopeStack ) { scopeStack.push( s.clone() ); } } /** * Returns the State of this thread. * @return the State of this thread * @see State */ public jolie.State state() { return state; } public Future< SessionMessage > requestMessage( Map< String, InputOperation > operations, ExecutionThread ethread ) { SessionMessageFuture future = new SessionMessageNDFuture( operations.keySet().toArray( new String[0] ) ); ethread.cancelIfKilled( future ); synchronized( messageQueues ) { Deque< SessionMessage > queue = null; SessionMessage message = null; InputOperation operation = null; Iterator< Deque< SessionMessage > > it = messageQueues.values().iterator(); while( operation == null && it.hasNext() ) { queue = it.next(); message = queue.peekFirst(); if ( message != null ) { operation = operations.get( message.message().operationName() ); } } if ( message == null ) { queue = uncorrelatedMessageQueue; message = queue.peekFirst(); if ( message != null ) { operation = operations.get( message.message().operationName() ); } } if ( message == null || operation == null ) { for( Map.Entry< String, InputOperation > entry : operations.entrySet() ) { addMessageWaiter( entry.getValue(), future ); } } else { future.setResult( message ); queue.removeFirst(); // Check if we unlocked other receives boolean keepRun = true; while( keepRun && !queue.isEmpty() ) { message = queue.peekFirst(); future = getMessageWaiter( message.message().operationName() ); if ( future != null ) { // We found a waiter for the unlocked message future.setResult( message ); queue.removeFirst(); } else { keepRun = false; } } } } return future; } public Future< SessionMessage > requestMessage( InputOperation operation, ExecutionThread ethread ) { SessionMessageFuture future = new SessionMessageFuture(); ethread.cancelIfKilled( future ); CorrelationSet cset = interpreter().getCorrelationSetForOperation( operation.id() ); synchronized( messageQueues ) { Deque< SessionMessage > queue; if ( cset == null ) { queue = uncorrelatedMessageQueue; } else { queue = messageQueues.get( cset ); } SessionMessage message = queue.peekFirst(); if ( message == null || message.message().operationName().equals( operation.id() ) == false ) { addMessageWaiter( operation, future ); } else { future.setResult( message ); queue.removeFirst(); // Check if we unlocked other receives boolean keepRun = true; SessionMessageFuture currFuture; while( keepRun && !queue.isEmpty() ) { message = queue.peekFirst(); currFuture = getMessageWaiter( message.message().operationName() ); if ( currFuture != null ) { // We found a waiter for the unlocked message currFuture.setResult( message ); queue.removeFirst(); } else { keepRun = false; } } } } return future; } private void addMessageWaiter( InputOperation operation, SessionMessageFuture future ) { Deque< SessionMessageFuture > waitersList = messageWaiters.get( operation.id() ); if ( waitersList == null ) { waitersList = new LinkedList< SessionMessageFuture >(); messageWaiters.put( operation.id(), waitersList ); } waitersList.addLast( future ); } private SessionMessageFuture getMessageWaiter( String operationName ) { Deque< SessionMessageFuture > waitersList = messageWaiters.get( operationName ); if ( waitersList == null || waitersList.isEmpty() ) { return null; } if ( waitersList.size() == 1 ) { messageWaiters.remove( operationName ); } return waitersList.removeFirst(); } public void pushMessage( SessionMessage message ) { synchronized( messageQueues ) { Deque< SessionMessage > queue; CorrelationSet cset = interpreter().getCorrelationSetForOperation( message.message().operationName() ); if ( cset != null ) { queue = messageQueues.get( cset ); } else { queue = uncorrelatedMessageQueue; } SessionMessageFuture future = getMessageWaiter( message.message().operationName() ); if ( future != null && queue.isEmpty() ) { future.setResult( message ); } else { queue.addLast( message ); } } } public void run() { try { try { process().run(); } catch( ExitingException e ) {} for( SessionListener listener : listeners ) { listener.onSessionExecuted( this ); } } catch( FaultException f ) { Process p = null; while( hasScope() && (p = getFaultHandler( f.faultName(), true )) == null ) { popScope(); } try { if ( p == null ) { Interpreter.getInstance().logUnhandledFault( f ); throw f; } else { Value scopeValue = new VariablePathBuilder( false ).add( currentScopeId(), 0 ).toVariablePath().getValue(); scopeValue.getChildren( f.faultName() ).set( 0, f.value() ); try { p.run(); } catch( ExitingException e ) {} } } catch( FaultException fault ) { for( SessionListener listener : listeners ) { listener.onSessionError( this, fault ); } } for( SessionListener listener : listeners ) { listener.onSessionExecuted( this ); } } } public String getSessionId() { //return new Long(this.getId()).toString(); return this.getName(); } }
package jolie; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import jolie.lang.Constants; import jolie.net.SessionMessage; import jolie.process.Process; import jolie.process.TransformationReason; import jolie.runtime.ExitingException; import jolie.runtime.FaultException; import jolie.runtime.InputOperation; import jolie.runtime.Value; import jolie.runtime.VariablePath; import jolie.runtime.VariablePathBuilder; import jolie.runtime.correlation.CorrelationSet; import jolie.util.Pair; /** * An ExecutionThread representing a session, equipped * with a dedicated state and message queue. * @author Fabrizio Montesi */ public class SessionThread extends ExecutionThread { private class SessionMessageFuture implements Future< SessionMessage > { private final Lock lock; private final Condition condition; private SessionMessage sessionMessage = null; private boolean isDone = false; public SessionMessageFuture() { lock = new ReentrantLock(); condition = lock.newCondition(); } public boolean cancel( boolean mayInterruptIfRunning ) { return false; } public SessionMessage get( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException { try { lock.lock(); if ( !isDone ) { if ( !condition.await( timeout, unit ) ) { throw new TimeoutException(); } } } finally { lock.unlock(); } return sessionMessage; } public SessionMessage get() throws InterruptedException { try { lock.lock(); if ( !isDone ) { condition.await(); } } finally { lock.unlock(); } return sessionMessage; } public boolean isCancelled() { return false; } public boolean isDone() { return isDone; } protected void setResult( SessionMessage sessionMessage ) { lock.lock(); try { this.sessionMessage = sessionMessage; isDone = true; condition.signalAll(); } finally { lock.unlock(); } } } private class SessionMessageNDFuture extends SessionMessageFuture { private final String[] operationNames; public SessionMessageNDFuture( String[] operationNames ) { super(); this.operationNames = operationNames; } @Override protected void setResult( SessionMessage sessionMessage ) { for( String operationName : operationNames ) { if ( operationName.equals( sessionMessage.message().operationName() ) == false ) { Deque< SessionMessageFuture > waitersList = messageWaiters.get( operationName ); if ( waitersList != null ) { waitersList.remove( this ); } } } super.setResult( sessionMessage ); } } private final jolie.State state; private final List< SessionListener > listeners = new LinkedList< SessionListener >(); protected final Map< CorrelationSet, Deque< SessionMessage > > messageQueues = new HashMap< CorrelationSet, Deque< SessionMessage > >(); protected final Deque< SessionMessage > uncorrelatedMessageQueue = new LinkedList< SessionMessage >(); private final Map< String, Deque< SessionMessageFuture > > messageWaiters = new HashMap< String, Deque< SessionMessageFuture > >(); private final static VariablePath typeMismatchPath; private final static VariablePath ioExceptionPath; static { typeMismatchPath = new VariablePathBuilder( false ) .add( "main", 0 ) .add( Constants.TYPE_MISMATCH_FAULT_NAME, 0 ) .toVariablePath(); ioExceptionPath = new VariablePathBuilder( false ) .add( "main", 0 ) .add( Constants.IO_EXCEPTION_FAULT_NAME, 0 ) .add( "stackTrace", 0 ) .toVariablePath(); } /** * Creates and returns a default list of handlers, initialized * with default fault handlers for built-in faults like, e.g., TypeMismatch. * @param interpreter the <code>Interpreter</code> in which the returned map will be used * @return a newly created default list of handlers */ public static List< Pair< String, Process > > createDefaultFaultHandlers( final Interpreter interpreter ) { final List< Pair< String, Process > > instList = new ArrayList< Pair< String, Process > >(); instList.add( new Pair< String, Process >( Constants.TYPE_MISMATCH_FAULT_NAME, new Process() { public void run() throws FaultException, ExitingException { interpreter.logWarning( typeMismatchPath.getValue().strValue() ); } public Process clone( TransformationReason reason ) { return this; } public boolean isKillable() { return true; } } ) ); instList.add( new Pair< String, Process >( Constants.IO_EXCEPTION_FAULT_NAME, new Process() { public void run() throws FaultException, ExitingException { interpreter.logWarning( ioExceptionPath.getValue().strValue() ); } public Process clone( TransformationReason reason ) { return this; } public boolean isKillable() { return true; } } ) ); return instList; } private SessionThread( Process process, ExecutionThread parent, jolie.State state ) { super( process, parent ); this.state = state; initMessageQueues(); } public SessionThread( Process process, jolie.State state, ExecutionThread parent ) { super( parent.interpreter(), process ); this.state = state; for( Scope s : parent.scopeStack ) { scopeStack.push( s.clone() ); } initMessageQueues(); } public boolean isInitialisingThread() { return false; } /** * Registers a <code>SessionListener</code> for receiving events from this * session. * @param listener the <code>SessionListener</code> to register */ public void addSessionListener( SessionListener listener ) { listeners.add( listener ); } /** * Constructs a SessionThread with a fresh State. * @param interpreter the Interpreter this thread must refer to * @param process the Process this thread has to execute */ public SessionThread( Interpreter interpreter, Process process ) { super( interpreter, process ); state = new jolie.State(); initMessageQueues(); } private void initMessageQueues() { for( CorrelationSet cset : interpreter().correlationSets() ) { messageQueues.put( cset, new LinkedList< SessionMessage >() ); } } /** * Constructs a SessionThread cloning another ExecutionThread, copying the * State and Scope stack of the parent. * * @param process the Process this thread has to execute * @param parent the ExecutionThread to copy * @param notifyProc the CorrelatedProcess to notify when this session expires * @see CorrelatedProcess */ public SessionThread( Process process, ExecutionThread parent ) { super( process, parent ); initMessageQueues(); assert( parent != null ); state = parent.state().clone(); for( Scope s : parent.scopeStack ) { scopeStack.push( s.clone() ); } } /** * Returns the State of this thread. * @return the State of this thread * @see State */ public jolie.State state() { return state; } public Future< SessionMessage > requestMessage( Map< String, InputOperation > operations ) { SessionMessageFuture future = new SessionMessageNDFuture( operations.keySet().toArray( new String[0] ) ); synchronized( messageQueues ) { Deque< SessionMessage > queue = null; SessionMessage message = null; InputOperation operation = null; Iterator< Deque< SessionMessage > > it = messageQueues.values().iterator(); while( operation == null && it.hasNext() ) { queue = it.next(); message = queue.peekFirst(); if ( message != null ) { operation = operations.get( message.message().operationName() ); } } if ( message == null ) { queue = uncorrelatedMessageQueue; message = queue.peekFirst(); if ( message != null ) { operation = operations.get( message.message().operationName() ); } } if ( message == null || operation == null ) { for( Map.Entry< String, InputOperation > entry : operations.entrySet() ) { addMessageWaiter( entry.getValue(), future ); } } else { future.setResult( message ); queue.removeFirst(); // Check if we unlocked other receives boolean keepRun = true; while( keepRun && !queue.isEmpty() ) { message = queue.peekFirst(); future = getMessageWaiter( message.message().operationName() ); if ( future != null ) { // We found a waiter for the unlocked message future.setResult( message ); queue.removeFirst(); } else { keepRun = false; } } } } return future; } public Future< SessionMessage > requestMessage( InputOperation operation ) { SessionMessageFuture future = new SessionMessageFuture(); CorrelationSet cset = interpreter().getCorrelationSetForOperation( operation.id() ); synchronized( messageQueues ) { Deque< SessionMessage > queue; if ( cset == null ) { queue = uncorrelatedMessageQueue; } else { queue = messageQueues.get( cset ); } SessionMessage message = queue.peekFirst(); if ( message == null || message.message().operationName().equals( operation.id() ) == false ) { addMessageWaiter( operation, future ); } else { future.setResult( message ); queue.removeFirst(); // Check if we unlocked other receives boolean keepRun = true; SessionMessageFuture currFuture; while( keepRun && !queue.isEmpty() ) { message = queue.peekFirst(); currFuture = getMessageWaiter( message.message().operationName() ); if ( currFuture != null ) { // We found a waiter for the unlocked message currFuture.setResult( message ); queue.removeFirst(); } else { keepRun = false; } } } } return future; } private void addMessageWaiter( InputOperation operation, SessionMessageFuture future ) { Deque< SessionMessageFuture > waitersList = messageWaiters.get( operation.id() ); if ( waitersList == null ) { waitersList = new LinkedList< SessionMessageFuture >(); messageWaiters.put( operation.id(), waitersList ); } waitersList.addLast( future ); } private SessionMessageFuture getMessageWaiter( String operationName ) { Deque< SessionMessageFuture > waitersList = messageWaiters.get( operationName ); if ( waitersList == null || waitersList.isEmpty() ) { return null; } if ( waitersList.size() == 1 ) { messageWaiters.remove( operationName ); } return waitersList.removeFirst(); } public void pushMessage( SessionMessage message ) { synchronized( messageQueues ) { SessionMessageFuture future = getMessageWaiter( message.message().operationName() ); if ( future == null ) { CorrelationSet cset = interpreter().getCorrelationSetForOperation( message.message().operationName() ); if ( cset != null ) { messageQueues.get( cset ).addLast( message ); } else { uncorrelatedMessageQueue.addLast( message ); } } else { future.setResult( message ); } } } public void run() { try { try { process().run(); } catch( ExitingException e ) {} for( SessionListener listener : listeners ) { listener.onSessionExecuted( this ); } } catch( FaultException f ) { Process p = null; while( hasScope() && (p = getFaultHandler( f.faultName(), true )) == null ) { popScope(); } try { if ( p == null ) { Interpreter.getInstance().logUnhandledFault( f ); throw f; } else { Value scopeValue = new VariablePathBuilder( false ).add( currentScopeId(), 0 ).toVariablePath().getValue(); scopeValue.getChildren( f.faultName() ).set( 0, f.value() ); try { p.run(); } catch( ExitingException e ) {} } } catch( FaultException fault ) { for( SessionListener listener : listeners ) { listener.onSessionError( this, fault ); } } for( SessionListener listener : listeners ) { listener.onSessionExecuted( this ); } } } public String getSessionId() { //return new Long(this.getId()).toString(); return this.getName(); } }
package org.nuxeo.ecm.admin.offline.update; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.common.Environment; import org.nuxeo.common.utils.FileUtils; import org.nuxeo.connect.update.LocalPackage; import org.nuxeo.connect.update.PackageException; import org.nuxeo.connect.update.PackageState; import org.nuxeo.connect.update.PackageUpdateService; import org.nuxeo.connect.update.ValidationStatus; import org.nuxeo.connect.update.task.Task; import org.nuxeo.osgi.application.loader.FrameworkLoader; import org.nuxeo.runtime.api.Framework; /** * Offline Marketplace packages manager. * * See {@link #printHelp()} for the usage. * * The target directory is set from System property "nuxeo.runtime.home". * * <p> * The environment used by Nuxeo runtime can be specified as System properties. * <p> * All the bundles and the third parties must be on the boot classpath. You * should have at least these bundles: * <ul> * <li>nuxeo-common * <li>nuxeo-connect-client * <li>nuxeo-connect-client-wrapper * <li>nuxeo-connect-update * <li>nuxeo-connect-offline-update * <li>nuxeo-runtime * <li>nuxeo-runtime-osgi * <li>nuxeo-runtime-reload * </ul> * and these libraries: * <ul> * <li>commons-io * <li>groovy-all * <li>osgi-core * <li>xercesImpl * <li>commons-logging * <li>log4j * </ul> * */ public class LocalPackageManager { static final Log log = LogFactory.getLog(LocalPackageManager.class); protected File home; protected File wd; protected File bundlesDir; protected List<File> bundles; protected File config; protected Map<String, Object> env; protected Environment targetEnv; protected List<String> packages = new ArrayList<String>(); protected PackageUpdateService pus; private String command; private int errorValue = 0; public static void main(String[] args) throws Exception { LocalPackageManager main = null; try { main = new LocalPackageManager(args); main.initializeFramework(); main.startFramework(); main.run(args); } catch (Throwable e) { log.error(e); main.errorValue = 2; } finally { if (main != null) { main.stopFramework(); } } System.exit(main.errorValue); } public LocalPackageManager(String[] args) throws FileNotFoundException { if (args.length < 3) { printHelp(); System.exit(1); } wd = new File(args[0]); if (!wd.isDirectory()) { throw new IllegalStateException(wd + " is not a directory!"); } command = args[1]; config = new File(args[2]); home = new File(System.getProperty("nuxeo.runtime.home")); if (home == null) { throw new IllegalStateException( "Syntax Error: You must provide the runtime home " + "as a System property (\"" + Environment.NUXEO_RUNTIME_HOME + "\")."); } bundlesDir = new File(wd, "bundles"); initBundleFiles(); initEnvironment(); targetEnv = createTargetEnvironment(); } public void run(String[] args) { Environment defaultEnv = Environment.getDefault(); try { Environment.setDefault(targetEnv); if ("install".equalsIgnoreCase(command)) { readPackages(); update(); } else if ("installpkg".equalsIgnoreCase(command)) { String packageParam = args[3]; if (new File(packageParam).exists()) { // packageParam is a file update(packageParam); } else { // packageParam maybe an ID updatePackage(packageParam); } } else if ("uninstall".equalsIgnoreCase(command)) { if (args.length < 4) { throw new PackageException( "Missing package id as parameter."); } uninstall(args[3]); } else if ("list".equalsIgnoreCase(command)) { readPackages(); listPackages(); } else if ("reset".equalsIgnoreCase(command)) { reset(); } else { printHelp(); return; } } catch (PackageException e) { log.error(e); errorValue = 1; } finally { Environment.setDefault(defaultEnv); } } public void printHelp() { log.error("\nLocalPackageManager usage: working_directory command [parameters]"); log.error("Commands:"); log.error("\tlist\t\t\t\tLists local packages and their status."); log.error("\tinstall /path/to/upgrade/file\t\t\tReads the given upgrade" + " file and performs install."); log.error("\tinstallpkg [/path/to/package|packageId]\t\tInstalls the given" + " package (as a file or its ID)."); log.error("\tuninstall packageId\t\t\t\tUninstalls the specified package."); log.error("\treset\t\t\t\t\tReset all package states to DOWNLOADED. " + "This may be useful after a manual upgrade of the server."); } protected void initEnvironment() { env = new HashMap<String, Object>(); } protected Environment createTargetEnvironment() { Environment environment = new Environment(home); environment.init(); return environment; } protected void initBundleFiles() throws FileNotFoundException { bundles = new ArrayList<File>(); if (!bundlesDir.isDirectory()) { throw new FileNotFoundException("File " + bundlesDir + " is not a directory"); } File[] list = bundlesDir.listFiles(); if (list == null) { throw new FileNotFoundException("No bundles found in " + bundlesDir); } for (File file : list) { String name = file.getName(); if (name.endsWith(".jar") && name.contains("nuxeo-")) { // a bundle if (!name.contains("osgi")) { // avoid loading the system bundle bundles.add(file); } } } } public void initializeFramework() { System.setProperty("org.nuxeo.connect.update.dataDir", targetEnv.getData().getAbsolutePath()); FrameworkLoader.initialize(LocalPackageManager.class.getClassLoader(), wd, bundles, env); } public void startFramework() throws Exception { FrameworkLoader.start(); pus = Framework.getLocalService(PackageUpdateService.class); if (pus == null) { throw new IllegalStateException("PackagUpdateService not found"); } } public void stopFramework() throws Exception { try { FrameworkLoader.stop(); } finally { if (wd != null) { FileUtils.deleteTree(wd); } } } public void update() throws PackageException { if (packages.isEmpty()) { throw new PackageException("No package found in " + config); } log.info("Performing update ..."); for (String pkgId : packages) { try { boolean uninstall = false; if (pkgId.startsWith("uninstall ")) { pkgId = pkgId.substring(10); uninstall = true; } if (pkgId.startsWith("file:")) { String packageFileName = pkgId.substring(5); log.info("Getting Installation package " + packageFileName); LocalPackage pkg = pus.addPackage(new File(packageFileName)); pkgId = pkg.getId(); } if (uninstall) { uninstall(pkgId); } else { updatePackage(pkgId); } } catch (PackageException e) { log.error(e); errorValue = 1; } } if (errorValue != 0) { File bak = new File(config.getPath() + ".bak"); bak.delete(); config.renameTo(bak); throw new PackageException("An error occurred. File renamed to " + bak); } log.info("Done."); config.delete(); } protected void readPackages() { if (!config.isFile()) { log.debug("No file " + config); return; } List<String> lines; try { lines = FileUtils.readLines(config); for (String line : lines) { line = line.trim(); if (line.length() > 0 && !line.startsWith(" packages.add(line); } } } catch (IOException e) { log.error(e.getMessage()); } return; } /** * @param pkgId * @throws PackageException * @since 5.5 */ public void update(String packageFileName) throws PackageException { LocalPackage pkg = pus.addPackage(new File(packageFileName)); String pkgId = pkg.getId(); updatePackage(pkgId); } protected void updatePackage(String pkgId) throws PackageException { LocalPackage pkg = pus.getPackage(pkgId); if (pkg == null) { throw new IllegalStateException("No package found: " + pkgId); } log.info("Updating " + pkgId); Task installTask = pkg.getInstallTask(); try { performTask(installTask); } catch (Throwable e) { installTask.rollback(); errorValue = 1; log.error("Failed to install package: " + pkgId, e); } } /** * Validate and run given task * * @since 5.5 * @param task * @throws PackageException */ public void performTask(Task task) throws PackageException { ValidationStatus status = task.validate(); if (status.hasErrors()) { errorValue = 3; throw new PackageException("Failed to validate package " + task.getPackage().getId() + " -> " + status.getErrors()); } task.run(null); } /** * @param pkgId Marketplace package id * @throws PackageException * @since 5.5 */ private void uninstall(String pkgId) throws PackageException { LocalPackage pkg = pus.getPackage(pkgId); if (pkg == null) { throw new IllegalStateException("No package found: " + pkgId); } log.info("Uninstalling " + pkgId); Task uninstallTask = pkg.getUninstallTask(); try { performTask(uninstallTask); } catch (Throwable e) { uninstallTask.rollback(); errorValue = 1; log.error("Failed to uninstall package: " + pkgId, e); } } /** * @throws PackageException * @since 5.5 */ private void listPackages() throws PackageException { if (packages.isEmpty()) { log.info("No package waiting for install."); } else { log.info("Waiting for install:"); for (String pkg : packages) { log.info(pkg); } } List<LocalPackage> localPackages = pus.getPackages(); if (localPackages.isEmpty()) { log.info("No local package."); } else { log.info("Local packages:"); for (LocalPackage localPackage : localPackages) { String packageDescription; switch (localPackage.getState()) { case PackageState.DOWNLOADING: packageDescription = "downloading..."; break; case PackageState.DOWNLOADED: packageDescription = "downloaded"; break; case PackageState.INSTALLING: packageDescription = "installing..."; break; case PackageState.INSTALLED: packageDescription = "installed"; break; case PackageState.STARTED: packageDescription = "started"; break; default: packageDescription = "unknown"; break; } packageDescription += "\t" + localPackage.getName() + " (id: " + localPackage.getId() + ")"; log.info(packageDescription); } } } private void reset() throws PackageException { pus.reset(); log.info("Packages reset done: All packages were marked as DOWNLOADED"); } }
package com.psddev.dari.db; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.psddev.dari.util.CompactMap; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import com.psddev.dari.util.Settings; import com.psddev.dari.util.SparseSet; /** * Skeletal database implementation. A subclass must implement: * * <ul> * <li>{@link #openConnection}</li> * <li>{@link #closeConnection}</li> * <li>{@link #readLastUpdate}</li> * <li>{@link #readPartial}</li> * <li>{@link #doWrites}</li> * </ul> * * <p>If it supports read slaves, it should override: * * <ul> * <li>{@link #doOpenReadConnection}</li> * </ul> * * <p>It can override these to improve performance: * * <ul> * <li>{@link #readAll}</li> * <li>{@link #readAllGrouped}</li> * <li>{@link #readCount}</li> * <li>{@link #readFirst}</li> * <li>{@link #readIterable}</li> * <li>{@link #readPartialGrouped}</li> * <li>{@link #doIndexes}</li> * <li>{@link #deleteByQuery}</li> * </ul> * * <p>If it supports transactional writes, it should override: * * <ul> * <li>{@link #beginTransaction}</li> * <li>{@link #commitTransaction}</li> * <li>{@link #rollbackTransaction}</li> * <li>{@link #endTransaction}</li> * </ul> * * @param C Type of the implementation-specific connection object that's * used for all database operations. */ public abstract class AbstractDatabase<C> implements Database { public static final double DEFAULT_READ_TIMEOUT = 3.0; public static final String NULL_TYPE_QUERY_OPTION = "db.nullType"; public static final String GROUPS_SUB_SETTING = "groups"; public static final String READ_TIMEOUT_SUB_SETTING = "readTimeout"; public static final String TRIGGER_EXTRA_PREFIX = "db.trigger."; private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDatabase.class); private volatile String name; private transient volatile DatabaseEnvironment environment; private volatile Set<String> groups; private volatile double readTimeout = DEFAULT_READ_TIMEOUT; private final transient ThreadLocal<Deque<Writes>> writesQueueLocal = new ThreadLocal<Deque<Writes>>(); private static class Writes { public int depth; public final List<State> validates = new ArrayList<State>(); public final List<State> saves = new ArrayList<State>(); public final List<State> indexes = new ArrayList<State>(); public final List<State> deletes = new ArrayList<State>(); public void addToValidates(State state) { validates.remove(state); validates.add(state); } public void addToSaves(State state) { saveJunctions(state, state.getDatabase().getEnvironment()); ObjectType type = state.getType(); if (type != null) { saveJunctions(state, type); } for (Iterator<State> i = saves.iterator(); i.hasNext();) { State s = i.next(); if (s.equals(state)) { i.remove(); state.getAtomicOperations().addAll(0, s.getAtomicOperations()); } } saves.add(state); } private void saveJunctions(State state, ObjectStruct struct) { for (ObjectField field : struct.getFields()) { String junctionField = field.getJunctionField(); if (!ObjectUtils.isBlank(junctionField)) { String fieldName = field.getInternalName(); List<Object> oldItems = field.findJunctionItems(state); Iterable<?> newItems = ObjectUtils.to(Iterable.class, state.get(fieldName)); if (newItems != null) { Iterator<?> i = newItems.iterator(); if (i.hasNext()) { Double lastPosition = null; String positionField = field.getJunctionPositionField(); for (Object item = i.next(), next = null; item != null; item = next) { next = i.hasNext() ? i.next() : null; State itemState = State.getInstance(item); Object junction = itemState.get(junctionField); double position; boolean save = false; oldItems.remove(item); if (junction == null || (junction instanceof Recordable && !State.getInstance(junction).equals(state))) { save = true; itemState.put(junctionField, state.getOriginalObject()); } else if (junction instanceof Collection) { save = true; @SuppressWarnings("unchecked") Collection<Object> junctionCollection = (Collection<Object>) junction; Object stateObject = state.getOriginalObject(); if (!junctionCollection.contains(stateObject)) { junctionCollection.add(stateObject); } } if (!ObjectUtils.isBlank(positionField)) { position = ObjectUtils.to(double.class, itemState.get(positionField)); if (position == 0.0) { position = 0.1; save = true; } if (lastPosition == null) { if (next != null) { double nextPosition = ObjectUtils.to(double.class, State.getInstance(next).get(positionField)); if (nextPosition <= position) { position = nextPosition - 1.0; save = true; } } } else if (lastPosition >= position) { if (next == null) { position = lastPosition + 1.0; } else { double nextPosition = ObjectUtils.to(double.class, State.getInstance(next).get(positionField)); position = (lastPosition + nextPosition) / 2.0; if (lastPosition >= position) { position = lastPosition + 1.0; } } save = true; } lastPosition = position; if (save) { itemState.put(positionField, position); } } if (save) { addToSaves(itemState); } } } } for (Object item : oldItems) { State itemState = State.getInstance(item); itemState.remove(junctionField); addToSaves(itemState); } } } } public void addToIndexes(State state) { for (Iterator<State> i = indexes.iterator(); i.hasNext();) { State s = i.next(); if (s.equals(state)) { i.remove(); } } indexes.add(state); } public void addToDeletes(State state) { deletes.remove(state); deletes.add(state); } } /** * Returns all {@linkplain ObjectType#getGroups groups} of types that * can be saved to this database. */ public Set<String> getGroups() { if (groups == null) { groups = new SparseSet("+/"); } return groups; } /** * Sets all {@linkplain ObjectType#getGroups groups} of types that * can be saved to this database. */ public void setGroups(Set<String> groups) { this.groups = groups; } /** * Returns {@code true} if the given {@code types} represent all * types that can be saved to this database as indicated in * {@link #getGroups}. */ public boolean isAllTypes(Collection<ObjectType> types) { Set<String> databaseGroups = getGroups(); int allTypesCount = 0; for (ObjectType type : getEnvironment().getTypes()) { if (!(type.isAbstract() || type.isEmbedded())) { for (String typeGroup : type.getGroups()) { if (databaseGroups.contains(typeGroup)) { ++ allTypesCount; break; } } } } return types.size() == allTypesCount; } /** * Returns the read timeout, in seconds. * * @return May be less than or equal to {@code 0} to indicate * no timeout. */ public double getReadTimeout() { return readTimeout; } /** * Sets the read timeout, in seconds. * * @param readTimeout May be less than or equal to {@code 0} to * indicate no timeout. */ public void setReadTimeout(double readTimeout) { this.readTimeout = readTimeout; } /** * Opens an implementation-specific connection to the underlying * database. Once opened, the connection should be closed with * {@link #closeConnection}. * * @return Can't be {@code null}. */ public abstract C openConnection(); /** * Opens an implementation-specific connection to the underlying * database that can only be used for reading data. Once opened, * the connection should be closed with {@link #closeConnection}. * * @return Can't be {@code null}. */ @SuppressWarnings("deprecation") public final C openReadConnection() { return Database.Static.isIgnoreReadConnection() ? openConnection() : doOpenReadConnection(); } /** * Called when this database needs to open an implementation-specific * connection to the underlying database that can only be used for * reading data. The default implementation calls * {@link #openConnection}. * * @return Can't be {@code null}. */ protected C doOpenReadConnection() { return openConnection(); } /** * Opens a connection that should be used to execute the given * {@code query}. */ public C openQueryConnection(Query<?> query) { return query != null && query.isMaster() ? openConnection() : openReadConnection(); } /** * Closes the given implementation-specific {@code connection} * to the underlying database. */ public abstract void closeConnection(C connection); /** Returns {@code true} if the given {@code error} is recoverable. */ protected boolean isRecoverableError(Exception error) { return false; } @Override public final synchronized void initialize(String settingsKey, Map<String, Object> settings) { String groupsPattern = ObjectUtils.to(String.class, settings.get(GROUPS_SUB_SETTING)); setGroups(new SparseSet(ObjectUtils.isBlank(groupsPattern) ? "+/" : groupsPattern)); Double readTimeout = ObjectUtils.to(Double.class, settings.get(READ_TIMEOUT_SUB_SETTING)); if (readTimeout != null) { setReadTimeout(readTimeout); } doInitialize(settingsKey, settings); } /** * Called to initialize this database using the given {@code settings}. */ protected abstract void doInitialize(String settingsKey, Map<String, Object> settings); @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public DatabaseEnvironment getEnvironment() { if (environment == null) { setEnvironment(new DatabaseEnvironment(this)); } return environment; } @Override public void setEnvironment(DatabaseEnvironment environment) { this.environment = environment; } @Override public <T> List<T> readAll(Query<T> query) { return readPartial(query, 0L, MAXIMUM_LIMIT).getItems(); } @Override public <T> List<Grouping<T>> readAllGrouped(Query<T> query, String... fields) { return readPartialGrouped(query, 0L, MAXIMUM_LIMIT, fields).getItems(); } @Deprecated @Override public <T> List<T> readList(Query<T> query) { return readAll(query); } @Override public long readCount(Query<?> query) { return readPartial(query, 0L, 1).getCount(); } @Override public <T> T readFirst(Query<T> query) { for (T item : readPartial(query, 0L, 1).getItems()) { return item; } return null; } @Override public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) { return new PaginatedIterable<T>(query, fetchSize); } private static class PaginatedIterable<T> implements Iterable<T> { private final Query<T> query; private final int fetchSize; public PaginatedIterable(Query<T> query, int fetchSize) { this.query = query; this.fetchSize = fetchSize; } @Override public Iterator<T> iterator() { return query.getSorters().isEmpty() ? new ByIdIterator<T>(query, fetchSize) : new PaginatedIterator<T>(query, fetchSize); } } private static class ByIdIterator<T> implements Iterator<T> { private final Query<T> query; private final int fetchSize; private UUID lastObjectId; private PaginatedResult<T> result; private int index; public ByIdIterator(Query<T> query, int fetchSize) { this.query = query.clone().sortAscending("_id"); this.fetchSize = fetchSize > 0 ? fetchSize : 200; } @Override public boolean hasNext() { if (result != null && index >= result.getItems().size()) { if (result.hasNext()) { result = null; } else { return false; } } if (result == null) { Query<T> nextQuery = query.clone(); if (lastObjectId != null) { nextQuery.and("_id > ?", lastObjectId); } result = nextQuery.select(0, fetchSize); List<T> items = result.getItems(); int size = items.size(); if (size < 1) { return false; } lastObjectId = State.getInstance(items.get(size - 1)).getId(); index = 0; } return true; } @Override public T next() { if (hasNext()) { T object = result.getItems().get(index); ++ index; return object; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } private static class PaginatedIterator<T> implements Iterator<T> { private final Query<T> query; private PaginatedResult<T> result; private long offset; private final int limit; private int index; public PaginatedIterator(Query<T> query, int limit) { this.query = query; this.limit = limit > 0 ? limit : 200; } @Override public boolean hasNext() { if (result != null && index >= result.getItems().size()) { if (result.hasNext()) { result = null; } else { return false; } } if (result == null) { result = query.select(offset, limit); List<T> items = result.getItems(); int size = items.size(); if (size < 1) { return false; } offset += limit; index = 0; } return true; } @Override public T next() { if (hasNext()) { T object = result.getItems().get(index); ++ index; return object; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) { Map<List<Object>, BasicGrouping<T>> groupingsMap = new CompactMap<List<Object>, BasicGrouping<T>>(); for (Object item : readIterable(query, 0)) { State itemState = State.getInstance(item); List<Object> keys = new ArrayList<Object>(); if (fields != null) { for (String field : fields) { Matcher groupingMatcher = Query.RANGE_PATTERN.matcher(field); if (groupingMatcher.find()) { Double bucket = null; String fieldName = groupingMatcher.group(1); if (itemState.getByPath(fieldName) != null) { Double start = ObjectUtils.to(Double.class, groupingMatcher.group(2).trim()); Double end = ObjectUtils.to(Double.class, groupingMatcher.group(3).trim()); Double gap = ObjectUtils.to(Double.class, groupingMatcher.group(4).trim()); Double value = ObjectUtils.to(Double.class, itemState.getByPath(fieldName)); for (double window = start; window <= end; window += gap) { if (value < window) { bucket = window - gap; break; } } } keys.add(bucket); } else { keys.add(itemState.getByPath(field)); } } } BasicGrouping<T> grouping = groupingsMap.get(keys); if (grouping == null) { grouping = new BasicGrouping<T>(keys, query, fields); groupingsMap.put(keys, grouping); } grouping.count += 1; } List<Grouping<T>> groupings = new ArrayList<Grouping<T>>(groupingsMap.values()); return new PaginatedResult<Grouping<T>>(offset, limit, groupings); } /** Basic implementation of {@link Grouping}. */ private class BasicGrouping<T> extends AbstractGrouping<T> { private long count; public BasicGrouping(List<Object> keys, Query<T> query, String[] fields) { super(keys, query, fields); } @Override protected Aggregate createAggregate(String field) { Aggregate aggregate = new Aggregate(); Query<?> aggregateQuery = Query.fromQuery(query); List<Object> keys = getKeys(); ITEM: for (Object item : readIterable(aggregateQuery, 0)) { State itemState = State.getInstance(item); Object value = itemState.getByPath(field); if (value == null) { continue; } for (int i = 0, length = fields.length; i < length; ++ i) { if (!ObjectUtils.equals(keys.get(i), itemState.getByPath(fields[i]))) { continue ITEM; } } aggregate.setNonNullCount(aggregate.getNonNullCount() + 1); if (ObjectUtils.compare(aggregate.getMaximum(), value, false) < 0) { aggregate.setMaximum(value); } if (ObjectUtils.compare(aggregate.getMinimum(), value, true) > 0) { aggregate.setMinimum(value); } Double valueDouble = ObjectUtils.to(Double.class, value); if (valueDouble != null) { aggregate.setSum(aggregate.getSum() + valueDouble); } } return aggregate; } @Override public long getCount() { return count; } } @Deprecated @Override public Map<Object, Long> readGroupedCount(Query<?> query, String field) { Map<Object, Long> counts = new CompactMap<Object, Long>(); for (Grouping<?> grouping : readAllGrouped(query, field)) { counts.put(grouping.getKeys().get(0), grouping.getCount()); } return counts; } private final Deque<Writes> getOrCreateWritesQueue() { Deque<Writes> writesQueue = writesQueueLocal.get(); if (writesQueue == null) { writesQueue = new ArrayDeque<Writes>(); writesQueueLocal.set(writesQueue); } return writesQueue; } @Override public final boolean beginWrites() { Deque<Writes> writesQueue = getOrCreateWritesQueue(); if (writesQueue.isEmpty()) { writesQueue.addLast(new Writes()); return true; } else { ++ writesQueue.peekLast().depth; return false; } } @Override public final void beginIsolatedWrites() { getOrCreateWritesQueue().addLast(new Writes()); } @Override public final boolean commitWrites() { return doCommitWrites(true); } @Override public final boolean commitWritesEventually() { return doCommitWrites(false); } private boolean doCommitWrites(boolean isImmediate) { Deque<Writes> writesQueue = writesQueueLocal.get(); if (writesQueue == null || writesQueue.isEmpty()) { throw new IllegalStateException("Can't commit writes that never began!"); } Writes writes = writesQueue.peekLast(); if (writes.depth > 0) { return false; } else { try { write(writes.validates, writes.saves, writes.indexes, writes.deletes, isImmediate); return true; } finally { writes.validates.clear(); writes.saves.clear(); writes.indexes.clear(); writes.deletes.clear(); } } } @Override public final boolean endWrites() { Deque<Writes> writesQueue = writesQueueLocal.get(); if (writesQueue == null || writesQueue.isEmpty()) { throw new IllegalStateException("Can't end writes that never began!"); } Writes writes = writesQueue.peekLast(); if (writes.depth > 0) { -- writes.depth; return false; } else { writesQueue.removeLast(); if (writesQueue.isEmpty()) { writesQueueLocal.remove(); } return true; } } private final Writes getCurrentWrites() { Deque<Writes> writesQueue = writesQueueLocal.get(); return writesQueue != null ? writesQueue.peekLast() : null; } private static class BeforeSaveTrigger extends TriggerOnce { @Override protected void executeOnce(Object object) { if (object instanceof Record) { ((Record) object).beforeSave(); } } }; private static class AfterSaveTrigger extends TriggerOnce { @Override protected void executeOnce(Object object) { if (object instanceof Record) { Record record = (Record) object; try { record.afterSave(); } catch (RuntimeException error) { LOGGER.warn( String.format("Couldn't run afterSave on [%s]", record.getId()), error); } } } }; private static class BeforeDeleteTrigger extends TriggerOnce { @Override protected void executeOnce(Object object) { if (object instanceof Record) { ((Record) object).beforeDelete(); } } }; private static class AfterDeleteTrigger extends TriggerOnce { @Override protected void executeOnce(Object object) { if (object instanceof Record) { Record record = (Record) object; try { record.afterDelete(); } catch (RuntimeException error) { LOGGER.warn("Couldn't run afterDelete on [{}]", record.getId()); } } } }; @Override public final void save(State state) { checkState(state); ObjectType type = state.getType(); if (type != null && !type.isConcrete()) { throw new IllegalStateException(String.format( "Can't save a non-concrete object! (%s)", type.getLabel())); } state.fireTrigger(new BeforeSaveTrigger()); Writes writes = getCurrentWrites(); if (writes != null) { writes.addToValidates(state); writes.addToSaves(state); } else { writes = new Writes(); writes.addToValidates(state); writes.addToSaves(state); write(writes.validates, writes.saves, null, null, true); } } @Override public final void saveUnsafely(State state) { checkState(state); Writes writes = getCurrentWrites(); if (writes != null) { writes.addToSaves(state); } else { write(null, Arrays.asList(state), null, null, true); } } @Override public final void index(State state) { checkState(state); Writes writes = getCurrentWrites(); if (writes != null) { writes.addToIndexes(state); } else { write(null, null, Arrays.asList(state), null, true); } } // Checks to make sure that the given {@code state} is savable. private void checkState(State state) { if (state == null) { throw new IllegalArgumentException("State is required!"); } if (state.isReferenceOnly()) { throw new IllegalArgumentException(String.format( "Can't write a reference-only object! (%s)", state.getId())); } } @Override public void indexAll(ObjectIndex index) { } @Override public final void delete(State state) { state.fireTrigger(new BeforeDeleteTrigger()); Writes writes = getCurrentWrites(); if (writes != null) { writes.addToDeletes(state); } else { write(null, null, null, Arrays.asList(state), true); } } @Override public void deleteByQuery(Query<?> query) { int batchSize = 200; try { beginWrites(); int i = 0; for (Object item : readIterable(query, batchSize)) { delete(State.getInstance(item)); ++ i; if (i % batchSize == 0) { commitWrites(); } } commitWrites(); } finally { endWrites(); } } // Performs the given write operations. private void write( List<State> validates, List<State> saves, List<State> indexes, List<State> deletes, boolean isImmediate) { boolean hasValidates = validates != null && !validates.isEmpty(); boolean hasSaves = saves != null && !saves.isEmpty(); boolean hasIndexes = indexes != null && !indexes.isEmpty(); boolean hasDeletes = deletes != null && !deletes.isEmpty(); if (!(hasValidates || hasSaves || hasIndexes || hasDeletes)) { return; } List<DistributedLock> locks = validate(validates, true); try { if (locks != null && !locks.isEmpty()) { for (DistributedLock lock : locks) { lock.lock(); } validate(validates, false); } boolean isCommitted = false; Exception lastError = null; for (int i = 0, limit = Settings.getOrDefault(int.class, "dari/databaseWriteRetryLimit", 10); i < limit; ++ i) { try { C connection = openConnection(); try { try { beginTransaction(connection, isImmediate); doWrites(connection, isImmediate, saves, indexes, deletes); commitTransaction(connection, isImmediate); isCommitted = true; break; } finally { try { if (!isCommitted) { rollbackTransaction(connection, isImmediate); } } finally { endTransaction(connection, isImmediate); } } } finally { closeConnection(connection); } } catch (Retry error) { } catch (Exception error) { lastError = error; if (error instanceof RecoverableDatabaseException || isRecoverableError(error)) { try { long initialPause = Settings.getOrDefault(long.class, "dari/databaseWriteRetryInitialPause", 10L); long finalPause = Settings.getOrDefault(long.class, "dari/databaseWriteRetryFinalPause", 1000L); double pauseJitter = Settings.getOrDefault(double.class, "dari/databaseWriteRetryPauseJitter", 0.5); long pause = ObjectUtils.jitter(initialPause + (finalPause - initialPause) * i / (limit - 1), pauseJitter); Thread.sleep(pause); continue; } catch (InterruptedException ex2) { // Ignore thread interruption and continue. } } break; } } if (!isCommitted) { if (lastError instanceof DatabaseException) { throw (DatabaseException) lastError; } else if (isRecoverableError(lastError)) { throw new RecoverableDatabaseException(this, lastError); } else { throw new DatabaseException(this, lastError); } } } finally { if (locks != null && !locks.isEmpty()) { for (DistributedLock lock : locks) { try { lock.unlock(); } catch (Throwable ex) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Can't unlock [" + lock + "]!", ex); } } } } } if (hasValidates) { for (State state : validates) { state.setStatus(StateStatus.SAVED); state.fireTrigger(new AfterSaveTrigger()); } } if (hasDeletes) { for (State state : deletes) { state.setStatus(StateStatus.DELETED); state.fireTrigger(new AfterDeleteTrigger()); } } } private static class OnDuplicateTrigger extends TriggerOnce { private final ObjectIndex index; private boolean corrected; public OnDuplicateTrigger(ObjectIndex index) { this.index = index; } @Override protected void executeOnce(Object object) { if (object instanceof Record) { corrected = ((Record) object).onDuplicate(index) || corrected; } } public boolean isCorrected() { return corrected; } } // Validates the given states and returns a list of locks that // should be used to enforce unique constraints. private List<DistributedLock> validate(List<State> states, boolean beforeLocks) { if (states == null || states.isEmpty()) { return null; } List<State> errors = null; Map<String, State> keys = null; DatabaseEnvironment environment = getEnvironment(); for (State state : states) { boolean retry; RETRY: do { retry = false; if (beforeLocks) { if (!state.validate()) { if (errors == null) { errors = new ArrayList<State>(); } errors.add(state); } } else { state.clearAllErrors(); } ObjectType type = state.getType(); for (ObjectStruct struct : type != null ? new ObjectStruct[] { type, environment } : new ObjectStruct[] { environment }) { for (ObjectIndex index : struct.getIndexes()) { if (!index.isUnique()) { continue; } Object[][] valuePermutations = index.getValuePermutations(state); if (valuePermutations == null) { continue; } String indexPrefix = index.getPrefix(); String indexName = index.getUniqueName(); List<String> fields = index.getFields(); for (int i = 0, ps = valuePermutations.length; i < ps; ++ i) { Query<Object> duplicateQuery = Query. from(Object.class). where("id != ?", state.getId()). using(state.getDatabase()). referenceOnly(). noCache(). master(); StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(indexName); Object[] values = valuePermutations[i]; for (int j = 0, vs = values.length; j < vs; ++ j) { Object value = values[j]; keyBuilder.append('\0'); keyBuilder.append(value); duplicateQuery.and(indexPrefix + fields.get(j) + " = ?", values[j]); } Object duplicate = duplicateQuery.first(); if (duplicate == null) { if (!beforeLocks) { continue; } else { if (keys == null) { keys = new HashMap<String, State>(); } String key = keyBuilder.toString(); duplicate = keys.get(key); if (duplicate == null) { keys.put(key, state); continue; } else if (state.equals(State.getInstance(duplicate))) { continue; } } } OnDuplicateTrigger trigger = new OnDuplicateTrigger(index); state.fireTrigger(trigger); if (trigger.isCorrected()) { retry = true; continue RETRY; } if (errors == null) { errors = new ArrayList<State>(); } errors.add(state); state.addError( state.getField(index.getField()), "Must be unique but duplicate at " + (State.getInstance(duplicate).getId()) + "!"); } } } } while (retry); } if (errors != null && !errors.isEmpty()) { throw new ValidationException(errors); } if (keys == null || keys.isEmpty()) { return null; } else { List<DistributedLock> locks = new ArrayList<DistributedLock>(); for (String key : keys.keySet()) { locks.add(DistributedLock.Static.getInstance(this, key)); } return locks; } } /** * Called by the write methods to begin a transaction. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void beginTransaction(C connection, boolean isImmediate) throws Exception { } /** * Called by the write methods to commit the transaction. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. * @param isImmediate If {@code true}, the saved data must be * available for read immediately. */ protected void commitTransaction(C connection, boolean isImmediate) throws Exception { } /** * Called by the write methods to roll back the transaction. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void rollbackTransaction(C connection, boolean isImmediate) throws Exception { } /** * Called by the write methods to end the transaction. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void endTransaction(C connection, boolean isImmediate) throws Exception { } /** * Called by the write methods to save, index, or delete the given states. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void doWrites(C connection, boolean isImmediate, List<State> saves, List<State> indexes, List<State> deletes) throws Exception { if (saves != null && !saves.isEmpty()) { doSaves(connection, isImmediate, saves); } if (indexes != null && !indexes.isEmpty()) { doIndexes(connection, isImmediate, indexes); } if (deletes != null && !deletes.isEmpty()) { doDeletes(connection, isImmediate, deletes); } } /** * Called by the write methods to save the given {@code states}. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void doSaves(C connection, boolean isImmediate, List<State> states) throws Exception { } /** * Called by the write methods to index the given {@code states}. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void doIndexes(C connection, boolean isImmediate, List<State> states) throws Exception { } /** * Called by the write methods to delete the given {@code states}. * * @param connection {@link #openConnection Implementation-specific * connection} to the underlying database. */ protected void doDeletes(C connection, boolean isImmediate, List<State> states) throws Exception { } @SuppressWarnings("serial") private static class Retry extends Error { @Override public Throwable fillInStackTrace() { return null; } } private static final Retry RETRY_INSTANCE = new Retry(); /** * Retries the current writes. This method should only be called within * {@link #doWrites}, {@link #doSaves}, {@link #doIndexes}, or * {@link #doDeletes}. */ protected void retryWrites() { throw RETRY_INSTANCE; } /** * Implementation helper method to create a previously saved object * with the given {@code id}, of the type represented by the given * {@code typeId}, and sets common state options based on the given * {@code query}. The ID parameters may be of any UUID-like object. */ protected final <T> T createSavedObject(Object typeId, Object id, Query<T> query) { DatabaseEnvironment environment = getEnvironment(); UUID typeIdUuid = ObjectUtils.to(UUID.class, typeId); UUID idUuid = ObjectUtils.to(UUID.class, id); if (typeIdUuid == null) { Object nullType = query.getOptions().get(NULL_TYPE_QUERY_OPTION); if (nullType != null) { if (nullType instanceof ObjectType) { typeIdUuid = ((ObjectType) nullType).getId(); } else if (nullType instanceof Class) { typeIdUuid = environment.getTypeByClass((Class<?>) nullType).getId(); } else if (nullType instanceof UUID) { typeIdUuid = (UUID) nullType; } else if (nullType instanceof String) { typeIdUuid = environment.getTypeByName((String) nullType).getId(); } else { throw new IllegalArgumentException(String.format( "Can't interpret [%s] as a type!", nullType)); } } } @SuppressWarnings("unchecked") T object = (T) environment.createObject(typeIdUuid, idUuid); State objectState = State.getInstance(object); if (idUuid != null) { objectState.setStatus(StateStatus.SAVED); } objectState.getExtras().put(Database.CREATOR_EXTRA, this); objectState.getExtras().put(Query.CREATOR_EXTRA, query); if (query != null) { objectState.setDatabase(query.getDatabase()); objectState.setResolveToReferenceOnly(query.isResolveToReferenceOnly()); objectState.setResolveUsingCache(query.isCache()); objectState.setResolveUsingMaster(query.isMaster()); objectState.setResolveInvisible(query.isResolveInvisible()); if (query.isReferenceOnly()) { objectState.setStatus(StateStatus.REFERENCE_ONLY); } } return object; } @SuppressWarnings("unchecked") protected final <T> T swapObjectType(Query<T> query, T object) { DatabaseEnvironment environment = getEnvironment(); State state = State.getInstance(object); ObjectType type = state.getType(); if (type != null) { Class<?> objectClass = type.getObjectClass(); if (objectClass != null && !objectClass.isInstance(object)) { State oldState = state; object = (T) environment.createObject(state.getTypeId(), state.getId()); state = State.getInstance(object); state.setDatabase(oldState.getRealDatabase()); state.setResolveToReferenceOnly(oldState.isResolveToReferenceOnly()); state.setResolveUsingCache(oldState.isResolveUsingCache()); state.setResolveUsingMaster(oldState.isResolveUsingMaster()); state.setResolveInvisible(oldState.isResolveInvisible()); state.setStatus(oldState.getStatus()); state.setValues(oldState); state.getExtras().putAll(oldState.getExtras()); } } populateJunctions(state, environment); if (type != null) { populateJunctions(state, type); } if (object instanceof ObjectType) { ObjectType asType = environment.getTypeById(((ObjectType) object).getId()); if (asType != null && asType != object) { return (T) asType.clone(); } } return object; } private void populateJunctions(State state, ObjectStruct struct) { for (ObjectField field : struct.getFields()) { String junctionField = field.getJunctionField(); if (!ObjectUtils.isBlank(junctionField)) { state.put(field.getInternalName(), new JunctionList(state, field)); } } } @Override public String toString() { return getName(); } /** @deprecated Use {@link #TRIGGER_EXTRA_PREFIX} instead. */ @Deprecated public static final String BEFORE_SAVES_EXTRA = "db.beforeSaves"; /** @deprecated Use {@link #READ_TIMEOUT_SUB_SETTING} instead. */ @Deprecated public static final String READ_TIMEOUT_SETTING = READ_TIMEOUT_SUB_SETTING; }
package tracker.start; import tracker.models.Item; import tracker.models.Task; /** * External class EditItem. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ class EditItem extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ EditItem(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { String id = input.ask("item id for edit: "); Item item = tracker.findById(id); if (item != null) { String name = input.ask("new name: "); String description = input.ask("new description: "); item.setName(name); item.setDescription(description); tracker.update(item); System.out.println("Success edit!"); } else { System.out.println("can't find any items with id: " + id + ", please try again."); } } } /** * External class DeleteItem. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ class DeleteItem extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ DeleteItem(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { String id = input.ask("item id for delete: "); Item item = tracker.findById(id); if (item != null) { tracker.delete(item); System.out.println("Success delete!"); } else { System.out.println("can't find any items with id: " + id + ", please try again."); } } } /** * External class ExitTracker. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ class ExitTracker extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ ExitTracker(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { System.out.println("Exiting..."); } } /** * Main class MenuTracker. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ public class MenuTracker { /** * Tracker object. */ private Tracker tracker; /** * Input object. */ private Input input; /** * array with actions. */ private UserAction[] actions = new UserAction[8]; /** * array range. */ private int[] ranges = new int[7]; /** * position menu number. */ private int position = 1; /** * Constructor. * @param tracker initialisation * @param input initialisation */ public MenuTracker(Input input, Tracker tracker) { this.input = input; this.tracker = tracker; } /** * Fill menu and determine action. */ public void fillActions() { this.actions[position++] = this.new AddItem("Add new item", position - 1); this.actions[position++] = new MenuTracker.ShowAllItems("Show all items", position - 1); this.actions[position++] = new EditItem("Edit item", position - 1); this.actions[position++] = new DeleteItem("Delete item", position - 1); this.actions[position++] = new MenuTracker.FindItemById("Find item by id", position - 1); this.actions[position++] = this.new FindItemByName("Find items by name", position - 1); this.actions[position++] = new ExitTracker("Exit programm", position - 1); } /** * Fill values range. */ public void fillRange() { for (int index = 0; index != this.actions.length - 1; index++) { this.ranges[index] = index + 1; } } /** * Get values range. * @return int array */ public int[] getRanges() { return this.ranges; } /** * Select action. * @param key int number of menu */ public void select(int key) { this.actions[key].execute(this.input, this.tracker); } /** * Show all actions menu. */ public void show() { fillRange(); for (UserAction action : actions) { if (action != null) { System.out.println(action.info()); } } } /** * Internal class AddItem. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ private class AddItem extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ AddItem(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { String name = input.ask("item user name: "); String description = input.ask("item description: "); tracker.add(new Task(name, description)); } } /** * Internal static class ShowAllItems. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ private static class ShowAllItems extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ ShowAllItems(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { for (Item items : tracker.findAll()) { if (items != null) { System.out.println("name: " + items.getName() + ", "); System.out.println("description: " + items.getDescription() + ", "); System.out.println("id: " + items.getId()); } } } } /** * Internal static class FindById. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ private static class FindItemById extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ FindItemById(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { String id = input.ask("item id: "); Item item = tracker.findById(id); if (item != null) { System.out.println("name: " + item.getName() + ", "); System.out.println("description: " + item.getDescription() + ", "); System.out.println("id: " + item.getId()); } else { System.out.println("can't find any items with id: " + id + ", please try again."); } } } /** * Internal class FindByName. * @author Maxim Ignashov (mailto:ignashov.m@icloud.com) * @version 1.0 * @since 15.05.17 */ private class FindItemByName extends BaseAction { /** * Constructor. * @param name action menu name * @param key key menu action */ FindItemByName(String name, int key) { super(name, key); } /** * execute action of menu. * @param input interface for ask * @param tracker object for action with */ @Override public void execute(Input input, Tracker tracker) { String name = input.ask("item name: "); Item[] item = tracker.findByName(name); int count = 0; for (int index = 0; index != item.length; index++) { if (item[index] != null) { System.out.println("name: " + item[index].getName() + ", "); System.out.println("description: " + item[index].getDescription() + ", "); System.out.println("id: " + item[index].getId()); } else { count++; } if (count == item.length) { System.out.println("can't find any items with name: " + name + ", please try again."); } } } } }
package nl.mpi.kinnate.svg; import java.awt.Point; import nl.mpi.kinnate.kindata.EntityData; import java.util.ArrayList; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.svg.SVGDocument; public class RelationSvg { private void addUseNode(SVGDocument doc, String svgNameSpace, Element targetGroup, String targetDefId) { String useNodeId = targetDefId + "use"; Node useNodeOld = doc.getElementById(useNodeId); if (useNodeOld != null) { useNodeOld.getParentNode().removeChild(useNodeOld); } Element useNode = doc.createElementNS(svgNameSpace, "use"); useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + targetDefId); // the xlink: of "xlink:href" is required for some svg viewers to render correctly // useNode.setAttribute("href", "#" + lineIdString); useNode.setAttribute("id", useNodeId); targetGroup.appendChild(useNode); } private void updateLabelNode(SVGDocument doc, String svgNameSpace, String lineIdString, String targetRelationId) { // remove and readd the text on path label so that it updates with the new path String labelNodeId = targetRelationId + "label"; Node useNodeOld = doc.getElementById(labelNodeId); if (useNodeOld != null) { Node textParentNode = useNodeOld.getParentNode(); String labelText = useNodeOld.getTextContent(); useNodeOld.getParentNode().removeChild(useNodeOld); Element textPath = doc.createElementNS(svgNameSpace, "textPath"); textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly textPath.setAttribute("startOffset", "50%"); textPath.setAttribute("id", labelNodeId); Text textNode = doc.createTextNode(labelText); textPath.appendChild(textNode); textParentNode.appendChild(textPath); } } protected void setPolylinePointsAttribute(LineLookUpTable lineLookUpTable, String lineIdString, Element targetNode, DataTypes.RelationType relationType, float vSpacing, float egoX, float egoY, float alterX, float alterY) { float midY = (egoY + alterY) / 2; // todo: Ticket #1064 when an entity is above one that it should be below the line should make a zigzag to indicate it switch (relationType) { case affiliation: break; case ancestor: midY = alterY + vSpacing / 2; break; case descendant: midY = egoY + vSpacing / 2; break; case none: break; case sibling: // if (commonParentMaxY != null) { // midY = commonParentMaxY + vSpacing / 2; // } else { midY = (egoY < alterY) ? egoY - vSpacing / 2 : alterY - vSpacing / 2; break; case union: midY = (egoY > alterY) ? egoY + vSpacing / 2 : alterY + vSpacing / 2; break; } // if (alterY == egoY) { // // make sure that union lines go below the entities and sibling lines go above // if (relationType == DataTypes.RelationType.sibling) { // midY = alterY - vSpacing / 2; // } else if (relationType == DataTypes.RelationType.union) { // midY = alterY + vSpacing / 2; Point[] initialPointsList = new Point[]{ new Point((int) egoX, (int) egoY), new Point((int) egoX, (int) midY), new Point((int) alterX, (int) midY), new Point((int) alterX, (int) alterY) }; Point[] adjustedPointsList = lineLookUpTable.adjustLineToObstructions(lineIdString, initialPointsList); StringBuilder stringBuilder = new StringBuilder(); for (Point currentPoint : adjustedPointsList) { stringBuilder.append(currentPoint.x); stringBuilder.append(","); stringBuilder.append(currentPoint.y); stringBuilder.append(" "); } targetNode.setAttribute("points", stringBuilder.toString()); } protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, DataTypes.RelationLineType relationLineType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) { float fromBezX; float fromBezY; float toBezX; float toBezY; if ((egoX > alterX && egoY < alterY) || (egoX > alterX && egoY > alterY)) { // prevent the label on the line from rendering upside down float tempX = alterX; float tempY = alterY; alterX = egoX; alterY = egoY; egoX = tempX; egoY = tempY; } if (relationLineType == DataTypes.RelationLineType.verticalCurve) { fromBezX = egoX; fromBezY = alterY; toBezX = alterX; toBezY = egoY; // todo: update the bezier positions similar to in the follwing else statement if (1 / (egoY - alterY) < vSpacing) { fromBezX = egoX; fromBezY = alterY - vSpacing / 2; toBezX = alterX; toBezY = egoY - vSpacing / 2; } } else { fromBezX = alterX; fromBezY = egoY; toBezX = egoX; toBezY = alterY; // todo: if the nodes are almost in align then this test fails and it should insted check for proximity not equality // System.out.println(1 / (egoX - alterX)); // if (1 / (egoX - alterX) < vSpacing) { if (egoX > alterX) { if (egoX - alterX < hSpacing / 4) { fromBezX = egoX - hSpacing / 4; toBezX = alterX - hSpacing / 4; } else { fromBezX = (egoX - alterX) / 2 + alterX; toBezX = (egoX - alterX) / 2 + alterX; } } else { if (alterX - egoX < hSpacing / 4) { fromBezX = egoX + hSpacing / 4; toBezX = alterX + hSpacing / 4; } else { fromBezX = (alterX - egoX) / 2 + egoX; toBezX = (alterX - egoX) / 2 + egoX; } } } targetNode.setAttribute("d", "M " + egoX + "," + egoY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + alterX + "," + alterY); } private boolean hasCommonParent(EntityData currentNode, EntityRelation graphLinkNode) { if (graphLinkNode.relationType == DataTypes.RelationType.sibling) { for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) { if (altersRelation.relationType == DataTypes.RelationType.ancestor) { for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) { if (egosRelation.relationType == DataTypes.RelationType.ancestor) { if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) { if (altersRelation.getAlterNode().isVisible) { return true; } } } } } } } return false; } // private Float getCommonParentMaxY(EntitySvg entitySvg, EntityData currentNode, EntityRelation graphLinkNode) { // if (graphLinkNode.relationType == DataTypes.RelationType.sibling) { // Float maxY = null; // ArrayList<Float> commonParentY = new ArrayList<Float>(); // for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) { // if (altersRelation.relationType == DataTypes.RelationType.ancestor) { // for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) { // if (egosRelation.relationType == DataTypes.RelationType.ancestor) { // if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) { // float parentY = entitySvg.getEntityLocation(egosRelation.alterUniqueIdentifier)[1]; // maxY = parentY > maxY ? parentY : maxY; // return maxY; // } else { // return null; protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData currentNode, EntityRelation graphLinkNode, int hSpacing, int vSpacing) { if (graphLinkNode.relationLineType == DataTypes.RelationLineType.sanguineLine) { if (hasCommonParent(currentNode, graphLinkNode)) { return; // do not draw lines for siblings if the common parent is visible because the ancestor lines will take the place of the sibling lines } } int relationLineIndex = relationGroupNode.getChildNodes().getLength(); Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); groupNode.setAttribute("id", "relation" + relationLineIndex); Element defsNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "defs"); String lineIdString = "relation" + relationLineIndex + "Line"; new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, graphLinkNode.relationType, graphLinkNode.relationLineType, currentNode.getUniqueIdentifier(), graphLinkNode.getAlterNode().getUniqueIdentifier()); // set the line end points // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(currentNode.getUniqueIdentifier()); // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); float[] egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(currentNode.getUniqueIdentifier()); float[] alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); // float fromX = (currentNode.getxPos()); // * hSpacing + hSpacing // float fromY = (currentNode.getyPos()); // * vSpacing + vSpacing // float toX = (graphLinkNode.getAlterNode().getxPos()); // * hSpacing + hSpacing // float toY = (graphLinkNode.getAlterNode().getyPos()); // * vSpacing + vSpacing float fromX = (egoSymbolPoint[0]); // * hSpacing + hSpacing float fromY = (egoSymbolPoint[1]); // * vSpacing + vSpacing float toX = (alterSymbolPoint[0]); // * hSpacing + hSpacing float toY = (alterSymbolPoint[1]); // * vSpacing + vSpacing boolean addedRelationLine = false; switch (graphLinkNode.relationLineType) { case kinTermLine: // this case uses the following case case verticalCurve: // todo: groupNode.setAttribute("id", ); // System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos); //// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/> // Element linkLine = doc.createElementNS(svgNS, "line"); // linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing)); // linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing)); // linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing)); // linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing)); // linkLine.setAttribute("stroke", "black"); // linkLine.setAttribute("stroke-width", "1"); // // Attach the rectangle to the root 'svg' element. // svgRoot.appendChild(linkLine); //System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos); // <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/> Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path"); setPathPointsAttribute(linkLine, graphLinkNode.relationType, graphLinkNode.relationLineType, hSpacing, vSpacing, fromX, fromY, toX, toY); // linkLine.setAttribute("x1", ); // linkLine.setAttribute("y1", ); // linkLine.setAttribute("x2", ); linkLine.setAttribute("fill", "none"); if (graphLinkNode.lineColour != null) { linkLine.setAttribute("stroke", graphLinkNode.lineColour); } else { linkLine.setAttribute("stroke", "blue"); } linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); linkLine.setAttribute("id", lineIdString); defsNode.appendChild(linkLine); addedRelationLine = true; break; case sanguineLine: // Element squareLinkLine = doc.createElement("line"); // squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing)); // squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing)); // squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing)); // squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing)); // squareLinkLine.setAttribute("stroke", "grey"); // squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth)); Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, graphLinkNode.relationType, vSpacing, fromX, fromY, toX, toY); squareLinkLine.setAttribute("fill", "none"); squareLinkLine.setAttribute("stroke", "grey"); squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); squareLinkLine.setAttribute("id", lineIdString); defsNode.appendChild(squareLinkLine); addedRelationLine = true; break; } groupNode.appendChild(defsNode); if (addedRelationLine) { // insert the node that uses the above definition addUseNode(graphPanel.doc, graphPanel.svgNameSpace, groupNode, lineIdString); // add the relation label if (graphLinkNode.labelString != null) { Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("text-anchor", "middle"); // labelText.setAttribute("x", Integer.toString(labelX)); // labelText.setAttribute("y", Integer.toString(labelY)); if (graphLinkNode.lineColour != null) { labelText.setAttribute("fill", graphLinkNode.lineColour); } else { labelText.setAttribute("fill", "blue"); } labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); // labelText.setAttribute("transform", "rotate(45)"); Element textPath = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "textPath"); textPath.setAttributeNS("http://www.w3.rg/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly textPath.setAttribute("startOffset", "50%"); textPath.setAttribute("id", "relation" + relationLineIndex + "label"); Text textNode = graphPanel.doc.createTextNode(graphLinkNode.labelString); textPath.appendChild(textNode); labelText.appendChild(textPath); groupNode.appendChild(labelText); } } relationGroupNode.appendChild(groupNode); } public void updateRelationLines(GraphPanel graphPanel, ArrayList<UniqueIdentifier> draggedNodeIds, int hSpacing, int vSpacing) { // todo: if an entity is above its ancestor then this must be corrected, if the ancestor data is stored in the relationLine attributes then this would be a good place to correct this Element relationGroup = graphPanel.doc.getElementById("RelationGroup"); for (Node currentChild = relationGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { if ("g".equals(currentChild.getLocalName())) { Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); //System.out.println("idAttrubite: " + idAttrubite.getNodeValue()); DataStoreSvg.GraphRelationData graphRelationData = new DataStoreSvg().getEntitiesForRelations(currentChild); if (graphRelationData != null) { if (draggedNodeIds.contains(graphRelationData.egoNodeId) || draggedNodeIds.contains(graphRelationData.alterNodeId)) { // todo: update the relation lines //System.out.println("needs update on: " + idAttrubite.getNodeValue()); String lineElementId = idAttrubite.getNodeValue() + "Line"; Element relationLineElement = graphPanel.doc.getElementById(lineElementId); //System.out.println("type: " + relationLineElement.getLocalName()); float[] egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId); float[] alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId); // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.egoNodeId); // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.alterNodeId); float egoX = egoSymbolPoint[0]; float egoY = egoSymbolPoint[1]; float alterX = alterSymbolPoint[0]; float alterY = alterSymbolPoint[1]; // SVGRect egoSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.egoNodeId); // SVGRect alterSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.alterNodeId); // float egoX = egoSymbolRect.getX() + egoSymbolRect.getWidth() / 2; // float egoY = egoSymbolRect.getY() + egoSymbolRect.getHeight() / 2; // float alterX = alterSymbolRect.getX() + alterSymbolRect.getWidth() / 2; // float alterY = alterSymbolRect.getY() + alterSymbolRect.getHeight() / 2; if ("polyline".equals(relationLineElement.getLocalName())) { setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, graphRelationData.relationType, vSpacing, egoX, egoY, alterX, alterY); } if ("path".equals(relationLineElement.getLocalName())) { setPathPointsAttribute(relationLineElement, graphRelationData.relationType, graphRelationData.relationLineType, hSpacing, vSpacing, egoX, egoY, alterX, alterY); } addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId); updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue()); } } } } } // new RelationSvg().addTestNode(doc, (Element) relationLineElement.getParentNode().getParentNode(), svgNameSpace); // public void addTestNode(SVGDocument doc, Element addTarget, String svgNameSpace) { // Element squareNode = doc.createElementNS(svgNameSpace, "rect"); // squareNode.setAttribute("x", "100"); // squareNode.setAttribute("y", "100"); // squareNode.setAttribute("width", "20"); // squareNode.setAttribute("height", "20"); // squareNode.setAttribute("fill", "green"); // squareNode.setAttribute("stroke", "black"); // squareNode.setAttribute("stroke-width", "2"); // addTarget.appendChild(squareNode); }
package org.slc.sli.ingestion.referenceresolution; import java.util.Map; import org.milyn.Smooks; import org.milyn.payload.StringResult; import org.milyn.payload.StringSource; /** * * @author tke * */ public class SmooksExtendedReferenceResolver extends ExtendedReferenceResolver { private static Map<String, Smooks> idRefConfigs; public Map<String, Smooks> getIdRefConfigs() { return idRefConfigs; } public void setIdRefConfigs(Map<String, Smooks> idRefConfigs) { SmooksExtendedReferenceResolver.idRefConfigs = idRefConfigs; } /** * resolve the reference * * @param interchange : Name of interchange * @param element : name of element * @param reference : name of the reference * @param content : the content of the referenced element in XML format * @return : the resolved content in XML format. Null if the reference is not supported yet. */ @Override public String resolve(String interchange, String element, String reference, String content) { String key = interchange + element + reference; if (!idRefConfigs.containsKey(key)) { return null; } Smooks smooks = idRefConfigs.get(key); StringResult result = new StringResult(); StringSource source = new StringSource(content); smooks.filterSource(source, result); return result.toString(); } }
package ualberta.g12.adventurecreator; import android.app.Activity; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class OnlineStoryViewActivity extends Activity implements OnItemClickListener { private Button mainButton; private ListView listView; private StoryAuthorMapListAdapter adapter; private List<TitleAuthor> titleAuthors; private static boolean downloadMode = true; private static final String DOWNLOAD_MODE = "download_mode"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_online_story_view); loadTitleAuthors(); setUpUi(); } private void loadTitleAuthors() { /* * Once online works we are going to load our list full of the title * authors */ titleAuthors = new ArrayList<TitleAuthor>(); titleAuthors.add(new TitleAuthor("And so I cry sometimes", "when I'm lying in bed")); titleAuthors.add(new TitleAuthor("Just to get it all out,", "what's in my head")); titleAuthors.add(new TitleAuthor("And I,", "I am feeling peculiar")); titleAuthors.add(new TitleAuthor("And so I wake up in the morning", "and I step outside")); titleAuthors.add(new TitleAuthor("And I take a big breath", "and I get real high")); titleAuthors.add(new TitleAuthor("And I scream", "from the top of my lungs,")); titleAuthors.add(new TitleAuthor("What's goin' on", "ooh")); titleAuthors.add(new TitleAuthor("And I say", "hey-yeah-yeah-yeah-yeah hey-yeah-yeah")); titleAuthors.add(new TitleAuthor("I said hey", "What's going on")); titleAuthors.add(new TitleAuthor("And I say", "hey-yeah-yeah-yeah-yeah hey-yeah-yeah")); titleAuthors.add(new TitleAuthor("And I said hey", "What's going on")); titleAuthors.add(new TitleAuthor("And I try", "Oh my god, do I try")); titleAuthors.add(new TitleAuthor("I try all the time", "in this institution")); titleAuthors.add(new TitleAuthor("And I pray,", "Oh my God, do I pray")); titleAuthors.add(new TitleAuthor("I pray every single day", "FOR A REVOLUTION!")); } private void setUpUi() { mainButton = (Button) findViewById(R.id.online_story_start_main_activity); mainButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* * The only time we're ever going to be called is when * MainActivity starts us. If we finish we'll bring the user * back to the the MainActivity */ finish(); } }); listView = (ListView) findViewById(R.id.online_story_author_listview); // Set up ListView Stuff-* adapter = new StoryAuthorMapListAdapter(this, R.layout.listview_story_list, titleAuthors); listView.setAdapter(adapter); listView.setOnItemClickListener(this); } @Override public void onResume() { super.onResume(); SharedPreferences settings = getPreferences(MODE_PRIVATE); downloadMode = settings.getBoolean(DOWNLOAD_MODE, true); } @Override public void onPause() { super.onPause(); SharedPreferences settings = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(DOWNLOAD_MODE, downloadMode); // Commit them datas editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.online_story_view, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // Make sure check box is checked if it needs to be menu.findItem(R.id.online_download_mode).setChecked(downloadMode); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.online_download_mode: boolean alreadyChecked = item.isChecked(); // Set it to the opposite of what it was previously item.setChecked(!alreadyChecked); // Update the flag downloadMode = item.isChecked(); return true; default: return super.onOptionsItemSelected(item); } } /** * A holder class that contains the Title and Author of a story */ public class TitleAuthor { public final String title, author; public TitleAuthor(String t, String a) { this.title = t; this.author = a; } } @Override public void onItemClick(AdapterView<?> parent, View v, int pos, long id) { // Download or stream story TitleAuthor ta = titleAuthors.get(pos); if (downloadMode) { // Download story lol Toast.makeText(this, String.format("Downloading story %s", ta.title), Toast.LENGTH_SHORT).show(); DownloadStory ds = new DownloadStory(); ds.execute(new TitleAuthor[] {ta}); } else { // Stream story Toast.makeText(this, String.format("Loading story %s", ta.title), Toast.LENGTH_SHORT) .show(); // Send some stuff to FragmentViewActivity } } private class DownloadStory extends AsyncTask<TitleAuthor, Void, String> { private Story s; @SuppressWarnings("unused") @Override protected String doInBackground(TitleAuthor... params) { // TODO Actually download the story here - this thread will actually do something s = new Story(params[0].title, params[0].author); // Once we're actually downloading the story this will matter if (true) { return String.format("%s Download complete", params[0].title); } else { return String.format("%s Download Failed", params[0].title); } } @Override protected void onCancelled() { Toast.makeText(getApplicationContext(), "Story Download Cancelled", Toast.LENGTH_SHORT).show(); super.onCancelled(); } @Override protected void onPostExecute(String result) { StoryListController slc = AdventureCreator.getStoryListController(); // Add the story to the list slc.addStory(s); OfflineIOHelper offlineHelper = AdventureCreator.getOfflineIOHelper(); // Save our list of stories offlineHelper.saveOfflineStories(AdventureCreator.getStoryList()); Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); super.onPostExecute(result); } } }
package edu.grinnell.csc207.zhangshe.hello; public class HelloWorld { public static void main (String[] args) { System.out.println ("Hello!!"); System.out.println ("Hello, GitHub!!!"); } // main(String[]) }
package com.pushtorefresh.storio.contentresolver.operation.put; import android.content.ContentValues; import android.support.annotation.NonNull; import com.pushtorefresh.storio.contentresolver.StorIOContentResolver; import rx.Observable; import rx.Subscriber; import static com.pushtorefresh.storio.util.Checks.checkNotNull; /** * Prepared Put Operation for {@link ContentValues} */ public class PreparedPutContentValues extends PreparedPut<ContentValues, PutResult> { @NonNull private final ContentValues contentValues; PreparedPutContentValues(@NonNull StorIOContentResolver storIOContentResolver, @NonNull PutResolver<ContentValues> putResolver, @NonNull ContentValues contentValues) { super(storIOContentResolver, putResolver); this.contentValues = contentValues; } /** * Executes Put Operation immediately in current thread * * @return non-null result of Put Operation */ @NonNull @Override public PutResult executeAsBlocking() { final PutResult putResult = putResolver.performPut(storIOContentResolver, contentValues); putResolver.afterPut(contentValues, putResult); return putResult; } /** * Creates {@link Observable} which will perform Put Operation and send result to observer * * @return non-null {@link Observable} which will perform Put Operation and send result to observer */ @NonNull @Override public Observable<PutResult> createObservable() { return Observable.create(new Observable.OnSubscribe<PutResult>() { @Override public void call(Subscriber<? super PutResult> subscriber) { final PutResult putResult = executeAsBlocking(); if (!subscriber.isUnsubscribed()) { subscriber.onNext(putResult); subscriber.onCompleted(); } } }); } /** * Builder for {@link PreparedPutContentValues} * <p> * Required: You should specify put resolver see {@link #withPutResolver(PutResolver)} */ public static class Builder { @NonNull final StorIOContentResolver storIOContentResolver; @NonNull final ContentValues contentValues; PutResolver<ContentValues> putResolver; /** * Creates builder for {@link PreparedPutContentValues} * * @param storIOContentResolver instance of {@link StorIOContentResolver} * @param contentValues some {@link ContentValues} to put */ public Builder(@NonNull StorIOContentResolver storIOContentResolver, @NonNull ContentValues contentValues) { checkNotNull(storIOContentResolver, "Please specify StorIOContentResolver"); checkNotNull(contentValues, "Please specify content values"); this.storIOContentResolver = storIOContentResolver; this.contentValues = contentValues; } /** * Required: Specifies resolver for Put Operation * that should define behavior of Put Operation: insert or update of the {@link ContentValues} * * @param putResolver resolver for Put Operation * @return builder */ @NonNull public CompleteBuilder withPutResolver(@NonNull PutResolver<ContentValues> putResolver) { this.putResolver = putResolver; return new CompleteBuilder(this); } } /** * Builder for {@link PreparedPutContentValues} */ public static class CompleteBuilder extends Builder { CompleteBuilder(@NonNull final Builder builder) { super(builder.storIOContentResolver, builder.contentValues); } /** * {@inheritDoc} */ @NonNull @Override public CompleteBuilder withPutResolver(@NonNull PutResolver<ContentValues> putResolver) { super.withPutResolver(putResolver); return this; } /** * Builds instance of {@link PreparedPutContentValues} * * @return instance of {@link PreparedPutContentValues} */ @NonNull public PreparedPutContentValues prepare() { checkNotNull(putResolver, "Please specify put resolver"); return new PreparedPutContentValues( storIOContentResolver, putResolver, contentValues ); } } }
package com.systematic.trading.backtest.display.file; import java.math.BigDecimal; import java.text.DecimalFormat; import java.time.LocalDate; import java.time.Period; import com.systematic.trading.simulation.analysis.roi.event.ReturnOnInvestmentEvent; import com.systematic.trading.simulation.analysis.roi.event.ReturnOnInvestmentEventListener; /** * Outputs the ROI to the console. * * @author CJ Hare */ public class FileReturnOnInvestmentDisplay implements ReturnOnInvestmentEventListener { enum RETURN_ON_INVESTMENT_DISPLAY { DAILY, MONTHLY, YEARLY, ALL; } private static final DecimalFormat TWO_DECIMAL_PLACES = new DecimalFormat(" /** Display responsible for handling the file output. */ private final FileDisplayMultithreading display; private final RETURN_ON_INVESTMENT_DISPLAY roiType; public FileReturnOnInvestmentDisplay(final RETURN_ON_INVESTMENT_DISPLAY roiType, final FileDisplayMultithreading display) { this.display = display; this.roiType = roiType; display.write("=== Return On Investment Events ==="); } public String createOutput( final ReturnOnInvestmentEvent event ) { final StringBuilder output = new StringBuilder(); final BigDecimal percentageChange = event.getPercentageChange(); final LocalDate startDateInclusive = event.getExclusiveStartDate(); final LocalDate endDateExclusive = event.getInclusiveEndDate(); final String formattedPercentageChange = TWO_DECIMAL_PLACES.format(percentageChange); final Period elapsed = Period.between(startDateInclusive, endDateExclusive); if (isDailyRoiOutput(elapsed)) { output.append(String.format("Daily - ROI: %s percent over %s day(s), from %s to %s", formattedPercentageChange, elapsed.getDays(), startDateInclusive, endDateExclusive)); } if (isMonthlyRoiOutput(elapsed)) { output.append(String.format("Monthly - ROI: %s percent over %s month(s), from %s to %s", formattedPercentageChange, getRoundedMonths(elapsed), startDateInclusive, endDateExclusive)); } if (isYearlyRoiOutput(elapsed)) { output.append(String.format("Yearly - ROI: %s percent over %s year(s), from %s to %s", formattedPercentageChange, getRoundedYears(elapsed), startDateInclusive, endDateExclusive)); } return output.toString(); } private boolean isDailyRoiOutput( final Period elapsed ) { switch (roiType) { case ALL: case DAILY: return hasMostlyDays(elapsed); default: return false; } } private boolean hasMostlyDays( final Period elapsed ) { return elapsed.getDays() > 0 && getRoundedMonths(elapsed) == 0 && getRoundedYears(elapsed) == 0; } private boolean isMonthlyRoiOutput( final Period elapsed ) { switch (roiType) { case ALL: case MONTHLY: return hasMostlyMonths(elapsed); default: return false; } } private boolean hasMostlyMonths( final Period elapsed ) { return getRoundedMonths(elapsed) > 0 && getRoundedYears(elapsed) == 0; } private int getRoundedMonths( final Period elapsed ) { return elapsed.getDays() > 20 ? elapsed.getMonths() + 1 : elapsed.getMonths(); } private boolean isYearlyRoiOutput( final Period elapsed ) { switch (roiType) { case ALL: case YEARLY: return getRoundedYears(elapsed) > 0; default: return false; } } private int getRoundedYears( final Period elapsed ) { return elapsed.getDays() > 20 && elapsed.getMonths() == 11 ? elapsed.getYears() + 1 : elapsed.getYears(); } @Override public void event( final ReturnOnInvestmentEvent event ) { display.write(createOutput((ReturnOnInvestmentEvent) event)); } }
package org.eclipse.persistence.tools.workbench.ant; import java.io.PrintStream; import org.apache.tools.ant.BuildException; import org.eclipse.persistence.exceptions.DatabaseException; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.internal.sessions.factories.XMLSessionConfigLoader; import org.eclipse.persistence.sessions.DatabaseLogin; import org.eclipse.persistence.sessions.DatabaseSession; import org.eclipse.persistence.sessions.factories.SessionManager; public class SessionValidator extends ProjectRunner implements SessionValidatorInterface { private DatabaseSession databaseSession; public SessionValidator() { super(); } public SessionValidator( PrintStream log) { super( log); } /** * Test TopLink deployment descriptor XML by running TopLink * * @return 0 if the there is no error in the project. */ public int execute( String sessionName, String sessionsFileName, String url, String driverclass, String user, String password) { int status = 0; try { this.login( sessionName, sessionsFileName, url, driverclass, user, password); } catch ( DatabaseException e) { String msg = ( e.getMessage() == null) ? e.toString() : e.getMessage(); throw new BuildException( this.stringRepository.getString( "couldNotLogin", msg), e); } catch( Throwable e) { Throwable t = ( e.getCause() == null) ? e : e.getCause(); String msg = ( t.getMessage() == null) ? t.toString() : t.getMessage(); throw new BuildException( this.stringRepository.getString( "errorWhileValidating", msg), e); } finally { this.logout(); } return status; } private void login( String sessionName, String sessionsFileName, String url, String driverclass, String user, String password) { this.databaseSession = ( DatabaseSession)SessionManager.getManager(). getSession( new XMLSessionConfigLoader( sessionsFileName), sessionName, PrivilegedAccessHelper.getClassLoaderForClass( getClass()), false, false, false); DatabaseLogin sessionLogin = this.databaseSession.getLogin(); if( url != "") { if( url != "") sessionLogin.setDatabaseURL( url); if( driverclass != "") sessionLogin.setDriverClassName( driverclass); if( user != "") sessionLogin.setUserName( user); if( password != "") sessionLogin.setPassword( password); } this.databaseSession.login( sessionLogin); } private void logout() { if( this.databaseSession != null) { this.databaseSession.logout(); } } }
package org.elasticsearch.xpack.core.indexlifecycle.action; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Objects; public class RemoveIndexLifecyclePolicyAction extends Action<RemoveIndexLifecyclePolicyAction.Request, RemoveIndexLifecyclePolicyAction.Response, RemovePolicyForIndexActionRequestBuilder> { public static final RemoveIndexLifecyclePolicyAction INSTANCE = new RemoveIndexLifecyclePolicyAction(); public static final String NAME = "indices:admin/ilm/remove_policy"; protected RemoveIndexLifecyclePolicyAction() { super(NAME); } @Override public RemoveIndexLifecyclePolicyAction.Response newResponse() { return new Response(); } public static class Response extends ActionResponse implements ToXContentObject { public static final ParseField HAS_FAILURES_FIELD = new ParseField("has_failures"); public static final ParseField FAILED_INDEXES_FIELD = new ParseField("failed_indexes"); @SuppressWarnings("unchecked") public static final ConstructingObjectParser<Response, Void> PARSER = new ConstructingObjectParser<>( "change_policy_for_index_response", a -> new Response((List<String>) a[0])); static { PARSER.declareStringArray(ConstructingObjectParser.constructorArg(), FAILED_INDEXES_FIELD); // Needs to be declared but not used in constructing the response object PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), HAS_FAILURES_FIELD); } private List<String> failedIndexes; public Response() { } public Response(List<String> failedIndexes) { if (failedIndexes == null) { throw new IllegalArgumentException(FAILED_INDEXES_FIELD.getPreferredName() + " cannot be null"); } this.failedIndexes = failedIndexes; } public List<String> getFailedIndexes() { return failedIndexes; } public boolean hasFailures() { return failedIndexes.isEmpty() == false; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(HAS_FAILURES_FIELD.getPreferredName(), hasFailures()); builder.field(FAILED_INDEXES_FIELD.getPreferredName(), failedIndexes); builder.endObject(); return builder; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); failedIndexes = in.readList(StreamInput::readString); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringList(failedIndexes); } @Override public int hashCode() { return Objects.hash(failedIndexes); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Response other = (Response) obj; return Objects.equals(failedIndexes, other.failedIndexes); } } public static class Request extends AcknowledgedRequest<Request> implements IndicesRequest.Replaceable { private String[] indices; private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpen(); public Request() { } public Request(String... indices) { if (indices == null) { throw new IllegalArgumentException("indices cannot be null"); } this.indices = indices; } @Override public Request indices(String... indices) { this.indices = indices; return this; } @Override public String[] indices() { return indices; } public void indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; } public IndicesOptions indicesOptions() { return indicesOptions; } @Override public ActionRequestValidationException validate() { return null; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArray(indices); indicesOptions.writeIndicesOptions(out); } @Override public int hashCode() { return Objects.hash(Arrays.hashCode(indices), indicesOptions); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Request other = (Request) obj; return Objects.deepEquals(indices, other.indices) && Objects.equals(indicesOptions, other.indicesOptions); } } @Override public RemovePolicyForIndexActionRequestBuilder newRequestBuilder(final ElasticsearchClient client) { return new RemovePolicyForIndexActionRequestBuilder(client, INSTANCE); } }
package org.fusesource.mop.support; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.kahadb.index.BTreeIndex; import org.apache.kahadb.page.Page; import org.apache.kahadb.page.PageFile; import org.apache.kahadb.page.Transaction; import org.apache.kahadb.util.LockFile; import org.apache.kahadb.util.Marshaller; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.channels.FileChannel; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author chirino */ public class Database { private static final transient Log LOG = LogFactory.getLog(Database.class); private PageFile pageFile; private boolean readOnly; private File directroy; private LockFile lock; private long lockRetryTimeout = 500; private long maximumRetryTime = 60 * 1000; protected int logRetryCountEvery = 50; public void delete() throws IOException { getReadOnlyFile().delete(); getUpdateFile().delete(); getUpdateRedoFile().delete(); } public void open(boolean readOnly) throws IOException { if (pageFile != null && pageFile.isLoaded()) { throw new IllegalStateException("database allready opened."); } this.readOnly = readOnly; if (!getReadOnlyFile().exists()) { initialize(); } if (readOnly) { pageFile = new PageFile(directroy, "index"); pageFile.setEnableWriteThread(false); pageFile.setEnableRecoveryFile(false); } else { lock = new LockFile(getUpdateFile(), false); lock(); pageFile = new PageFile(directroy, "update"); pageFile.setEnableWriteThread(false); pageFile.setEnableRecoveryFile(true); } pageFile.load(); } protected void lock() throws IOException { long timeoutTime = System.currentTimeMillis() + maximumRetryTime; for (int i = 0; true; i++) { try { lock.lock(); return; } catch (IOException e) { long now = System.currentTimeMillis(); if (now > timeoutTime) { LOG.info("Tried to lock the file " + lock + " " + i + " time(s) but failed " + e); throw e; } if (i > 0 && i % logRetryCountEvery == 0) { LOG.info("retrying lock attempt " + i + " on " + lock); } try { Thread.sleep(lockRetryTimeout); } catch (InterruptedException e1) { // ignore } } } } public void close() throws IOException { try { // TODO is this valid? //assertOpen(); if (pageFile != null) { if (pageFile.isLoaded()) { pageFile.flush(); pageFile.unload(); } else { LOG.warn("database was not loaded yet am about to close it", new Exception()); } pageFile = null; } } finally { if (!readOnly) { copy(getUpdateFile(), getReadOnlyFile()); lock.unlock(); lock = null; } } } public void beginInstall(final String id) throws IOException { assertOpen(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); root.installingArtifact = id; root.tx_sequence++; root.store(tx); } }); pageFile.flush(); } public void installDone() { try { assertOpen(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); root.installingArtifact = null; root.tx_sequence++; root.store(tx); } }); pageFile.flush(); } catch (Throwable e) { } } public void install(final LinkedHashSet<String> artifiactIds) throws IOException { if (artifiactIds.isEmpty()) { throw new IllegalArgumentException("artifiactIds cannot be empty"); } final String mainArtifact = artifiactIds.iterator().next(); assertOpen(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> artifacts = root.artifacts.get(tx); BTreeIndex<String, HashSet<String>> artifactIdIndex = root.artifactIdIndex.get(tx); BTreeIndex<String, HashSet<String>> typeIndex = root.typeIndex.get(tx); BTreeIndex<String, HashSet<String>> explicityInstalledArtifacts = root.explicityInstalledArtifacts.get(tx); explicityInstalledArtifacts.put(tx, mainArtifact, new LinkedHashSet<String>(artifiactIds)); for (String id : artifiactIds) { ArtifactId a = new ArtifactId(); if (!a.strictParse(id)) { throw new IOException("Invalid artifact id: " + id); } HashSet<String> rc = artifacts.get(tx, id); if (rc == null) { rc = new HashSet<String>(); rc.add(mainArtifact); artifacts.put(tx, id, rc); indexAdd(tx, artifactIdIndex, id, a.getArtifactId()); indexAdd(tx, typeIndex, id, a.getType()); } else { rc.add(mainArtifact); artifacts.put(tx, id, rc); } } root.tx_sequence++; root.store(tx); } }); } public TreeSet<String> uninstall(final String mainArtifact) throws IOException { assertOpen(); return pageFile.tx().execute(new Transaction.CallableClosure<TreeSet<String>, IOException>() { public TreeSet<String> execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> artifacts = root.artifacts.get(tx); BTreeIndex<String, HashSet<String>> artifactIdIndex = root.artifactIdIndex.get(tx); BTreeIndex<String, HashSet<String>> typeIndex = root.typeIndex.get(tx); BTreeIndex<String, HashSet<String>> explicityInstalledArtifacts = root.explicityInstalledArtifacts.get(tx); TreeSet<String> unused = new TreeSet<String>(); HashSet<String> artifiactIds = explicityInstalledArtifacts.remove(tx, mainArtifact); for (String id : artifiactIds) { ArtifactId a = new ArtifactId(); if (!a.strictParse(id)) { throw new IOException("Invalid artifact id: " + id); } HashSet<String> rc = artifacts.get(tx, id); rc.remove(mainArtifact); if (rc.isEmpty()) { unused.add(id); artifacts.remove(tx, id); indexRemove(tx, artifactIdIndex, id, a.getArtifactId()); indexRemove(tx, typeIndex, id, a.getType()); } else { artifacts.put(tx, id, rc); } } root.tx_sequence++; root.store(tx); return unused; } }); } private void indexRemove(Transaction tx, BTreeIndex<String, HashSet<String>> artifactIdIndex, String id, String artifactId) { } public Set<String> findByArtifactId(final String artifactId) throws IOException { assertOpen(); return pageFile.tx().execute(new Transaction.CallableClosure<Set<String>, IOException>() { public Set<String> execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> artifactIdIndex = root.artifactIdIndex.get(tx); HashSet<String> set = artifactIdIndex.get(tx, artifactId); return set == null ? new HashSet() : new HashSet(set); } }); } public static Map<String, Set<String>> groupByGroupId(Set<String> values) { Map<String, Set<String>> rc = new LinkedHashMap<String, Set<String>>(); for (String value : values) { ArtifactId id = new ArtifactId(); id.strictParse(value); Set<String> t = rc.get(id.getGroupId()); if (t == null) { t = new LinkedHashSet(5); rc.put(id.getGroupId(), t); } t.add(value); } return rc; } public Set<String> findByType(final String type) throws IOException { assertOpen(); return pageFile.tx().execute(new Transaction.CallableClosure<Set<String>, IOException>() { public Set<String> execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> typeIndex = root.typeIndex.get(tx); HashSet<String> set = typeIndex.get(tx, type); return set == null ? new HashSet() : new HashSet(set); } }); } public TreeSet<String> listAll() throws IOException { assertOpen(); return pageFile.tx().execute(new Transaction.CallableClosure<TreeSet<String>, IOException>() { public TreeSet<String> execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> artifacts = root.artifacts.get(tx); Iterator<Map.Entry<String, HashSet<String>>> i = artifacts.iterator(tx); TreeSet<String> rc = new TreeSet<String>(); while (i.hasNext()) { Map.Entry<String, HashSet<String>> entry = i.next(); rc.add(entry.getKey()); } return rc; } }); } public TreeSet<String> listInstalled() throws IOException { assertOpen(); return pageFile.tx().execute(new Transaction.CallableClosure<TreeSet<String>, IOException>() { public TreeSet<String> execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> explicityInstalledArtifacts = root.explicityInstalledArtifacts.get(tx); Iterator<Map.Entry<String, HashSet<String>>> i = explicityInstalledArtifacts.iterator(tx); TreeSet<String> rc = new TreeSet<String>(); while (i.hasNext()) { Map.Entry<String, HashSet<String>> entry = i.next(); rc.add(entry.getKey()); } return rc; } }); } public TreeSet<String> listDependenants(final String artifact) throws IOException { assertOpen(); return pageFile.tx().execute(new Transaction.CallableClosure<TreeSet<String>, IOException>() { public TreeSet<String> execute(Transaction tx) throws IOException { RootEntity root = RootEntity.load(tx); BTreeIndex<String, HashSet<String>> artifacts = root.artifacts.get(tx); HashSet<String> deps = artifacts.get(tx, artifact); if (deps == null) { return null; } TreeSet<String> rc = new TreeSet<String>(); rc.addAll(deps); rc.remove(artifact); return rc; } }); } // helper methods static private void indexAdd(Transaction tx, BTreeIndex<String, HashSet<String>> index, String pk, String field) throws IOException { HashSet<String> ids = index.get(tx, field); if (ids == null) { ids = new HashSet<String>(); } ids.add(pk); index.put(tx, field, ids); } private void assertOpen() { if (pageFile == null || !pageFile.isLoaded()) { throw new IllegalStateException("database not opened."); } } private void initialize() throws IOException { lock = new LockFile(getUpdateFile(), false); lock(); try { // Now that we have the lock.. lets check again.. if (getReadOnlyFile().exists()) { return; } pageFile = new PageFile(directroy, "update"); pageFile.setEnableWriteThread(false); pageFile.setEnableRecoveryFile(true); pageFile.load(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { RootEntity root = new RootEntity(); root.create(tx); } }); pageFile.flush(); ; pageFile.unload(); pageFile = null; copy(getUpdateFile(), getReadOnlyFile()); } finally { lock.unlock(); lock = null; } } static private void copy(File from, File to) throws IOException { to.delete(); FileChannel in = new FileInputStream(from).getChannel(); try { File tmp = File.createTempFile(to.getName(), ".part", to.getParentFile()); FileChannel out = new FileOutputStream(tmp).getChannel(); try { out.transferFrom(in, 0, from.length()); } finally { out.close(); } tmp.renameTo(to); } finally { in.close(); } } private File getUpdateFile() { return new File(directroy, "update.data"); } private File getUpdateRedoFile() { return new File(directroy, "update.redo"); } private File getReadOnlyFile() { return new File(directroy, "index.data"); } // Properties... public File getDirectroy() { return directroy; } public void setDirectroy(File directroy) { this.directroy = directroy; } // Helper Classes static private class RootEntity implements Serializable { private static final long serialVersionUID = -3845184822064658540L; static Marshaller<RootEntity> MARSHALLER = new ObjectMarshaller<RootEntity>(); protected String installingArtifact; protected long tx_sequence; // This is map of the artifcact -> set of it's transitive dependencies. protected BTreeIndexReference<String, HashSet<String>> explicityInstalledArtifacts = new BTreeIndexReference<String, HashSet<String>>(); // This is map of the artifcact -> set of installed artifacts that depend on it. protected BTreeIndexReference<String, HashSet<String>> artifacts = new BTreeIndexReference<String, HashSet<String>>(); // This is map of the artifcactId -> set of artifacts that have the artifact id protected BTreeIndexReference<String, HashSet<String>> artifactIdIndex = new BTreeIndexReference<String, HashSet<String>>(); // This is map of the type -> set of artifacts that have the type protected BTreeIndexReference<String, HashSet<String>> typeIndex = new BTreeIndexReference<String, HashSet<String>>(); public void create(Transaction tx) throws IOException { // Allocate the root page. Page<RootEntity> page = tx.allocate(); if (page.getPageId() != 0) { throw new IOException("RootEntity could not allocate page 0"); } explicityInstalledArtifacts.create(tx); artifacts.create(tx); artifactIdIndex.create(tx); typeIndex.create(tx); page.set(this); tx.store(page, MARSHALLER, true); } static RootEntity load(Transaction tx) throws IOException { Page<RootEntity> rootPage = tx.load(0, RootEntity.MARSHALLER); return rootPage.get(); } public void store(Transaction tx) throws IOException { Page<RootEntity> rootPage = tx.load(0, RootEntity.MARSHALLER); rootPage.set(this); tx.store(rootPage, RootEntity.MARSHALLER, true); } } static private class BTreeIndexReference<K, V> implements Serializable { private static final long serialVersionUID = 3875822596923539147L; protected long pageId; transient protected BTreeIndex<K, V> index; public BTreeIndex<K, V> get(Transaction tx) throws IOException { if (index == null) { index = new BTreeIndex<K, V>(tx.getPageFile(), pageId); index.setKeyMarshaller(new ObjectMarshaller<K>()); index.setValueMarshaller(new ObjectMarshaller<V>()); index.load(tx); } return index; } public void create(Transaction tx) throws IOException { pageId = tx.allocate().getPageId(); } } static private class ObjectMarshaller<T> implements org.apache.kahadb.util.Marshaller<T> { public void writePayload(T object, DataOutput dataOutput) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(baos); os.writeObject(object); os.close(); byte[] data = baos.toByteArray(); dataOutput.writeInt(data.length); dataOutput.write(data); } public T readPayload(DataInput dataInput) throws IOException { byte data[] = new byte[dataInput.readInt()]; dataInput.readFully(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream os = new ObjectInputStream(bais); T object = null; try { object = (T) os.readObject(); } catch (ClassNotFoundException e) { throw new IOException(e.getMessage()); } return object; } public int getFixedSize() { return 0; } public boolean isDeepCopySupported() { return false; } public T deepCopy(T object) { return null; } } }
package org.eclipse.birt.report.item.crosstab.core.re.executor; import java.util.ArrayList; import java.util.List; import javax.olap.OLAPException; import javax.olap.cursor.DimensionCursor; import javax.olap.cursor.EdgeCursor; import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants; import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle; import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.LevelHandle; /** * GroupUtil */ public class GroupUtil implements ICrosstabConstants { /** * Prevent from instantiation */ private GroupUtil( ) { } /** * Returns the accumulated group index for current level element. * * @param crosstabItem * @param axisType * @param dimensionIndex * @param levelIndex * If this is negative(<0), means the last level index in given * dimension. * @return */ public static int getGroupIndex( CrosstabReportItemHandle crosstabItem, int axisType, int dimensionIndex, int levelIndex ) { List<EdgeGroup> groups = getGroups( crosstabItem, axisType ); if ( levelIndex < 0 ) { for ( int i = groups.size( ) - 1; i >= 0; i { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == dimensionIndex ) { return i; } } } else { for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == dimensionIndex && gp.levelIndex == levelIndex ) { return i; } } } return -1; } /** * Returns the accumulated group index for current level element from given * group list. The search is done by comparing dimension name and level name * from given handle. Caller must ensure the name is valid. * * @param groups * @param levelHandle * @param levelIndex * @return */ public static int getGroupIndex( List<EdgeGroup> groups, LevelHandle levelHandle ) { if ( groups != null && levelHandle != null && levelHandle.getContainer( ) != null ) { DimensionHandle dimensionHandle = (DimensionHandle) levelHandle.getContainer( ) .getContainer( ); if ( dimensionHandle != null ) { for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); // use qualified name for dimension but full name for level, // because dimension name is globally unique if ( dimensionHandle.getQualifiedName( ) .equals( gp.dimensionName ) && levelHandle.getFullName( ).equals( gp.levelName ) ) { return i; } } } } return -1; } /** * Returns the accumulated group index for current level element from given * group list. * * @param groups * @param dimensionIndex * @param levelIndex * If this is negative(<0), means the last level index in given * dimension. * @return */ public static int getGroupIndex( List<EdgeGroup> groups, int dimensionIndex, int levelIndex ) { if ( levelIndex < 0 ) { for ( int i = groups.size( ) - 1; i >= 0; i { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == dimensionIndex ) { return i; } } } else { for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == dimensionIndex && gp.levelIndex == levelIndex ) { return i; } } } return -1; } /** * Returns the span between current group to last group. */ public static int computeGroupSpan( List<EdgeGroup> groups, int dimensionIndex, int levelIndex ) { int currentGroup = -1; for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == dimensionIndex && gp.levelIndex == levelIndex ) { currentGroup = i; break; } } if ( currentGroup == -1 ) { return 1; } return groups.size( ) - currentGroup - 1; } /** * Checks if the crosstab has any corresponding aggregation cell defined for * specific level. */ public static boolean hasTotalContent( CrosstabReportItemHandle crosstabItem, int axisType, int dimX, int levelX, int meaX ) { if ( !IColumnWalker.IGNORE_TOTAL_COLUMN_WITHOUT_AGGREGATION ) { return true; } // TODO skip invisible levels int mCount = crosstabItem.getMeasureCount( ); if ( mCount == 0 ) { return !IColumnWalker.IGNORE_TOTAL_COLUMN_WITHOUT_MEASURE; } int rdCount = crosstabItem.getDimensionCount( ROW_AXIS_TYPE ); int cdCount = crosstabItem.getDimensionCount( COLUMN_AXIS_TYPE ); boolean checkAllMeasure = meaX < 0 || meaX >= mCount; int startMeasure = meaX; int endMeasure = meaX + 1; if ( checkAllMeasure ) { startMeasure = 0; endMeasure = mCount; } if ( startMeasure >= endMeasure ) { return false; } if ( axisType == COLUMN_AXIS_TYPE ) { if ( rdCount == 0 ) { // default as grand total String colDimName = null; String colLevelName = null; if ( dimX >= 0 && levelX >= 0 ) { // sub total DimensionViewHandle cdv = crosstabItem.getDimension( COLUMN_AXIS_TYPE, dimX ); LevelViewHandle clv = cdv.getLevel( levelX ); colDimName = cdv.getCubeDimensionName( ); colLevelName = clv.getCubeLevelName( ); } return hasAggregationCell( startMeasure, endMeasure, crosstabItem, null, null, colDimName, colLevelName ); } else { for ( int i = 0; i < rdCount; i++ ) { DimensionViewHandle rdv = crosstabItem.getDimension( ROW_AXIS_TYPE, i ); for ( int j = 0; j < rdv.getLevelCount( ); j++ ) { LevelViewHandle rlv = rdv.getLevel( j ); // default as grand total String colDimName = null; String colLevelName = null; if ( dimX >= 0 && levelX >= 0 ) { // sub total DimensionViewHandle cdv = crosstabItem.getDimension( COLUMN_AXIS_TYPE, dimX ); LevelViewHandle clv = cdv.getLevel( levelX ); colDimName = cdv.getCubeDimensionName( ); colLevelName = clv.getCubeLevelName( ); } if ( hasAggregationCell( startMeasure, endMeasure, crosstabItem, rdv.getCubeDimensionName( ), rlv.getCubeLevelName( ), colDimName, colLevelName ) ) { return true; } } } } } else { if ( cdCount == 0 ) { // default as grand total String rowDimName = null; String rowLevelName = null; if ( dimX >= 0 && levelX >= 0 ) { // sub total DimensionViewHandle rdv = crosstabItem.getDimension( ROW_AXIS_TYPE, dimX ); LevelViewHandle rlv = rdv.getLevel( levelX ); rowDimName = rdv.getCubeDimensionName( ); rowLevelName = rlv.getCubeLevelName( ); } return hasAggregationCell( startMeasure, endMeasure, crosstabItem, rowDimName, rowLevelName, null, null ); } else { for ( int i = 0; i < cdCount; i++ ) { DimensionViewHandle cdv = crosstabItem.getDimension( COLUMN_AXIS_TYPE, i ); for ( int j = 0; j < cdv.getLevelCount( ); j++ ) { LevelViewHandle clv = cdv.getLevel( j ); // default as grand total String rowDimName = null; String rowLevelName = null; if ( dimX >= 0 && levelX >= 0 ) { // sub total DimensionViewHandle rdv = crosstabItem.getDimension( ROW_AXIS_TYPE, dimX ); LevelViewHandle rlv = rdv.getLevel( levelX ); rowDimName = rdv.getCubeDimensionName( ); rowLevelName = rlv.getCubeLevelName( ); } if ( hasAggregationCell( startMeasure, endMeasure, crosstabItem, rowDimName, rowLevelName, cdv.getCubeDimensionName( ), clv.getCubeLevelName( ) ) ) { return true; } } } } } return false; } private static boolean hasAggregationCell( int startMeasure, int endMeasure, CrosstabReportItemHandle crosstabItem, String rowDimensionName, String rowLevelName, String columnDimensionName, String columnLevelName ) { for ( int k = startMeasure; k < endMeasure; k++ ) { AggregationCellHandle cell = crosstabItem.getMeasure( k ) .getAggregationCell( rowDimensionName, rowLevelName, columnDimensionName, columnLevelName ); if ( cell != null ) { return true; } } return false; } /** * Returns a list of groups on specific axis. */ public static List<EdgeGroup> getGroups( CrosstabReportItemHandle crosstabItem, int axisType ) { List<EdgeGroup> groups = new ArrayList<EdgeGroup>( ); int dimCount = crosstabItem.getDimensionCount( axisType ); if ( dimCount > 0 ) { // TODO filter invisible levels for ( int i = 0; i < dimCount; i++ ) { DimensionViewHandle dv = crosstabItem.getDimension( axisType, i ); for ( int j = 0; j < dv.getLevelCount( ); j++ ) { groups.add( new EdgeGroup( i, j, dv.getCubeDimensionName( ), dv.getLevel( j ).getCubeLevelName( ) ) ); } } } return groups; } /** * Check if this group is a leaf group, e.g. the innerest non-dummy group. */ public static boolean isLeafGroup( List<DimensionCursor> groupCursors, int groupIndex ) throws OLAPException { for ( int i = groupIndex + 1; i < groupCursors.size( ); i++ ) { DimensionCursor dc = groupCursors.get( i ); if ( !isDummyGroup( dc ) ) { return false; } } return true; } /** * Checks if given dimension cusor is associated with a dummy group */ public static boolean isDummyGroup( DimensionCursor dc ) throws OLAPException { // // check special edge start/end value for dummy group // return dc.getEdgeStart( ) == -1 && dc.getEdgeEnd( ) == -1; // now use 'extent' to determine if this is a dummy group return dc.getExtent( ) == -1; } /** * Returns the previous group on specific axis */ public static EdgeGroup getPreviousGroup( List<EdgeGroup> groups, int currentDimensionIndex, int currentLevelIndex ) { int currentGroup = -1; for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == currentDimensionIndex && gp.levelIndex == currentLevelIndex ) { currentGroup = i; break; } } if ( currentGroup > 0 && currentGroup < groups.size( ) ) { return groups.get( currentGroup - 1 ); } return null; } /** * Returns the next group on given group list. */ public static EdgeGroup getNextGroup( List<EdgeGroup> groups, int currentDimensionIndex, int currentLevelIndex ) { int currentGroup = -1; for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == currentDimensionIndex && gp.levelIndex == currentLevelIndex ) { currentGroup = i; break; } } if ( currentGroup >= 0 && currentGroup < groups.size( ) - 1 ) { return groups.get( currentGroup + 1 ); } return null; } /** * Returns the next group index on given group list. */ public static int getNextGroupIndex( List<EdgeGroup> groups, int currentDimensionIndex, int currentLevelIndex ) { int currentGroup = -1; for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup gp = groups.get( i ); if ( gp.dimensionIndex == currentDimensionIndex && gp.levelIndex == currentLevelIndex ) { currentGroup = i; break; } } if ( currentGroup >= 0 && currentGroup < groups.size( ) - 1 ) { return currentGroup + 1; } return -1; } /** * Checks if current group is the first group */ public static boolean isFirstGroup( List<EdgeGroup> groups, int dimensionIndex, int levelIndex ) { if ( groups.size( ) > 0 ) { EdgeGroup eg = groups.get( 0 ); return dimensionIndex == eg.dimensionIndex && levelIndex == eg.levelIndex; } return false; } /** * Computes row span for aggreagtion cell by given target span over * dimension and level. * * @param crosstabItem * @param rowGroups * @param targetDimensionIndex * @param targetLevelIndex * @param rowEdgeCursor * @return * @throws OLAPException */ public static int computeAggregationCellRowOverSpan( CrosstabReportItemHandle crosstabItem, List<EdgeGroup> rowGroups, LevelHandle targetSpanLevel, EdgeCursor rowEdgeCursor ) throws OLAPException { if ( rowEdgeCursor == null || targetSpanLevel == null ) { return 1; } long startPosition = rowEdgeCursor.getPosition( ); int targetGroupIndex = getGroupIndex( rowGroups, targetSpanLevel ); boolean verticalHeader = MEASURE_DIRECTION_VERTICAL.equals( crosstabItem.getMeasureDirection( ) ); int factor = verticalHeader ? Math.max( crosstabItem.getMeasureCount( ), 1 ) : 1; if ( targetGroupIndex != -1 ) { long currentPosition = startPosition; long edgeEndPosition; DimensionCursor dc; if ( targetGroupIndex > 0 ) { dc = (DimensionCursor) rowEdgeCursor.getDimensionCursor( ) .get( targetGroupIndex - 1 ); edgeEndPosition = dc.getEdgeEnd( ); } else { edgeEndPosition = Long.MAX_VALUE; } int span = 0; while ( currentPosition <= edgeEndPosition && !rowEdgeCursor.isAfterLast( ) ) { span += factor; for ( int i = rowGroups.size( ) - 2; i >= targetGroupIndex; i { dc = (DimensionCursor) rowEdgeCursor.getDimensionCursor( ) .get( i ); // skip dummy groups if ( isDummyGroup( dc ) ) { continue; } // check for each group end if ( currentPosition == dc.getEdgeEnd( ) ) { EdgeGroup gp = rowGroups.get( i ); DimensionViewHandle dv = crosstabItem.getDimension( ROW_AXIS_TYPE, gp.dimensionIndex ); LevelViewHandle lv = dv.getLevel( gp.levelIndex ); // consider vertical measure case if ( lv.getAggregationHeader( ) != null ) { span += getTotalRowSpan( crosstabItem, gp.dimensionIndex, gp.levelIndex, verticalHeader ); } } else { break; } } rowEdgeCursor.next( ); currentPosition = rowEdgeCursor.getPosition( ); } // restore original position rowEdgeCursor.setPosition( startPosition ); return span; } return factor; } /** * Compute the row span include data span and subtotal span for row edge * area, this doesn't consider for multiple vertical measures. */ public static int computeRowSpan( CrosstabReportItemHandle crosstabItem, List<EdgeGroup> rowGroups, int dimensionIndex, int levelIndex, EdgeCursor rowEdgeCursor, boolean isLayoutDownThenOver ) throws OLAPException { if ( rowEdgeCursor == null ) { return 1; } long startPosition = rowEdgeCursor.getPosition( ); int groupIndex = -1; for ( int i = 0; i < rowGroups.size( ); i++ ) { EdgeGroup gp = rowGroups.get( i ); if ( gp.dimensionIndex == dimensionIndex && gp.levelIndex == levelIndex ) { groupIndex = i; break; } } boolean verticalHeader = MEASURE_DIRECTION_VERTICAL.equals( crosstabItem.getMeasureDirection( ) ); int factor = verticalHeader ? Math.max( crosstabItem.getMeasureCount( ), 1 ) : 1; if ( groupIndex != -1 && !isLeafGroup( rowEdgeCursor.getDimensionCursor( ), groupIndex ) ) { long currentPosition = startPosition; DimensionCursor dc = (DimensionCursor) rowEdgeCursor.getDimensionCursor( ) .get( groupIndex ); long edgeEndPosition = dc.getEdgeEnd( ); assert currentPosition == dc.getEdgeStart( ); int span = 0; int startGroupIndex = isLayoutDownThenOver ? ( groupIndex + 1 ) : groupIndex; while ( currentPosition <= edgeEndPosition ) { span += factor; for ( int i = rowGroups.size( ) - 2; i >= startGroupIndex; i { dc = (DimensionCursor) rowEdgeCursor.getDimensionCursor( ) .get( i ); // skip dummy groups if ( isDummyGroup( dc ) ) { continue; } // check for each group end if ( currentPosition == dc.getEdgeEnd( ) ) { EdgeGroup gp = rowGroups.get( i ); DimensionViewHandle dv = crosstabItem.getDimension( ROW_AXIS_TYPE, gp.dimensionIndex ); LevelViewHandle lv = dv.getLevel( gp.levelIndex ); // consider vertical measure case if ( lv.getAggregationHeader( ) != null ) { span += getTotalRowSpan( crosstabItem, gp.dimensionIndex, gp.levelIndex, verticalHeader ); } } else { break; } } rowEdgeCursor.next( ); currentPosition = rowEdgeCursor.getPosition( ); } // restore original position rowEdgeCursor.setPosition( startPosition ); return span; } return factor; } /** * Returns the first visible total row index */ public static int getFirstTotalRowIndex( CrosstabReportItemHandle crosstabItem, int dimensionIndex, int levelIndex, boolean isVerticalMeasure ) { int totalMeasureCount = crosstabItem.getMeasureCount( ); if ( totalMeasureCount > 0 && isVerticalMeasure ) { for ( int k = 0; k < totalMeasureCount; k++ ) { if ( hasTotalContent( crosstabItem, ROW_AXIS_TYPE, dimensionIndex, levelIndex, k ) ) { return k; } } } return 0; } /** * Computes the necessary row span for specific subtotal/grandtotal cell */ public static int getTotalRowSpan( CrosstabReportItemHandle crosstabItem, int dimensionIndex, int levelIndex, boolean isVerticalMeasure ) { int totalMeasureCount = crosstabItem.getMeasureCount( ); if ( totalMeasureCount == 0 ) { return !IColumnWalker.IGNORE_TOTAL_COLUMN_WITHOUT_MEASURE ? 1 : 0; } if ( !isVerticalMeasure ) { return hasTotalContent( crosstabItem, ROW_AXIS_TYPE, dimensionIndex, levelIndex, -1 ) ? 1 : 0; } else { int span = 0; for ( int k = 0; k < totalMeasureCount; k++ ) { if ( hasTotalContent( crosstabItem, ROW_AXIS_TYPE, dimensionIndex, levelIndex, k ) ) { span++; } } return span; } } /** * Checks if the given crosstab has measure header in specified axis */ public static boolean hasMeasureHeader( CrosstabReportItemHandle crosstabItem, int axisType ) { if ( crosstabItem.isHideMeasureHeader( ) ) { return false; } int mc = crosstabItem.getMeasureCount( ); if ( mc > 0 ) { if ( axisType == COLUMN_AXIS_TYPE ) { if ( MEASURE_DIRECTION_HORIZONTAL.equals( crosstabItem.getMeasureDirection( ) ) ) { for ( int i = 0; i < mc; i++ ) { if ( crosstabItem.getMeasure( i ).getHeader( ) != null ) { return true; } } } } else { if ( MEASURE_DIRECTION_VERTICAL.equals( crosstabItem.getMeasureDirection( ) ) ) { for ( int i = 0; i < mc; i++ ) { if ( crosstabItem.getMeasure( i ).getHeader( ) != null ) { return true; } } } } } return false; } /** * Returns 1-based starting group index, 0 means start of entire edge */ public static int getStartingGroupLevel( EdgeCursor edgeCursor, List<DimensionCursor> groupCursors ) throws OLAPException { if ( edgeCursor.isFirst( ) ) { return 0; } for ( int i = 0; i < groupCursors.size( ) - 1; i++ ) { DimensionCursor dc = groupCursors.get( i ); if ( GroupUtil.isDummyGroup( dc ) ) { // if first level is dummy, we still return the first index, // otherwise, we return the previous index return i == 0 ? 1 : i; } if ( dc.getEdgeStart( ) == edgeCursor.getPosition( ) ) { return i + 1; } } return groupCursors.size( ); } /** * Returns 1-based ending group index, 0 means end of entire edge. */ public static int getEndingGroupLevel( EdgeCursor edgeCursor, List<DimensionCursor> groupCursors ) throws OLAPException { if ( edgeCursor.isLast( ) ) { return 0; } for ( int i = 0; i < groupCursors.size( ) - 1; i++ ) { DimensionCursor dc = groupCursors.get( i ); if ( GroupUtil.isDummyGroup( dc ) ) { // if first level is dummy, we still return the first index, // otherwise, we return the previous index return i == 0 ? 1 : i; } if ( dc.getEdgeEnd( ) == edgeCursor.getPosition( ) ) { return i + 1; } } return groupCursors.size( ); } /** * Returns the effective page break interval settings on given axis */ public static int[] getLevelPageBreakIntervals( CrosstabReportItemHandle crosstabItem, List groups, int axisType ) { if ( crosstabItem == null || groups == null || groups.size( ) == 0 ) { return null; } int[] intervals = new int[groups.size( )]; boolean hasEffectiveInterval = false; for ( int i = 0; i < groups.size( ); i++ ) { EdgeGroup eg = (EdgeGroup) groups.get( i ); LevelViewHandle lv = crosstabItem.getDimension( axisType, eg.dimensionIndex ).getLevel( eg.levelIndex ); int intv = lv.getPageBreakInterval( ); if ( intv > 0 ) { hasEffectiveInterval = true; intervals[i] = intv; } } return hasEffectiveInterval ? intervals : null; } /** * Returns the position state of each dimension cursor on given edge cursor */ public static long[] getLevelCursorState( EdgeCursor cursor ) throws OLAPException { if ( cursor == null ) { return null; } List dimCursors = cursor.getDimensionCursor( ); long[] levelState = new long[dimCursors.size( )]; for ( int i = 0; i < levelState.length; i++ ) { DimensionCursor dc = (DimensionCursor) dimCursors.get( i ); levelState[i] = dc.getPosition( ); } return levelState; } }
/** * Main class for manifestParsing, it takes the URL, parse its content. */ package downloader.manifest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import downloader.exceptions.invalidManifestFileException; import downloader.exceptions.invalidUrlException; import downloader.utils.Utils; public class ManifestParser { private Manifest manifestFile; private ArrayList<UrlLine> segments; /** * ManifestParser constructor, it takes Manifest file as an object to * extract the content * * @param Object * manifestFile manifestFile object * */ public ManifestParser(Manifest manifestFile) { this.manifestFile = manifestFile; segments = new ArrayList<UrlLine>(); } /** * getURLcontentType function, it takes Manifest url and extracts the * content type * * @param String * manifestUrl manifest string url * * @return string content type * * @throws IOException * @throws invalidUrlException * */ private String getURLcontentType(String manifestUrl) throws IOException, invalidUrlException { if (Utils.isUrl(manifestUrl)) { URL url = new URL(manifestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); return connection.getContentType(); } else { throw new invalidUrlException("The URL provided is not valid URL"); } } /** * isValidManifestUrl function, check if the manifest url is valid * * @param String * url, manifest string url * * @return boolean true if url is valid manifest Url, false otherwise * * @throws IOException * @throws invalidUrlException * */ private boolean isValidManifestUrl(String url) throws IOException, invalidUrlException { if (url.endsWith(".segments") || getURLcontentType(url).equals("text/segments-manifest")) { return true; } return false; } /** * getSegments function, extracts the segments from manifest file * * @param * * @return ArrayList, returns array list of segments and manifest urls * inside manifest file * * @throws IOException * @throws invalidUrlException * @throws invalidManifestFileException * */ public ArrayList<UrlLine> getSegments() throws IOException, invalidUrlException, invalidManifestFileException { ArrayList<String> manifestLines = extractManifestLines(); boolean isAlternative = false; for (String manifestline : manifestLines) { if (manifestline.trim().equals("**")) { isAlternative = false; } else if (manifestline.trim().startsWith("http")) { // validate if URL is real URL if ((Utils.isUrl(manifestline.trim()))) { // check if Manifest if (isValidManifestUrl(manifestline.trim())) { segments.add(new Manifest(manifestline.trim())); } else { // it is a Segment if (isAlternative) { Segment s = (Segment) segments.get(segments.size() - 1); s.addMirror(manifestline); } else { segments.add(new Segment(manifestline.trim())); isAlternative = true; } } } } else { throw new invalidManifestFileException("Invalided Manifest File"); } } return segments; } /** * extractManifestLines function, extracts the lines from manifest file * * @param * * @return ArrayList, returns array list of lines inside the manifest file * * @throws IOException * */ private ArrayList<String> extractManifestLines() throws IOException { ArrayList<String> manifestLines = new ArrayList<String>(); URLConnection manifestUrlCon = new URL(this.manifestFile.getUrl()).openConnection(); InputStream in = manifestUrlCon.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String manifestLine = null; while ((manifestLine = reader.readLine()) != null) { manifestLines.add(manifestLine); } in.close(); return manifestLines; } }
package com.artemis.managers; import java.util.HashMap; import java.util.Map; import com.artemis.Entity; import com.artemis.Manager; import com.artemis.utils.Bag; import com.artemis.utils.ImmutableBag; /** * If you need to group your entities together, e.g tanks going into "units" * group or explosions into "effects", then use this manager. * <p> * You must retrieve it using world instance. * </p><p> * A entity can be assigned to more than one group. * </p> * * @author Arni Arent */ public class GroupManager extends Manager { /** All entities and groups mapped with group names as key. */ private final Map<String, Bag<Entity>> entitiesByGroup; /** All entities and groups mapped with entities as key. */ private final Map<Entity, Bag<String>> groupsByEntity; /** * Creates a new GroupManager instance. */ public GroupManager() { entitiesByGroup = new HashMap<String, Bag<Entity>>(); groupsByEntity = new HashMap<Entity, Bag<String>>(); } @Override protected void initialize() { } /** * Set the group of the entity. * * @param group * group to add the entity into * @param e * entity to add into the group */ public void add(Entity e, String group) { Bag<Entity> entities = entitiesByGroup.get(group); if(entities == null) { entities = new Bag<Entity>(); entitiesByGroup.put(group, entities); } if (!entities.contains(e)) entities.add(e); Bag<String> groups = groupsByEntity.get(e); if(groups == null) { groups = new Bag<String>(); groupsByEntity.put(e, groups); } if (!groups.contains(group)) groups.add(group); } /** * Remove the entity from the specified group. * * @param e * entity to remove from group * @param group * group to remove the entity from */ public void remove(Entity e, String group) { Bag<Entity> entities = entitiesByGroup.get(group); if(entities != null) { entities.remove(e); } Bag<String> groups = groupsByEntity.get(e); if(groups != null) { groups.remove(group); if (groups.size() == 0) groupsByEntity.remove(e); } } /** * Remove the entity from all groups. * * @param e * the entity to remove */ public void removeFromAllGroups(Entity e) { Bag<String> groups = groupsByEntity.get(e); if(groups == null) return; for(int i = 0, s = groups.size(); s > i; i++) { Bag<Entity> entities = entitiesByGroup.get(groups.get(i)); if(entities != null) { entities.remove(e); } } groupsByEntity.remove(e); } /** * Get all entities that belong to the provided group. * * @param group * name of the group * * @return read-only bag of entities belonging to the group */ public ImmutableBag<Entity> getEntities(String group) { Bag<Entity> entities = entitiesByGroup.get(group); if(entities == null) { entities = new Bag<Entity>(); entitiesByGroup.put(group, entities); } return entities; } /** * Get all groups the entity belongs to. * * @param e * the entity * * @return the groups the entity belongs to, null if none */ public ImmutableBag<String> getGroups(Entity e) { return groupsByEntity.get(e); } /** * Checks if the entity belongs to any group. * * @param e * the entity to check * * @return true if it is in any group, false if none */ public boolean isInAnyGroup(Entity e) { return getGroups(e) != null; } /** * Check if the entity is in the supplied group. * * @param group * the group to check in * @param e * the entity to check for * * @return true if the entity is in the supplied group, false if not */ public boolean isInGroup(Entity e, String group) { if(group != null) { Bag<String> bag = groupsByEntity.get(e); if (bag != null) { Object[] groups = bag.getData(); for(int i = 0, s = bag.size(); s > i; i++) { String g = (String)groups[i]; if(group.equals(g)) { return true; } } } } return false; } /** * Removes the entity from all groups. * * @param e * the deleted entity */ @Override public void deleted(Entity e) { removeFromAllGroups(e); } }
package dk.itst.oiosaml.trust; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.security.cert.CertificateFactory; import org.apache.xml.security.signature.SignedInfo; import org.apache.xml.security.signature.XMLSignature; import org.apache.xml.security.signature.XMLSignatureInput; import org.junit.Before; import org.junit.Test; import org.opensaml.saml2.core.Assertion; import org.opensaml.ws.soap.soap11.Envelope; import org.opensaml.ws.soap.util.SOAPConstants; import org.opensaml.ws.wsaddressing.Action; import org.opensaml.ws.wsaddressing.MessageID; import org.opensaml.ws.wsaddressing.WSAddressingConstants; import org.opensaml.ws.wssecurity.Security; import org.opensaml.ws.wssecurity.SecurityTokenReference; import org.opensaml.ws.wssecurity.Timestamp; import org.opensaml.xml.schema.XSAny; import org.opensaml.xml.schema.impl.XSAnyBuilder; import org.opensaml.xml.security.x509.BasicX509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.signature.X509Certificate; import org.opensaml.xml.signature.X509Data; import org.opensaml.xml.signature.impl.SignatureImpl; import org.opensaml.xml.util.XMLHelper; import org.opensaml.xml.validation.ValidationException; import org.w3c.dom.Element; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.liberty.UserInteraction; import dk.itst.oiosaml.sp.model.OIOAssertion; public class OIOSoapEnvelopeTest extends TrustTests { private OIOSoapEnvelope env; @Before public void setUp() { env = OIOSoapEnvelope.buildEnvelope(); } @Test public void testBuild() { assertNotNull(env); assertNotNull(env.getXMLObject()); assertTrue(env.getXMLObject() instanceof Envelope); Envelope e = (Envelope) env.getXMLObject(); assertNull(e.getBody()); assertNotNull(e.getHeader()); assertFalse(e.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).isEmpty()); } @Test public void testAction() { env.setAction("action"); Envelope e = (Envelope) env.getXMLObject(); assertFalse(e.getHeader().getUnknownXMLObjects(Action.ELEMENT_NAME).isEmpty()); Action a = (Action) e.getHeader().getUnknownXMLObjects(Action.ELEMENT_NAME).get(0); assertEquals("action", a.getValue()); assertNotNull(a.getUnknownAttributes().get(TrustConstants.WSU_ID)); } @Test public void testBody() { env.setBody(OIOIssueRequest.buildRequest().getXMLObject()); Envelope e = (Envelope) env.getXMLObject(); assertNotNull(e.getBody()); assertNotNull(e.getBody().getUnknownAttributes().get(TrustConstants.WSU_ID)); } @Test public void testTimestamp() { env.setTimestamp(5); Envelope e = (Envelope) env.getXMLObject(); Security sec = (Security) e.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).get(0); Timestamp ts = (Timestamp) sec.getUnknownXMLObjects(Timestamp.ELEMENT_NAME).get(0); assertNotNull(ts.getCreated()); assertNotNull(ts.getExpires()); assertNotNull(ts.getUnknownAttributes().get(TrustConstants.WSU_ID)); } @Test public void testAddSEcurityToken() { env.addSecurityToken(TestHelper.buildAssertion("rec", "aud")); Envelope e = (Envelope) env.getXMLObject(); Security sec = (Security) e.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).get(0); assertFalse(sec.getUnknownXMLObjects(Assertion.DEFAULT_ELEMENT_NAME).isEmpty()); } @Test public void testSign() throws Exception { env.setAction("action"); BasicX509Credential credential = TestHelper.getCredential(); Element e = env.sign(credential); assertEquals("Envelope", e.getLocalName()); assertEquals(SOAPConstants.SOAP11_NS, e.getNamespaceURI()); Envelope envelope = (Envelope) SAMLUtil.unmarshallElementFromString(XMLHelper.nodeToString(e)); Security sec = (Security) envelope.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).get(0); assertFalse(sec.getUnknownXMLObjects(Signature.DEFAULT_ELEMENT_NAME).isEmpty()); SignatureImpl signature = (SignatureImpl) sec.getUnknownXMLObjects(Signature.DEFAULT_ELEMENT_NAME).get(0); assertEquals(3, signature.getXMLSignature().getSignedInfo().getLength()); Action action = (Action) envelope.getHeader().getUnknownXMLObjects(Action.ELEMENT_NAME).get(0); boolean found = false; for (int i = 0; i < signature.getXMLSignature().getSignedInfo().getLength(); i++) { if (("#" + action.getUnknownAttributes().get(TrustConstants.WSU_ID)).equals(signature.getXMLSignature().getSignedInfo().getReferencedContentBeforeTransformsItem(i).getSourceURI())) { found = true; } } assertTrue(found); SignatureValidator validator = new SignatureValidator(credential); validator.validate(signature); } @Test public void testValidateFromX509data() throws Exception { env.setAction("action"); BasicX509Credential credential = TestHelper.getCredential(); Element e = env.sign(credential); Envelope envelope = (Envelope) SAMLUtil.unmarshallElementFromString(XMLHelper.nodeToString(e)); Security sec = (Security) envelope.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).get(0); assertFalse(sec.getUnknownXMLObjects(Signature.DEFAULT_ELEMENT_NAME).isEmpty()); SignatureImpl signature = (SignatureImpl) sec.getUnknownXMLObjects(Signature.DEFAULT_ELEMENT_NAME).get(0); assertNotNull(signature.getKeyInfo()); assertFalse(signature.getKeyInfo().getX509Datas().isEmpty()); X509Data x509 = signature.getKeyInfo().getX509Datas().get(0); assertEquals(1, x509.getX509Certificates().size()); X509Certificate cert = x509.getX509Certificates().get(0); BasicX509Credential cred = new BasicX509Credential(); String base64 = " cred.setEntityCertificate((java.security.cert.X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(base64.getBytes()))); SignatureValidator validator = new SignatureValidator(cred); validator.validate(signature); } @Test(expected=ValidationException.class) public void testInvalidSignature() throws Exception { env.setAction("action"); BasicX509Credential credential = TestHelper.getCredential(); Element e = env.sign(credential); Element actionElement = (Element) e.getElementsByTagNameNS(WSAddressingConstants.WSA_NS, "Action").item(0); actionElement.setTextContent("test"); Envelope envelope = (Envelope) SAMLUtil.unmarshallElementFromString(XMLHelper.nodeToString(e)); Security sec = (Security) envelope.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).get(0); Signature signature = (Signature) sec.getUnknownXMLObjects(Signature.DEFAULT_ELEMENT_NAME).get(0); SignatureValidator validator = new SignatureValidator(credential); validator.validate(signature); } @Test public void testSignatureWithSignedAssertion() throws Exception { BasicX509Credential credential = TestHelper.getCredential(); env.setAction("action"); Assertion assertion = SAMLUtil.buildXMLObject(Assertion.class); assertion.setID("testing"); new OIOAssertion(assertion).sign(credential); env.addSecurityToken(assertion); Element e = env.sign(credential); Envelope envelope = (Envelope) SAMLUtil.unmarshallElementFromString(XMLHelper.nodeToString(e)); Security sec = (Security) envelope.getHeader().getUnknownXMLObjects(Security.ELEMENT_NAME).get(0); SignatureImpl signature = (SignatureImpl) sec.getUnknownXMLObjects(Signature.DEFAULT_ELEMENT_NAME).get(0); SignatureValidator validator = new SignatureValidator(credential); validator.validate(signature); assertion = (Assertion) sec.getUnknownXMLObjects(Assertion.DEFAULT_ELEMENT_NAME).get(0); assertTrue(new OIOAssertion(assertion).verifySignature(credential.getPublicKey())); } @Test public void testRelatesTo() { assertFalse(env.relatesTo("vlah")); Envelope e = (Envelope) env.getXMLObject(); XSAny relatesTo = new XSAnyBuilder().buildObject(MessageID.ELEMENT_NAME.getNamespaceURI(), "RelatesTo", "wsa"); relatesTo.setTextContent("id"); e.getHeader().getUnknownXMLObjects().add(relatesTo); OIOSoapEnvelope env = new OIOSoapEnvelope(e); assertTrue(env.relatesTo("id")); } @Test public void testUserInteraction() throws Exception { assertNull(env.getHeaderElement(UserInteraction.class)); env.setUserInteraction(dk.itst.oiosaml.trust.UserInteraction.IF_NEEDED, true); assertNotNull(env.getHeaderElement(UserInteraction.class)); UserInteraction ui = env.getHeaderElement(UserInteraction.class); assertTrue(ui.redirect()); assertEquals("InteractIfNeeded", ui.getInteract()); System.out.println(env.toXML()); } @Test public void testSecurityReferenceIsSignedWithSTRTransform() throws Exception { Assertion assertion = (Assertion) SAMLUtil.unmarshallElement(getClass().getResourceAsStream("assertion.xml")); env.addSecurityTokenReference(assertion); Security sec = env.getHeaderElement(Security.class); assertNotNull(SAMLUtil.getFirstElement(sec, Assertion.class)); Element signed = env.sign(TestHelper.getCredential()); env = new OIOSoapEnvelope((Envelope) SAMLUtil.unmarshallElementFromString(XMLHelper.nodeToString(signed))); sec = env.getHeaderElement(Security.class); SecurityTokenReference str = SAMLUtil.getFirstElement(sec, SecurityTokenReference.class); assertNotNull(str); assertEquals(assertion.getID(), str.getKeyIdentifier().getValue()); Signature sig = SAMLUtil.getFirstElement(sec, Signature.class); SignedInfo si = new XMLSignature(sig.getDOM(), null).getSignedInfo(); boolean found = false; for (int i = 0; i < si.getLength(); i++) { XMLSignatureInput ref = si.getReferencedContentBeforeTransformsItem(i); System.out.println(ref.getSourceURI()); if (("#" + str.getId()).equals(ref.getSourceURI())) { found = true; } } assertTrue(found); } }
package org.eclipse.birt.report.designer.internal.ui.swt.custom; import org.eclipse.birt.report.designer.internal.ui.util.SortMap; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.ACC; import org.eclipse.swt.accessibility.Accessible; import org.eclipse.swt.accessibility.AccessibleAdapter; import org.eclipse.swt.accessibility.AccessibleControlAdapter; import org.eclipse.swt.accessibility.AccessibleControlEvent; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.forms.FormColors; import org.eclipse.ui.forms.widgets.FormToolkit; public class TabbedPropertyList extends Canvas { private static final ListElement[] ELEMENTS_EMPTY = new ListElement[0]; protected static final int NONE = -1; protected static final int INDENT = 7; private boolean focus = false; private ListElement[] elements; private int selectedElementIndex = NONE; private int topVisibleIndex = NONE; private int bottomVisibleIndex = NONE; private TopNavigationElement topNavigationElement; private BottomNavigationElement bottomNavigationElement; private int widestLabelIndex = NONE; private int tabsThatFitInComposite = NONE; private Color widgetForeground; private Color widgetBackground; private Color widgetNormalShadow; private Color widgetDarkShadow; private Color listBackground; private Color hoverGradientStart; private Color hoverGradientEnd; private Color defaultGradientStart; private Color defaultGradientEnd; private Color indentedDefaultBackground; private Color indentedHoverBackground; private Color navigationElementShadowStroke; private Color bottomNavigationElementShadowStroke1; private Color bottomNavigationElementShadowStroke2; private GC textGc; private FormToolkit factory; public class ListElement extends Canvas { private Tab tab; private int index; private boolean selected; private boolean hover; public ListElement( Composite parent, final Tab tab, int index ) { super( parent, SWT.NO_FOCUS ); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { if ( !selected ) { select( getIndex( ListElement.this ), true ); } Composite tabbedPropertyComposite = getParent( ); Control[] children = tabbedPropertyComposite.getParent( ) .getTabList( ); if ( children != null && children.length > 0 ) { for ( int i = 0; i < children.length; i++ ) { if ( children[i] == TabbedPropertyList.this ) { continue; } else if ( children[i].setFocus( ) ) { focus = false; return; } } } } } ); addMouseMoveListener( new MouseMoveListener( ) { public void mouseMove( MouseEvent e ) { if ( !hover ) { hover = true; redraw( ); } } } ); addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseExit( MouseEvent e ) { hover = false; redraw( ); } } ); } public void setSelected( boolean selected ) { this.selected = selected; redraw( ); } /** * Draws elements and collects element areas. */ private void paint( PaintEvent e ) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds( ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( listBackground ); e.gc.drawLine( 0, 1, bounds.width - 1, 1 ); /* draw the fill in the tab */ if ( selected ) { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 2, bounds.width, bounds.height - 1 ); } else if ( hover && tab.isIndented( ) ) { e.gc.setBackground( indentedHoverBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else if ( hover ) { e.gc.setForeground( hoverGradientStart ); e.gc.setBackground( hoverGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } else if ( tab.isIndented( ) ) { e.gc.setBackground( indentedDefaultBackground ); e.gc.fillRectangle( 0, 2, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setForeground( defaultGradientStart ); e.gc.setBackground( defaultGradientEnd ); e.gc.fillGradientRectangle( 0, 2, bounds.width - 1, bounds.height - 1, true ); } if ( !selected ) { e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 1, bounds.width - 1, bounds.height + 1 ); } int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; if ( selected && tab.getImage( ) != null && !tab.getImage( ).isDisposed( ) ) { /* draw the icon for the selected tab */ if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } else { textIndent = textIndent - 3; } e.gc.drawImage( tab.getImage( ), textIndent, textMiddle - 1 ); textIndent = textIndent + 16 + 5; } else if ( tab.isIndented( ) ) { textIndent = textIndent + INDENT; } /* draw the text */ e.gc.setForeground( widgetForeground ); if ( selected ) { /* selected tab is bold font */ e.gc.setFont( JFaceResources.getFontRegistry( ) .getBold( JFaceResources.DEFAULT_FONT ) ); } e.gc.drawText( tab.getText( ), textIndent, textMiddle, true ); if ( ( (TabbedPropertyList) getParent( ) ).focus && selected && focus ) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent( tab.getText( ) ); e.gc.drawLine( textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4 ); } /* draw the bottom line on the tab for selected and default */ if ( !hover ) { e.gc.setForeground( listBackground ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } public String getText( ) { return tab.getText( ); } public String toString( ) { return tab.getText( ); } } public class TopNavigationElement extends Canvas { /** * @param parent */ public TopNavigationElement( Composite parent ) { super( parent, SWT.NO_FOCUS ); addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseUp( MouseEvent e ) { if ( isUpScrollRequired( ) ) { bottomVisibleIndex if ( topVisibleIndex != 0 ) { topVisibleIndex } layoutTabs( ); topNavigationElement.redraw( ); bottomNavigationElement.redraw( ); } } } ); } /** * @param e */ private void paint( PaintEvent e ) { e.gc.setBackground( widgetBackground ); e.gc.setForeground( widgetForeground ); Rectangle bounds = getBounds( ); if ( elements.length != 0 ) { e.gc.fillRectangle( 0, 0, bounds.width, bounds.height ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 0, bounds.width - 1, bounds.height - 1 ); } else { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 0, bounds.width, bounds.height ); int textIndent = INDENT; FontMetrics fm = e.gc.getFontMetrics( ); int height = fm.getHeight( ); int textMiddle = ( bounds.height - height ) / 2; e.gc.setForeground( widgetForeground ); String properties_not_available = Messages.getString( "TabbedPropertyList.properties.not.available" ); //$NON-NLS-1$ e.gc.drawText( properties_not_available, textIndent, textMiddle ); } if ( isUpScrollRequired( ) ) { e.gc.setForeground( widgetDarkShadow ); int middle = bounds.width / 2; e.gc.drawLine( middle + 1, 3, middle + 5, 7 ); e.gc.drawLine( middle, 3, middle - 4, 7 ); e.gc.drawLine( middle - 3, 7, middle + 4, 7 ); e.gc.setForeground( listBackground ); e.gc.drawLine( middle, 4, middle + 1, 4 ); e.gc.drawLine( middle - 1, 5, middle + 2, 5 ); e.gc.drawLine( middle - 2, 6, middle + 3, 6 ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, 0, bounds.width - 2, 0 ); e.gc.setForeground( navigationElementShadowStroke ); e.gc.drawLine( 0, 1, bounds.width - 2, 1 ); e.gc.drawLine( 0, bounds.height - 1, bounds.width - 2, bounds.height - 1 ); } } } public class BottomNavigationElement extends Canvas { /** * @param parent */ public BottomNavigationElement( Composite parent ) { super( parent, SWT.NO_FOCUS ); addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { paint( e ); } } ); addMouseListener( new MouseAdapter( ) { public void mouseUp( MouseEvent e ) { if ( isDownScrollRequired( ) ) { topVisibleIndex++; if ( bottomVisibleIndex != elements.length - 1 ) { bottomVisibleIndex++; } layoutTabs( ); topNavigationElement.redraw( ); bottomNavigationElement.redraw( ); } } } ); } /** * @param e */ private void paint( PaintEvent e ) { e.gc.setBackground( widgetBackground ); e.gc.setForeground( widgetForeground ); Rectangle bounds = getBounds( ); if ( elements.length != 0 ) { e.gc.fillRectangle( 0, 0, bounds.width, bounds.height ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( bounds.width - 1, 0, bounds.width - 1, bounds.height - 1 ); e.gc.drawLine( 0, 0, bounds.width - 1, 0 ); e.gc.setForeground( bottomNavigationElementShadowStroke1 ); e.gc.drawLine( 0, 1, bounds.width - 2, 1 ); e.gc.setForeground( bottomNavigationElementShadowStroke2 ); e.gc.drawLine( 0, 2, bounds.width - 2, 2 ); } else { e.gc.setBackground( listBackground ); e.gc.fillRectangle( 0, 0, bounds.width, bounds.height ); } if ( isDownScrollRequired( ) ) { e.gc.setForeground( widgetDarkShadow ); int middle = bounds.width / 2; int bottom = bounds.height - 3; e.gc.drawLine( middle + 1, bottom, middle + 5, bottom - 4 ); e.gc.drawLine( middle, bottom, middle - 4, bottom - 4 ); e.gc.drawLine( middle - 3, bottom - 4, middle + 4, bottom - 4 ); e.gc.setForeground( listBackground ); e.gc.drawLine( middle, bottom - 1, middle + 1, bottom - 1 ); e.gc.drawLine( middle - 1, bottom - 2, middle + 2, bottom - 2 ); e.gc.drawLine( middle - 2, bottom - 3, middle + 3, bottom - 3 ); e.gc.setForeground( widgetNormalShadow ); e.gc.drawLine( 0, bottom - 7, bounds.width - 2, bottom - 7 ); e.gc.setForeground( navigationElementShadowStroke ); e.gc.drawLine( 0, bottom + 2, bounds.width - 2, bottom + 2 ); e.gc.drawLine( 0, bottom - 6, bounds.width - 2, bottom - 6 ); } } } public TabbedPropertyList( Composite parent ) { super( parent, SWT.NONE ); factory = FormWidgetFactory.getInstance( ); removeAll( ); setLayout( new FormLayout( ) ); initColours( ); initAccessible( ); topNavigationElement = new TopNavigationElement( this ); bottomNavigationElement = new BottomNavigationElement( this ); this.addFocusListener( new FocusListener( ) { public void focusGained( FocusEvent e ) { focus = true; int i = getSelectionIndex( ); if ( i >= 0 ) { elements[i].redraw( ); } } public void focusLost( FocusEvent e ) { focus = false; int i = getSelectionIndex( ); if ( i >= 0 ) { elements[i].redraw( ); } } } ); // do nothing, just for tab traverse. this.addKeyListener( new KeyAdapter( ) { } ); this.addControlListener( new ControlAdapter( ) { public void controlResized( ControlEvent e ) { topNavigationElement.redraw( ); bottomNavigationElement.redraw( ); computeTopAndBottomTab( ); } } ); this.addTraverseListener( new TraverseListener( ) { public void keyTraversed( TraverseEvent e ) { if ( e.detail == SWT.TRAVERSE_ARROW_PREVIOUS || e.detail == SWT.TRAVERSE_ARROW_NEXT ) { int nMax = elements.length - 1; int nCurrent = getSelectionIndex( ); if ( e.detail == SWT.TRAVERSE_ARROW_PREVIOUS ) { nCurrent -= 1; nCurrent = Math.max( 0, nCurrent ); } else if ( e.detail == SWT.TRAVERSE_ARROW_NEXT ) { nCurrent += 1; nCurrent = Math.min( nCurrent, nMax ); } select( nCurrent, true ); redraw( ); } else { e.doit = true; } } } ); } /** * Calculate the number of tabs that will fit in the tab list composite. */ protected void computeTabsThatFitInComposite( ) { tabsThatFitInComposite = ( ( getSize( ).y - 22 ) ) / getTabHeight( ); if ( tabsThatFitInComposite <= 0 ) { tabsThatFitInComposite = 1; } } /** * Returns the element with the given index from this list viewer. Returns * <code>null</code> if the index is out of range. * * @param index * the zero-based index * @return the element at the given index, or <code>null</code> if the index * is out of range */ public Object getElementAt( int index ) { if ( index >= 0 && index < elements.length ) { return elements[index]; } return null; } /** * Returns the zero-relative index of the item which is currently selected * in the receiver, or -1 if no item is selected. * * @return the index of the selected item */ public int getSelectionIndex( ) { return selectedElementIndex; } public String getSelectionKey( ) { return elementMap.getKeyList( ).get( selectedElementIndex ).toString( ); } /** * Removes all elements from this list. */ public void removeAll( ) { if ( elements != null ) { for ( int i = 0; i < elements.length; i++ ) { elements[i].dispose( ); } } elements = ELEMENTS_EMPTY; selectedElementIndex = NONE; widestLabelIndex = NONE; topVisibleIndex = NONE; bottomVisibleIndex = NONE; } /** * Sets the new list elements. */ private SortMap elementMap = null; public void setElements( SortMap children ) { elementMap = children; if ( elements != ELEMENTS_EMPTY ) { removeAll( ); } elements = new ListElement[children.size( )]; if ( children.size( ) == 0 ) { widestLabelIndex = NONE; } else { widestLabelIndex = 0; for ( int i = 0; i < children.size( ); i++ ) { elements[i] = new ListElement( this, (Tab) children.getValue( i ), i ); elements[i].setVisible( false ); elements[i].setLayoutData( null ); if ( i != widestLabelIndex ) { String label = ( (Tab) children.getValue( i ) ).getText( ); if ( getTextDimension( label ).x > getTextDimension( ( (Tab) children.getValue( widestLabelIndex ) ).getText( ) ).x ) { widestLabelIndex = i; } } } } computeTopAndBottomTab( ); } /** * Selects one for the elements in the list. */ public void select( int index, boolean reveal ) { if ( getSelectionIndex( ) == index ) { /* * this index is already selected. */ return; } if ( index >= 0 && index < elements.length ) { int lastSelected = getSelectionIndex( ); elements[index].setSelected( true ); selectedElementIndex = index; if ( lastSelected != NONE ) { elements[lastSelected].setSelected( false ); if ( getSelectionIndex( ) != elements.length - 1 ) { /* * redraw the next tab to fix the border by calling * setSelected() */ elements[getSelectionIndex( ) + 1].setSelected( false ); } } topNavigationElement.redraw( ); bottomNavigationElement.redraw( ); if ( selectedElementIndex < topVisibleIndex || selectedElementIndex > bottomVisibleIndex ) { computeTopAndBottomTab( ); } } notifyListeners( SWT.Selection, new Event( ) ); } public void setSelection( String key, int index ) { if ( elementMap.containKey( key ) ) index = elementMap.getIndexOf( key ); if ( getSelectionIndex( ) == index ) { /* * this index is already selected. */ return; } if ( index >= 0 && index < elements.length ) { int lastSelected = getSelectionIndex( ); elements[index].setSelected( true ); selectedElementIndex = index; if ( lastSelected != NONE ) { elements[lastSelected].setSelected( false ); if ( getSelectionIndex( ) != elements.length - 1 ) { /* * redraw the next tab to fix the border by calling * setSelected() */ elements[getSelectionIndex( ) + 1].setSelected( false ); } } topNavigationElement.redraw( ); bottomNavigationElement.redraw( ); if ( selectedElementIndex < topVisibleIndex || selectedElementIndex > bottomVisibleIndex ) { computeTopAndBottomTab( ); } } }; /** * Selects one for the elements in the list. */ public void deselectAll( ) { if ( getSelectionIndex( ) != NONE ) { elements[getSelectionIndex( )].setSelected( false ); selectedElementIndex = NONE; } } private int getIndex( ListElement element ) { return element.index; } /** * Computes the size based on the widest string in the list. */ public Point computeSize( int wHint, int hHint, boolean changed ) { Point result = super.computeSize( hHint, wHint, changed ); if ( widestLabelIndex == -1 ) { String properties_not_available = Messages.getString( "TabbedPropertyList.properties.not.available" ); //$NON-NLS-1$ result.x = getTextDimension( properties_not_available ).x + INDENT; } else { int width = getTextDimension( elements[widestLabelIndex].getText( ) ).x; /* * To anticipate for the icon placement we should always keep the * space available after the label. So when the active tab includes * an icon the width of the tab doesn't change. */ result.x = width + 32; result.x = result.x >= 125 ? result.x : 125; } return result; } private Point getTextDimension( String text ) { if ( textGc == null || textGc.isDisposed( ) ) { textGc = new GC( this ); } textGc.setFont( getFont( ) ); Point point = textGc.textExtent( text ); point.x++; return point; } /** * Initialize the colours used. */ private void initColours( ) { /* * Colour 3 COLOR_LIST_BACKGROUND */ listBackground = Display.getCurrent( ) .getSystemColor( SWT.COLOR_LIST_BACKGROUND ); /* * Colour 13 COLOR_WIDGET_BACKGROUND */ widgetBackground = Display.getCurrent( ) .getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ); /* * Colour 15 COLOR_WIDGET_DARK_SHADOW */ widgetDarkShadow = Display.getCurrent( ) .getSystemColor( SWT.COLOR_WIDGET_DARK_SHADOW ); /* * Colour 16 COLOR_WIDGET_FOREGROUND */ widgetForeground = Display.getCurrent( ) .getSystemColor( SWT.COLOR_WIDGET_FOREGROUND ); /* * Colour 19 COLOR_WIDGET_NORMAL_SHADOW */ widgetNormalShadow = Display.getCurrent( ) .getSystemColor( SWT.COLOR_WIDGET_NORMAL_SHADOW ); RGB infoBackground = Display.getCurrent( ) .getSystemColor( SWT.COLOR_INFO_BACKGROUND ) .getRGB( ); RGB white = Display.getCurrent( ) .getSystemColor( SWT.COLOR_WHITE ) .getRGB( ); RGB black = Display.getCurrent( ) .getSystemColor( SWT.COLOR_BLACK ) .getRGB( ); /* * gradient in the default tab: start colour WIDGET_NORMAL_SHADOW 100% + * white 20% + INFO_BACKGROUND 60% end colour WIDGET_NORMAL_SHADOW 100% * + INFO_BACKGROUND 40% */ defaultGradientStart = factory.getColors( ) .createColor( "TabbedPropertyList.defaultTabGradientStart", //$NON-NLS-1$ FormColors.blend( infoBackground, FormColors.blend( white, widgetNormalShadow.getRGB( ), 20 ), 60 ) ); defaultGradientEnd = factory.getColors( ) .createColor( "TabbedPropertyList.defaultTabGradientEnd", //$NON-NLS-1$ FormColors.blend( infoBackground, widgetNormalShadow.getRGB( ), 40 ) ); navigationElementShadowStroke = factory.getColors( ) .createColor( "TabbedPropertyList.shadowStroke", //$NON-NLS-1$ FormColors.blend( white, widgetNormalShadow.getRGB( ), 55 ) ); bottomNavigationElementShadowStroke1 = factory.getColors( ) .createColor( "TabbedPropertyList.tabShadowStroke1", //$NON-NLS-1$ FormColors.blend( black, widgetBackground.getRGB( ), 10 ) ); bottomNavigationElementShadowStroke2 = factory.getColors( ) .createColor( "TabbedPropertyList.tabShadowStroke2", //$NON-NLS-1$ FormColors.blend( black, widgetBackground.getRGB( ), 5 ) ); /* * gradient in the hover tab: start colour WIDGET_BACKGROUND 100% + * white 20% end colour WIDGET_BACKGROUND 100% + WIDGET_NORMAL_SHADOW * 10% */ hoverGradientStart = factory.getColors( ) .createColor( "TabbedPropertyList.hoverBackgroundGradientStart", //$NON-NLS-1$ FormColors.blend( white, widgetBackground.getRGB( ), 20 ) ); hoverGradientEnd = factory.getColors( ) .createColor( "TabbedPropertyList.hoverBackgroundGradientEnd", //$NON-NLS-1$ FormColors.blend( widgetNormalShadow.getRGB( ), widgetBackground.getRGB( ), 10 ) ); indentedDefaultBackground = factory.getColors( ) .createColor( "TabbedPropertyList.indentedDefaultBackground", //$NON-NLS-1$ FormColors.blend( white, widgetBackground.getRGB( ), 10 ) ); indentedHoverBackground = factory.getColors( ) .createColor( "TabbedPropertyList.indentedHoverBackground", //$NON-NLS-1$ FormColors.blend( white, widgetBackground.getRGB( ), 75 ) ); } /** * @see org.eclipse.swt.widgets.Widget#dispose() */ public void dispose( ) { if ( textGc != null && !textGc.isDisposed( ) ) { textGc.dispose( ); textGc = null; } super.dispose( ); } /** * Get the height of a tab. The height of the tab is the height of the text * plus buffer. * * @return the height of a tab. */ private int getTabHeight( ) { int tabHeight = getTextDimension( "" ).y + INDENT; //$NON-NLS-1$ if ( tabsThatFitInComposite == 1 ) { /* * if only one tab will fix, reduce the size of the tab height so * that the navigation elements fit. */ int ret = getBounds( ).height - 20; return ( ret > tabHeight ) ? tabHeight : ( ret < 5 ) ? 5 : ret; } return tabHeight; } private boolean isDownScrollRequired( ) { return elements.length > tabsThatFitInComposite && bottomVisibleIndex != elements.length - 1; } private boolean isUpScrollRequired( ) { return elements.length > tabsThatFitInComposite && topVisibleIndex != 0; } private void computeTopAndBottomTab( ) { computeTabsThatFitInComposite( ); if ( elements.length == 0 ) { /* * no tabs to display. */ topVisibleIndex = 0; bottomVisibleIndex = 0; } else if ( tabsThatFitInComposite >= elements.length ) { /* * all the tabs fit. */ topVisibleIndex = 0; bottomVisibleIndex = elements.length - 1; } else if ( getSelectionIndex( ) == NONE ) { /* * there is no selected tab yet, assume that tab one would be * selected for now. */ topVisibleIndex = 0; bottomVisibleIndex = tabsThatFitInComposite - 1; } else if ( getSelectionIndex( ) + tabsThatFitInComposite > elements.length ) { /* * the selected tab is near the bottom. */ bottomVisibleIndex = elements.length - 1; topVisibleIndex = bottomVisibleIndex - tabsThatFitInComposite + 1; } else { /* * the selected tab is near the top. */ topVisibleIndex = selectedElementIndex; bottomVisibleIndex = selectedElementIndex + tabsThatFitInComposite - 1; } layoutTabs( ); } /** * Layout the tabs. * * @param up * if <code>true</code>, then we are laying out as a result of an * scroll up request. */ private void layoutTabs( ) { // System.out.println("TabFit " + tabsThatFitInComposite + " length " // + elements.length + " top " + topVisibleIndex + " bottom " // + bottomVisibleIndex); if ( tabsThatFitInComposite == NONE || elements.length == 0 ) { FormData formData = new FormData( ); formData.left = new FormAttachment( 0, 0 ); formData.right = new FormAttachment( 100, 0 ); formData.top = new FormAttachment( 0, 0 ); formData.height = getTabHeight( ); topNavigationElement.setLayoutData( formData ); formData = new FormData( ); formData.left = new FormAttachment( 0, 0 ); formData.right = new FormAttachment( 100, 0 ); formData.top = new FormAttachment( topNavigationElement, 0 ); formData.bottom = new FormAttachment( 100, 0 ); bottomNavigationElement.setLayoutData( formData ); } else { FormData formData = new FormData( ); formData.left = new FormAttachment( 0, 0 ); formData.right = new FormAttachment( 100, 0 ); formData.top = new FormAttachment( 0, 0 ); formData.height = 10; topNavigationElement.setLayoutData( formData ); /* * use nextElement to attach the layout to the previous canvas * widget in the list. */ Canvas nextElement = topNavigationElement; for ( int i = 0; i < elements.length; i++ ) { // System.out.print(i + " [" + elements[i].getText() + "]"); if ( i < topVisibleIndex || i > bottomVisibleIndex ) { /* * this tab is not visible */ elements[i].setLayoutData( null ); elements[i].setVisible( false ); } else { /* * this tab is visible. */ // System.out.print(" visible"); formData = new FormData( ); formData.height = getTabHeight( ); formData.left = new FormAttachment( 0, 0 ); formData.right = new FormAttachment( 100, 0 ); formData.top = new FormAttachment( nextElement, 0 ); nextElement = elements[i]; elements[i].setLayoutData( formData ); elements[i].setVisible( true ); } // if (i == selectedElementIndex) { // System.out.print(" selected"); // System.out.println(""); } formData = new FormData( ); formData.left = new FormAttachment( 0, 0 ); formData.right = new FormAttachment( 100, 0 ); formData.top = new FormAttachment( nextElement, 0 ); formData.bottom = new FormAttachment( 100, 0 ); formData.height = 10; bottomNavigationElement.setLayoutData( formData ); } // System.out.println(""); // layout so that we have enough space for the new labels Composite grandparent = getParent( ).getParent( ); grandparent.layout( true ); layout( true ); } /** * Initialize the accessibility adapter. */ private void initAccessible( ) { final Accessible accessible = getAccessible( ); accessible.addAccessibleListener( new AccessibleAdapter( ) { public void getName( AccessibleEvent e ) { if ( getSelectionIndex( ) != NONE ) { e.result = elements[getSelectionIndex( )].getText( ); } } public void getHelp( AccessibleEvent e ) { if ( getSelectionIndex( ) != NONE ) { e.result = elements[getSelectionIndex( )].getText( ); } } } ); accessible.addAccessibleControlListener( new AccessibleControlAdapter( ) { public void getChildAtPoint( AccessibleControlEvent e ) { Point pt = toControl( new Point( e.x, e.y ) ); e.childID = ( getBounds( ).contains( pt ) ) ? ACC.CHILDID_SELF : ACC.CHILDID_NONE; } public void getLocation( AccessibleControlEvent e ) { if ( getSelectionIndex( ) != NONE ) { Rectangle location = elements[getSelectionIndex( )].getBounds( ); Point pt = toDisplay( new Point( location.x, location.y ) ); e.x = pt.x; e.y = pt.y; e.width = location.width; e.height = location.height; } } public void getChildCount( AccessibleControlEvent e ) { e.detail = 0; } public void getRole( AccessibleControlEvent e ) { e.detail = ACC.ROLE_TABITEM; } public void getState( AccessibleControlEvent e ) { e.detail = ACC.STATE_NORMAL | ACC.STATE_SELECTABLE | ACC.STATE_SELECTED | ACC.STATE_FOCUSED | ACC.STATE_FOCUSABLE; } } ); addListener( SWT.Selection, new Listener( ) { public void handleEvent( Event event ) { if ( isFocusControl( ) ) { accessible.setFocus( ACC.CHILDID_SELF ); } } } ); addListener( SWT.FocusIn, new Listener( ) { public void handleEvent( Event event ) { accessible.setFocus( ACC.CHILDID_SELF ); } } ); } }
package com.marshalchen.common.commonUtils.networkUtils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Check network status */ public class BasicNetworkUtils { /** * Check if the device has connected network. * @param context * @return */ public static boolean checkNetwork(Context context) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo net = conn.getActiveNetworkInfo(); if (net != null && net.isConnected()) { return true; } return false; } /** * Check the network is Wifi or not * @param context * @return */ public static boolean isWifiConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWiFiNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWiFiNetworkInfo != null) { return mWiFiNetworkInfo.isAvailable(); } } return false; } }
package org.csstudio.sds.components.ui.internal.figures; import org.csstudio.sds.ui.figures.IBorderEquippedWidget; import org.csstudio.sds.util.CustomMediaFactory; import org.eclipse.draw2d.AbstractBorder; import org.eclipse.draw2d.AbstractLabeledBorder; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LineBorder; import org.eclipse.draw2d.SchemeBorder; import org.eclipse.draw2d.TitleBarBorder; import org.eclipse.draw2d.SchemeBorder.Scheme; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; /** * This adapter enriches <code>IFigure</code> instances with the abilities * that are defined by the <code>IBorderEquippedWidget</code> interface. * * @author Sven Wende * @version $Revision$ * */ public class BorderAdapter implements IBorderEquippedWidget { /** * The enriched <code>IFigure</code> instance. */ private IFigure _figure; /** * The border width. */ private int _borderWidth = 0; /** * The border color. */ private Color _borderColor = CustomMediaFactory.getInstance().getColor(0, 0, 0); /** * The border style. */ private Integer _borderStyle = 1; /** * The text for the border. */ private String _borderText; /** * Standard constructor. * * @param figure * The enriched <code>IFigure</code> instance. */ public BorderAdapter(final IFigure figure) { _figure = figure; } /** * {@inheritDoc} */ public final void setBorderWidth(final int width) { _borderWidth = width; refreshBorder(); } /** * {@inheritDoc} */ public final void setBorderColor(final Color borderColor) { _borderColor = borderColor; refreshBorder(); } /** * {@inheritDoc} */ public final void setBorderStyle(final int style) { _borderStyle = style; refreshBorder(); } /** * {@inheritDoc} */ public final void setBorderText(final String borderText) { _borderText = borderText; refreshBorder(); } /** * Refresh the border. */ private void refreshBorder() { AbstractBorder border; switch (_borderStyle) { case 0: border = null; break; case 1: border = this.createLineBorder(); break; case 2: border = this.createLabeledBorder(); break; case 3: border = this.createSchemeBorder(SchemeBorder.SCHEMES.RAISED); break; case 4: border = this.createSchemeBorder(SchemeBorder.SCHEMES.LOWERED); break; case 5: border = this.createStriatedBorder(); break; case 6: border = this.createShapeBorder(_borderWidth, _borderColor); break; default: border = null; break; } _figure.setBorder(border); } /** * Creates a LineBorder. * * @return AbstractBorder The requested Border */ private AbstractBorder createLineBorder() { if (_borderWidth>0) { LineBorder border = new LineBorder(); border.setWidth(_borderWidth); border.setColor(_borderColor); return border; } return null; } /** * Creates a AbstractLabeledBorder. * * @return AbstractBorder The requested Border */ private AbstractBorder createLabeledBorder() { AbstractLabeledBorder border = new TitleBarBorder(_borderText); return border; } /** * Creates a SchemeBorder. * @param scheme the scheme for the {@link SchemeBorder} * @return AbstractBorder The requested Border */ private AbstractBorder createSchemeBorder(final Scheme scheme) { SchemeBorder border = new SchemeBorder(scheme); return border; } /** * Creates a StriatedBorder. * * @return AbstractBorder The requested Border */ private AbstractBorder createStriatedBorder() { if (_borderWidth>0) { StriatedBorder border = new StriatedBorder(_borderWidth); border.setBorderColor(_borderColor); return border; } return null; } /** * Creates a ShapedBorder. * * @param borderWidth * the width of the border * @param borderColor * the color of the border * @return AbstractBorder The requested Border */ protected AbstractBorder createShapeBorder(final int borderWidth, final Color borderColor) { if (_borderWidth>0) { LineBorder border = new LineBorder(); border.setWidth(borderWidth); border.setColor(borderColor); return border; } return null; } /** * A striated Border. * * @author Kai Meyer */ private final class StriatedBorder extends AbstractBorder { /** * The insets for this Border. */ private Insets _insets; /** * The Height of the Border. */ private int _borderWidth; /** * The Color of the border. */ private Color _borderColor; /** * Constructor. * * @param borderWidth * The width of the Border */ public StriatedBorder(final int borderWidth) { _insets = new Insets(borderWidth); _borderWidth = borderWidth; } /** * Sets the Color of the border. * * @param borderColor * The Color for the border */ public void setBorderColor(final Color borderColor) { _borderColor = borderColor; } /** * {@inheritDoc} */ public Insets getInsets(final IFigure figure) { return _insets; } /** * {@inheritDoc} */ public void paint(final IFigure figure, final Graphics graphics, final Insets insets) { Rectangle bounds = figure.getBounds(); graphics.setForegroundColor(_borderColor); graphics.setBackgroundColor(_borderColor); graphics.setLineStyle(SWT.LINE_DOT); graphics.setLineWidth(_borderWidth); graphics.drawLine(bounds.x, bounds.y + _borderWidth / 2, bounds.x + bounds.width / 2, bounds.y + _borderWidth / 2); graphics.drawLine(bounds.x + bounds.width, bounds.y + _borderWidth / 2, bounds.x + bounds.width / 2, bounds.y + _borderWidth / 2); graphics.drawLine(bounds.x + bounds.width -1 - _borderWidth / 2, bounds.y, bounds.x + bounds.width -1 - _borderWidth / 2, bounds.y + bounds.height / 2); graphics.drawLine(bounds.x + bounds.width -1 - _borderWidth / 2, bounds.y + bounds.height, bounds.x + bounds.width -1 - _borderWidth / 2, bounds.y + bounds.height / 2); graphics.drawLine(bounds.x, bounds.y + bounds.height -1 - _borderWidth / 2, bounds.x + bounds.width / 2, bounds.y + bounds.height -1 - _borderWidth / 2); graphics.drawLine(bounds.x + bounds.width, bounds.y + bounds.height -1 - _borderWidth / 2, bounds.x + bounds.width / 2, bounds.y + bounds.height -1 - _borderWidth / 2); graphics.drawLine(bounds.x + _borderWidth / 2, bounds.y, bounds.x + _borderWidth / 2, bounds.y + bounds.height / 2); graphics.drawLine(bounds.x + _borderWidth / 2, bounds.y + bounds.height, bounds.x + _borderWidth / 2, bounds.y + bounds.height / 2); graphics.setLineStyle(SWT.LINE_SOLID); } } }
package com.axelor.meta; import com.axelor.common.StringUtils; import com.axelor.db.JPA; import com.axelor.db.Model; import com.axelor.db.QueryBinder; import com.axelor.event.Event; import com.axelor.event.NamedLiteral; import com.axelor.events.PostAction; import com.axelor.events.PreAction; import com.axelor.inject.Beans; import com.axelor.meta.schema.actions.Action; import com.axelor.meta.schema.actions.ActionGroup; import com.axelor.meta.schema.actions.ActionMethod; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.axelor.rpc.Context; import com.axelor.rpc.ContextEntity; import com.axelor.rpc.Resource; import com.axelor.script.CompositeScriptHelper; import com.axelor.script.ScriptHelper; import com.axelor.text.Templates; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Collections2; import com.google.common.escape.Escaper; import com.google.common.escape.Escapers; import com.google.common.io.CharStreams; import com.google.inject.servlet.RequestScoped; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.persistence.Query; import javax.script.Bindings; import net.bytebuddy.ByteBuddy; import net.bytebuddy.implementation.InvocationHandlerAdapter; import net.bytebuddy.matcher.ElementMatchers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RequestScoped public class ActionHandler { private final Logger log = LoggerFactory.getLogger(ActionHandler.class); private final ActionRequest request; private final Event<PreAction> preActionEvent; private final Event<PostAction> postActionEvent; private final Context context; private final Bindings bindings; private final ScriptHelper scriptHelper; private final Pattern pattern = Pattern.compile("^\\s*(select\\[\\]|select|action|call|eval):\\s*(.*)"); /** @deprecated Use {@link ActionExecutor#newActionHandler(ActionRequest)} instead. */ @Deprecated public ActionHandler(ActionRequest request) { this(request, Beans.get(ActionExecutor.class)); } private ActionHandler(ActionRequest request, ActionExecutor actionExecutor) { this(request, actionExecutor.getPreActionEvent(), actionExecutor.getPostActionEvent()); } ActionHandler( ActionRequest request, Event<PreAction> preActionEvent, Event<PostAction> postActionEvent) { this.request = request; this.preActionEvent = preActionEvent; this.postActionEvent = postActionEvent; this.context = request.getContext(); this.scriptHelper = new CompositeScriptHelper(this.context); this.bindings = this.scriptHelper.getBindings(); this.bindings.put("__me__", this); } public void firePreEvent(String name) { preActionEvent.select(NamedLiteral.of(name)).fire(new PreAction(name, context)); } public PostAction firePostEvent(String name, Object result) { PostAction event = new PostAction(name, context, result); postActionEvent.select(NamedLiteral.of(name)).fire(event); return event; } public Context getContext() { return context; } public ActionRequest getRequest() { return request; } /** * Evaluate the given <code>expression</code>. * * @param expression the expression to evaluate prefixed with action type followed by a <code>: * </code> * @param references * @return expression result */ public Object evaluate(String expression) { if (StringUtils.isEmpty(expression)) { return null; } String expr = expression.trim(); if (expr.startsWith("#{") && expr.endsWith("}")) { return handleScript(expr); } String kind = null; Matcher matcher = pattern.matcher(expression); if (matcher.matches()) { kind = matcher.group(1); expr = matcher.group(2); } else { return expr; } if ("eval".equals(kind)) { return handleScript(expr); } if ("action".equals(kind)) { return handleAction(expr); } if ("call".equals(kind)) { return handleCall(expr); } if ("select".equals(kind)) { return handleSelectOne(expr); } if ("select[]".equals(kind)) { return handleSelectAll(expr); } return expr; } public Object call(String className, String method) { ActionResponse response = new ActionResponse(); try { final Class<?> klass = Class.forName(className); final Method m = klass.getMethod(method, ActionRequest.class, ActionResponse.class); final Object obj = Beans.get(klass); m.invoke(obj, new Object[] {request, response}); } catch (Exception e) { log.error(e.getMessage(), e); response.setException(e); } return response; } public Object rpc(String className, String methodCall) { Pattern pattern = Pattern.compile("(\\w+)\\((.*?)\\)"); Matcher matcher = pattern.matcher(methodCall); if (!matcher.matches()) { return null; } String methodName = matcher.group(1); String methodArgs = matcher.group(2); try { final Class<?> klass = Class.forName(className); final List<Method> methods = Arrays.stream(klass.getMethods()) .filter(m -> m.getName().equals(methodName)) .collect(Collectors.toList()); // method not found if (methods.size() == 0) { throw new IllegalArgumentException( new NoSuchMethodException(String.format("%s.%s()", className, methodName))); } // validate no-args or only matched method if (methods.size() == 1 || StringUtils.isBlank(methodArgs)) { Method method = methods.get(0); if (method.getAnnotation(CallMethod.class) == null) { throw new IllegalArgumentException( String.format("Action not allowed: %s:%s", className, methodCall)); } } else { // validate exact matched method with arguments final Object validator = new ByteBuddy() .subclass(klass) .method(ElementMatchers.named(methodName)) .intercept( InvocationHandlerAdapter.of( (proxy, method, args) -> { if (method.getAnnotation(CallMethod.class) == null) { throw new IllegalArgumentException( String.format("Action not allowed: %s:%s", className, methodCall)); } return null; })) .make() .load(klass.getClassLoader()) .getLoaded() .newInstance(); // validate method scriptHelper.call(validator, methodCall); } final Object object = Beans.get(klass); return scriptHelper.call(object, methodCall); } catch (Exception e) { throw new IllegalArgumentException(e); } } public String template(Templates engine, Reader template) throws IOException { return engine.fromText(CharStreams.toString(template)).make(bindings).render(); } @SuppressWarnings("all") private Query select(String query, Object... params) { Preconditions.checkArgument(!Strings.isNullOrEmpty(query)); if (!query.toLowerCase().startsWith("select ")) query = "SELECT " + query; Query q = JPA.em().createQuery(query); QueryBinder.of(q).bind(bindings, params); return q; } public Object selectOne(String query, Object... params) { Query q = select(query, params); q.setMaxResults(1); try { return q.getResultList().get(0); } catch (Exception e) { } return null; } public Object selectAll(String query, Object... params) { try { return select(query, params).getResultList(); } catch (Exception e) { } return null; } public Object selectOne(String query) { return selectOne(query, new Object[] {}); } public Object selectAll(String query) { return selectAll(query, new Object[] {}); } @SuppressWarnings("all") public Object search(Class<?> entityClass, String filter, Map params) { filter = makeMethodCall( String.format("__repo__(%s).all().filter", entityClass.getSimpleName()), filter); com.axelor.db.Query q = (com.axelor.db.Query) handleScript(filter); q = q.bind(bindings); q = q.bind(params); return q.fetchOne(); } private static final Escaper STRING_ESCAPER = Escapers.builder().addEscape('"', "\\\"").build(); private String makeMethodCall(String method, String expression) { expression = expression.trim(); // check if expression is parameterized if (!expression.startsWith("(")) { if (!expression.matches("('|\")")) { expression = "\"" + STRING_ESCAPER.escape(expression) + "\""; } expression = "(" + expression + ")"; } return "#{" + method + expression + "}"; } private Object handleSelectOne(String expression) { expression = makeMethodCall("__me__.selectOne", expression); return handleScript(expression); } private Object handleSelectAll(String expression) { expression = makeMethodCall("__me__.selectAll", expression); return handleScript(expression); } private Object handleScript(String expression) { return scriptHelper.eval(expression); } private Object handleAction(String expression) { Action action = MetaStore.getAction(expression); if (action == null) { log.debug("no such action found: {}", expression); return null; } return action.execute(this); } private Object handleCall(String expression) { if (Strings.isNullOrEmpty(expression)) return null; String[] parts = expression.split("\\:"); if (parts.length != 2) { log.error("Invalid call expression: ", expression); return null; } ActionMethod action = new ActionMethod(); ActionMethod.Call call = new ActionMethod.Call(); call.setController(parts[0]); call.setMethod(parts[1]); action.setCall(call); action.setName(expression); return action.execute(this); } private static final String KEY_VALUES = "values"; private static final String KEY_ATTRS = "attrs"; private static final String KEY_VALUE = "value"; private Object toCompact(final Object item) { if (item == null) return null; if (item instanceof Collection) { return Collections2.transform( (Collection<?>) item, new Function<Object, Object>() { @Override public Object apply(Object input) { return toCompact(input); } }); } if (item instanceof Model) { Model bean = (Model) item; if (bean.getId() != null && JPA.em().contains(bean)) { return Resource.toMapCompact(bean); } } return item; } /** * This method finds m2o values which are managed instances and converts them to compact maps to * avoid unnecessary data transmission and prevents object graph recreation issues. */ @SuppressWarnings("all") private Object process(Object data) { if (data == null || data instanceof ContextEntity) return data; if (data instanceof Collection) { final List items = new ArrayList<>(); for (Object item : (Collection) data) { items.add(process(item)); } return items; } if (data instanceof Map) { final Map<String, Object> item = new HashMap<>((Map<String, Object>) data); if (item.containsKey(KEY_VALUES) && item.get(KEY_VALUES) instanceof Map && !(item.get(KEY_VALUES) instanceof ContextEntity)) { final Map<String, Object> values = (Map) item.get(KEY_VALUES); for (String key : values.keySet()) { Object value = values.get(key); if (value instanceof Model) { values.put(key, toCompact(value)); } } } if (item.containsKey(KEY_ATTRS) && item.get(KEY_ATTRS) instanceof Map && !(item.get(KEY_ATTRS) instanceof ContextEntity)) { final Map<String, Object> values = (Map) item.get(KEY_ATTRS); for (String key : values.keySet()) { final Map<String, Object> attrs = (Map) values.get(key); if (attrs.containsKey(KEY_VALUE)) { attrs.put(KEY_VALUE, toCompact(attrs.get(KEY_VALUE))); } } } return item; } return data; } public ActionResponse execute() { ActionResponse response = new ActionResponse(); String name = request.getAction(); if (name == null) { throw new NullPointerException("no action provided"); } String[] names = name.split(","); ActionGroup action = new ActionGroup(); for (String item : names) { action.addAction(item); } Object data = action.wrap(this); if (data instanceof ActionResponse) { return (ActionResponse) data; } response.setData(process(data)); response.setStatus(ActionResponse.STATUS_SUCCESS); return response; } }
package com.blankj.utilcode.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.blankj.utilcode.utils.ConstUtils.*; public class FileUtils { private FileUtils() { throw new UnsupportedOperationException("u can't fuck me..."); } /** * * * @param filePath * @return */ public static File getFileByPath(String filePath) { return StringUtils.isSpace(filePath) ? null : new File(filePath); } /** * * * @param filePath * @return {@code true}: <br>{@code false}: */ public static boolean isFileExists(String filePath) { return isFileExists(getFileByPath(filePath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean isFileExists(File file) { return file != null && file.exists(); } /** * * * @param dirPath * @return {@code true}: <br>{@code false}: */ public static boolean isDir(String dirPath) { return isDir(getFileByPath(dirPath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean isDir(File file) { return isFileExists(file) && file.isDirectory(); } /** * * * @param filePath * @return {@code true}: <br>{@code false}: */ public static boolean isFile(String filePath) { return isFile(getFileByPath(filePath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean isFile(File file) { return isFileExists(file) && file.isFile(); } /** * * * @param dirPath * @return {@code true}: <br>{@code false}: */ public static boolean createOrExistsDir(String dirPath) { return createOrExistsDir(getFileByPath(dirPath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean createOrExistsDir(File file) { // truefalse return file != null && (file.exists() ? file.isDirectory() : file.mkdirs()); } /** * * * @param filePath * @return {@code true}: <br>{@code false}: */ public static boolean createOrExistsFile(String filePath) { return createOrExistsFile(getFileByPath(filePath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean createOrExistsFile(File file) { if (file == null) return false; // truefalse if (file.exists()) return file.isFile(); if (!createOrExistsDir(file.getParentFile())) return false; try { return file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * * * @param filePath * @return {@code true}: <br>{@code false}: */ public static boolean createFileByDeleteOldFile(String filePath) { return createFileByDeleteOldFile(getFileByPath(filePath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean createFileByDeleteOldFile(File file) { if (file == null) return false; // false if (file.exists() && file.isFile() && !file.delete()) return false; // false if (!createOrExistsDir(file.getParentFile())) return false; try { return file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * * * @param srcDirPath * @param destDirPath * @param isMove * @return {@code true}: <br>{@code false}: */ private static boolean copyOrMoveDir(String srcDirPath, String destDirPath, boolean isMove) { return copyOrMoveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath), isMove); } /** * * * @param srcDir * @param destDir * @param isMove * @return {@code true}: <br>{@code false}: */ private static boolean copyOrMoveDir(File srcDir, File destDir, boolean isMove) { if (srcDir == null || destDir == null) return false; // false // srcPath : F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res // destPath: F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res1 String srcPath = srcDir.getPath() + File.separator; String destPath = destDir.getPath() + File.separator; if (destPath.contains(srcPath)) return false; // false if (!srcDir.exists() || !srcDir.isDirectory()) return false; // false if (!createOrExistsDir(destDir)) return false; File[] files = srcDir.listFiles(); for (File file : files) { File oneDestFile = new File(destPath + file.getName()); if (file.isFile()) { // false if (!copyOrMoveFile(file, oneDestFile, isMove)) return false; } else if (file.isDirectory()) { // false if (!copyOrMoveDir(file, oneDestFile, isMove)) return false; } } return !isMove || deleteDir(srcDir); } /** * * * @param srcFilePath * @param destFilePath * @param isMove * @return {@code true}: <br>{@code false}: */ private static boolean copyOrMoveFile(String srcFilePath, String destFilePath, boolean isMove) { return copyOrMoveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath), isMove); } /** * * * @param srcFile * @param destFile * @param isMove * @return {@code true}: <br>{@code false}: */ private static boolean copyOrMoveFile(File srcFile, File destFile, boolean isMove) { if (srcFile == null || destFile == null) return false; // false if (!srcFile.exists() || !srcFile.isFile()) return false; // false if (destFile.exists() && destFile.isFile()) return false; // false if (!createOrExistsDir(destFile.getParentFile())) return false; try { return writeFileFromIS(destFile, new FileInputStream(srcFile), false) && !(isMove && !deleteFile(srcFile)); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } /** * * * @param srcDirPath * @param destDirPath * @return {@code true}: <br>{@code false}: */ public static boolean copyDir(String srcDirPath, String destDirPath) { return copyDir(getFileByPath(srcDirPath), getFileByPath(destDirPath)); } /** * * * @param srcDir * @param destDir * @return {@code true}: <br>{@code false}: */ public static boolean copyDir(File srcDir, File destDir) { return copyOrMoveDir(srcDir, destDir, false); } /** * * * @param srcFilePath * @param destFilePath * @return {@code true}: <br>{@code false}: */ public static boolean copyFile(String srcFilePath, String destFilePath) { return copyFile(getFileByPath(srcFilePath), getFileByPath(destFilePath)); } /** * * * @param srcFile * @param destFile * @return {@code true}: <br>{@code false}: */ public static boolean copyFile(File srcFile, File destFile) { return copyOrMoveFile(srcFile, destFile, false); } /** * * * @param srcDirPath * @param destDirPath * @return {@code true}: <br>{@code false}: */ public static boolean moveDir(String srcDirPath, String destDirPath) { return moveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath)); } /** * * * @param srcDir * @param destDir * @return {@code true}: <br>{@code false}: */ public static boolean moveDir(File srcDir, File destDir) { return copyOrMoveDir(srcDir, destDir, true); } /** * * * @param srcFilePath * @param destFilePath * @return {@code true}: <br>{@code false}: */ public static boolean moveFile(String srcFilePath, String destFilePath) { return moveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath)); } /** * * * @param srcFile * @param destFile * @return {@code true}: <br>{@code false}: */ public static boolean moveFile(File srcFile, File destFile) { return copyOrMoveFile(srcFile, destFile, true); } /** * * * @param dirPath * @return {@code true}: <br>{@code false}: */ public static boolean deleteDir(String dirPath) { return deleteDir(getFileByPath(dirPath)); } /** * * * @param dir * @return {@code true}: <br>{@code false}: */ public static boolean deleteDir(File dir) { if (dir == null) return false; // true if (!dir.exists()) return true; // false if (!dir.isDirectory()) return false; File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { if (!deleteFile(file)) return false; } else if (file.isDirectory()) { if (!deleteDir(file)) return false; } } return dir.delete(); } /** * * * @param srcFilePath * @return {@code true}: <br>{@code false}: */ public static boolean deleteFile(String srcFilePath) { return deleteFile(getFileByPath(srcFilePath)); } /** * * * @param file * @return {@code true}: <br>{@code false}: */ public static boolean deleteFile(File file) { return file != null && (!file.exists() || file.isFile() && file.delete()); } /** * * * @param dirPath * @param isRecursive * @return */ public static List<File> listFilesInDir(String dirPath, boolean isRecursive) { return listFilesInDir(getFileByPath(dirPath), isRecursive); } /** * * * @param dir * @param isRecursive * @return */ public static List<File> listFilesInDir(File dir, boolean isRecursive) { if (isRecursive) return listFilesInDir(dir); if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); Collections.addAll(list, dir.listFiles()); return list; } /** * * * @param dirPath * @return */ public static List<File> listFilesInDir(String dirPath) { return listFilesInDir(getFileByPath(dirPath)); } /** * * * @param dir * @return */ public static List<File> listFilesInDir(File dir) { if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); File[] files = dir.listFiles(); for (File file : files) { list.add(file); if (file.isDirectory()) { list.addAll(listFilesInDir(file)); } } return list; } /** * suffix * <p></p> * * @param dirPath * @param suffix * @param isRecursive * @return */ public static List<File> listFilesInDirWithFilter(String dirPath, String suffix, boolean isRecursive) { return listFilesInDirWithFilter(getFileByPath(dirPath), suffix, isRecursive); } /** * suffix * <p></p> * * @param dir * @param suffix * @param isRecursive * @return */ public static List<File> listFilesInDirWithFilter(File dir, String suffix, boolean isRecursive) { if (isRecursive) return listFilesInDirWithFilter(dir, suffix); if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); File[] files = dir.listFiles(); for (File file : files) { if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) { list.add(file); } } return list; } /** * suffix * <p></p> * * @param dirPath * @param suffix * @return */ public static List<File> listFilesInDirWithFilter(String dirPath, String suffix) { return listFilesInDirWithFilter(getFileByPath(dirPath), suffix); } /** * suffix * <p></p> * * @param dir * @param suffix * @return */ public static List<File> listFilesInDirWithFilter(File dir, String suffix) { if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); File[] files = dir.listFiles(); for (File file : files) { if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) { list.add(file); } if (file.isDirectory()) { list.addAll(listFilesInDirWithFilter(file, suffix)); } } return list; } /** * filter * * @param dirPath * @param filter * @param isRecursive * @return */ public static List<File> listFilesInDirWithFilter(String dirPath, FilenameFilter filter, boolean isRecursive) { return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive); } /** * filter * * @param dir * @param filter * @param isRecursive * @return */ public static List<File> listFilesInDirWithFilter(File dir, FilenameFilter filter, boolean isRecursive) { if (isRecursive) return listFilesInDirWithFilter(dir, filter); if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); File[] files = dir.listFiles(); for (File file : files) { if (filter.accept(file.getParentFile(), file.getName())) { list.add(file); } } return list; } /** * filter * * @param dirPath * @param filter * @return */ public static List<File> listFilesInDirWithFilter(String dirPath, FilenameFilter filter) { return listFilesInDirWithFilter(getFileByPath(dirPath), filter); } /** * filter * * @param dir * @param filter * @return */ public static List<File> listFilesInDirWithFilter(File dir, FilenameFilter filter) { if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); File[] files = dir.listFiles(); for (File file : files) { if (filter.accept(file.getParentFile(), file.getName())) { list.add(file); } if (file.isDirectory()) { list.addAll(listFilesInDirWithFilter(file, filter)); } } return list; } /** * * <p></p> * * @param dirPath * @param fileName * @return */ public static List<File> searchFileInDir(String dirPath, String fileName) { return searchFileInDir(getFileByPath(dirPath), fileName); } /** * * <p></p> * * @param dir * @param fileName * @return */ public static List<File> searchFileInDir(File dir, String fileName) { if (dir == null || !isDir(dir)) return null; List<File> list = new ArrayList<>(); File[] files = dir.listFiles(); for (File file : files) { if (file.getName().toUpperCase().equals(fileName.toUpperCase())) { list.add(file); } if (file.isDirectory()) { list.addAll(listFilesInDirWithFilter(file, fileName)); } } return list; } /** * * * @param filePath * @param is * @param append * @return {@code true}: <br>{@code false}: */ public static boolean writeFileFromIS(String filePath, InputStream is, boolean append) { return writeFileFromIS(getFileByPath(filePath), is, append); } /** * * * @param file * @param is * @param append * @return {@code true}: <br>{@code false}: */ public static boolean writeFileFromIS(File file, InputStream is, boolean append) { if (file == null || is == null) return false; if (!createOrExistsFile(file)) return false; OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file, append)); byte data[] = new byte[KB]; int len; while ((len = is.read(data, 0, KB)) != -1) { os.write(data, 0, len); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { closeIO(is, os); } } /** * * * @param filePath * @param content * @param append * @return {@code true}: <br>{@code false}: */ public static boolean writeFileFromString(String filePath, String content, boolean append) { return writeFileFromString(getFileByPath(filePath), content, append); } /** * * * @param file * @param content * @param append * @return {@code true}: <br>{@code false}: */ public static boolean writeFileFromString(File file, String content, boolean append) { if (file == null || content == null) return false; if (!createOrExistsFile(file)) return false; FileWriter fileWriter = null; try { fileWriter = new FileWriter(file, append); fileWriter.write(content); return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { closeIO(fileWriter); } } /** * List * * @param filePath * @param charsetName * @return */ public static List<String> readFile2List(String filePath, String charsetName) { return readFile2List(getFileByPath(filePath), charsetName); } /** * List * * @param file * @param charsetName * @return */ public static List<String> readFile2List(File file, String charsetName) { return readFile2List(file, 0, 0x7FFFFFFF, charsetName); } /** * List * * @param filePath * @param st * @param end * @param charsetName * @return list */ public static List<String> readFile2List(String filePath, int st, int end, String charsetName) { return readFile2List(getFileByPath(filePath), st, end, charsetName); } /** * List * * @param file * @param st * @param end * @param charsetName * @return startendlist */ public static List<String> readFile2List(File file, int st, int end, String charsetName) { if (file == null) return null; if (st > end) return null; BufferedReader reader = null; try { String line; int curLine = 1; List<String> list = new ArrayList<>(); if (StringUtils.isSpace(charsetName)) { reader = new BufferedReader(new FileReader(file)); } else { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName)); } while ((line = reader.readLine()) != null) { if (curLine > end) break; if (st <= curLine && curLine <= end) list.add(line); ++curLine; } return list; } catch (IOException e) { e.printStackTrace(); return null; } finally { closeIO(reader); } } /** * * * @param filePath * @param charsetName * @return */ public static String readFile2String(String filePath, String charsetName) { return readFile2String(getFileByPath(filePath), charsetName); } /** * * * @param file * @param charsetName * @return */ public static String readFile2String(File file, String charsetName) { if (file == null) return null; BufferedReader reader = null; try { StringBuilder sb = new StringBuilder(); if (StringUtils.isSpace(charsetName)) { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); } else { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName)); } String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\r\n");// windows\r\nLinux\n } return sb.delete(sb.length() - 2, sb.length()).toString(); } catch (IOException e) { e.printStackTrace(); return null; } finally { closeIO(reader); } } /** * * * @param filePath * @return StringBuilder */ public static byte[] readFile2Bytes(String filePath) { return readFile2Bytes(getFileByPath(filePath)); } /** * * * @param file * @return StringBuilder */ public static byte[] readFile2Bytes(File file) { if (file == null) return null; try { return ConvertUtils.inputStream2Bytes(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } /** * * * @param filePath * @return */ public static String getFileCharsetSimple(String filePath) { return getFileCharsetSimple(getFileByPath(filePath)); } /** * * * @param file * @return */ public static String getFileCharsetSimple(File file) { int p = 0; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); p = (is.read() << 8) + is.read(); } catch (IOException e) { e.printStackTrace(); } finally { closeIO(is); } switch (p) { case 0xefbb: return "UTF-8"; case 0xfffe: return "Unicode"; case 0xfeff: return "UTF-16BE"; default: return "GBK"; } } /** * * * @param filePath * @return */ public static int getFileLines(String filePath) { return getFileLines(getFileByPath(filePath)); } /** * * * @param file * @return */ public static int getFileLines(File file) { int count = 1; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[KB]; int readChars; while ((readChars = is.read(buffer, 0, KB)) != -1) { for (int i = 0; i < readChars; ++i) { if (buffer[i] == '\n') ++count; } } } catch (IOException e) { e.printStackTrace(); } finally { closeIO(is); } return count; } /** * * * @param filePath * @return */ public static String getFileSize(String filePath) { return getFileSize(getFileByPath(filePath)); } /** * * <p>getFileSize(file, ConstUtils.MB); MB</p> * * @param file * @return */ public static String getFileSize(File file) { if (!isFileExists(file)) return ""; return ConvertUtils.byte2FitSize(file.length()); } /** * MD5 * * @param filePath * @return MD5 */ public static String getFileMD5(String filePath) { return getFileMD5(getFileByPath(filePath)); } /** * MD5 * * @param file * @return MD5 */ public static String getFileMD5(File file) { return EncryptUtils.encryptMD5File2String(file); } /** * IO * * @param closeables closeable */ public static void closeIO(Closeable... closeables) { if (closeables == null) return; try { for (Closeable closeable : closeables) { if (closeable != null) { closeable.close(); } } } catch (IOException e) { e.printStackTrace(); } } /** * * * @param file * @return filePath */ public static String getDirName(File file) { if (file == null) return null; return getDirName(file.getPath()); } /** * * * @param filePath * @return filePath */ public static String getDirName(String filePath) { if (StringUtils.isSpace(filePath)) return filePath; int lastSep = filePath.lastIndexOf(File.separator); return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1); } /** * * * @param file * @return */ public static String getFileName(File file) { if (file == null) return null; return getFileName(file.getPath()); } /** * * * @param filePath * @return */ public static String getFileName(String filePath) { if (StringUtils.isSpace(filePath)) return filePath; int lastSep = filePath.lastIndexOf(File.separator); return lastSep == -1 ? filePath : filePath.substring(lastSep + 1); } /** * * * @param file * @return */ public static String getFileNameNoExtension(File file) { if (file == null) return null; return getFileNameNoExtension(file.getPath()); } /** * * * @param filePath * @return */ public static String getFileNameNoExtension(String filePath) { if (StringUtils.isSpace(filePath)) return filePath; int lastPoi = filePath.lastIndexOf('.'); int lastSep = filePath.lastIndexOf(File.separator); if (lastSep == -1) { return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi)); } if (lastPoi == -1 || lastSep > lastPoi) { return filePath.substring(lastSep + 1); } return filePath.substring(lastSep + 1, lastPoi); } /** * * * @param file * @return */ public static String getFileExtension(File file) { if (file == null) return null; return getFileExtension(file.getPath()); } /** * * * @param filePath * @return */ public static String getFileExtension(String filePath) { if (StringUtils.isSpace(filePath)) return filePath; int lastPoi = filePath.lastIndexOf('.'); int lastSep = filePath.lastIndexOf(File.separator); if (lastPoi == -1 || lastSep >= lastPoi) return ""; return filePath.substring(lastPoi+1); } }
package org.hisp.dhis.android.testapp.program; import android.support.test.runner.AndroidJUnit4; import org.hisp.dhis.android.core.common.FormType; import org.hisp.dhis.android.core.data.database.SyncedDatabaseMockIntegrationShould; import org.hisp.dhis.android.core.period.FeatureType; import org.hisp.dhis.android.core.period.PeriodType; import org.hisp.dhis.android.core.program.ProgramStage; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @RunWith(AndroidJUnit4.class) public class ProgramStageCollectionRepositoryMockIntegrationShould extends SyncedDatabaseMockIntegrationShould { @Test public void find_all() { List<ProgramStage> programStages = d2.programModule().programStages .get(); assertThat(programStages.size(), is(2)); } @Test public void include_object_style_as_children() { ProgramStage programStage = d2.programModule().programStages .one() .getWithAllChildren(); assertThat(programStage.style().icon(), is("program-stage-icon")); assertThat(programStage.style().color(), is("#444")); } @Test public void include_program_stage_data_elements_as_children() { ProgramStage programStage = d2.programModule().programStages .one() .getWithAllChildren(); assertThat(programStage.programStageDataElements().size(), is(3)); } @Test public void include_program_stage_section_as_children() { ProgramStage programStage = d2.programModule().programStages .one() .getWithAllChildren(); assertThat(programStage.programStageSections().size(), is(1)); } @Test public void filter_by_description() { List<ProgramStage> programStages = d2.programModule().programStages .byDescription() .eq("Description") .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_display_description() { List<ProgramStage> programStages = d2.programModule().programStages .byDisplayDescription() .eq("Display Description") .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_execution_date_label() { List<ProgramStage> programStages = d2.programModule().programStages .byExectuionDateLabel() .eq("Visit date") .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_allow_generate_next_visit() { List<ProgramStage> programStages = d2.programModule().programStages .byAllowGenerateNextVisit() .isFalse() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_valid_complete_only() { List<ProgramStage> programStages = d2.programModule().programStages .byValidCompleteOnly() .isTrue() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_report_date_to_use() { List<ProgramStage> programStages = d2.programModule().programStages .byReportDateToUse() .eq("report_date_to_use") .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_open_after_enrollment() { List<ProgramStage> programStages = d2.programModule().programStages .byOpenAfterEnrollment() .isFalse() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_repeatable() { List<ProgramStage> programStages = d2.programModule().programStages .byRepeatable() .isFalse() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_capture_coordinates() { List<ProgramStage> programStages = d2.programModule().programStages .byCaptureCoordinates() .isTrue() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_feature_type() { List<ProgramStage> programStages = d2.programModule().programStages .byFeatureType() .eq(FeatureType.POINT) .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_form_type() { List<ProgramStage> programStages = d2.programModule().programStages .byFormType() .eq(FormType.DEFAULT) .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_display_generate_event_box() { List<ProgramStage> programStages = d2.programModule().programStages .byDisplayGenerateEventBox() .isFalse() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_generated_by_enrollment_data() { List<ProgramStage> programStages = d2.programModule().programStages .byGeneratedByEnrollmentDate() .isFalse() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_autogenerate_event() { List<ProgramStage> programStages = d2.programModule().programStages .byAutoGenerateEvent() .isTrue() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_sort_order() { List<ProgramStage> programStages = d2.programModule().programStages .bySortOrder() .eq(1) .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_hide_due_date() { List<ProgramStage> programStages = d2.programModule().programStages .byHideDueDate() .isFalse() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_block_entry_form() { List<ProgramStage> programStages = d2.programModule().programStages .byBlockEntryForm() .isTrue() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_min_days_from_start() { List<ProgramStage> programStages = d2.programModule().programStages .byMinDaysFromStart() .eq(0) .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_standard_interval() { List<ProgramStage> programStages = d2.programModule().programStages .byStandardInterval() .eq(0) .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_period_type() { List<ProgramStage> programStages = d2.programModule().programStages .byPeriodType() .eq(PeriodType.Monthly) .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_program() { List<ProgramStage> programStages = d2.programModule().programStages .byProgramUid() .eq("lxAQ7Zs9VYR") .get(); assertThat(programStages.size(), is(2)); } @Test public void filter_by_access_data_write() { List<ProgramStage> programStages = d2.programModule().programStages .byAccessDataWrite() .isTrue() .get(); assertThat(programStages.size(), is(1)); } @Test public void filter_by_remind_completed() { List<ProgramStage> programStages = d2.programModule().programStages .byRemindCompleted() .isTrue() .get(); assertThat(programStages.size(), is(1)); } }
package ai.subut.kurjun.db.file; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.TxMaker; /** * File based db. This db stores records in a key value pairs. * */ public class FileDb implements Closeable { private final File file; protected final TxMaker txMaker; /** * Constructs file based db backed by supplied file. * * @param dbFile * @throws IOException */ public FileDb( String dbFile ) throws IOException { this( dbFile, false ); } FileDb( String dbFile, boolean readOnly ) throws IOException { if ( dbFile == null || dbFile.isEmpty() ) { throw new IllegalArgumentException( "File db path can not be empty" ); } Path path = Paths.get( dbFile ); // ensure parent dirs do exist Files.createDirectories( path.getParent() ); this.file = path.toFile(); DBMaker dbMaker = DBMaker.newFileDB( file ); if ( readOnly ) { dbMaker.readOnly(); } // TODO: Check on standalone env of temporary CL swapping ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); this.txMaker = dbMaker .closeOnJvmShutdown() .mmapFileEnableIfSupported() .snapshotEnable() .makeTxMaker(); } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Gets underlying db file. * * @return file to underlying db file */ public File getFile() { return file; } /** * Checks if association exists for the key in a map with supplied name. * * @param mapName name of the map to check * @param key key to check association for * @return {@code true} if map contains association for the key; * {@code false} otherwise */ public boolean contains( String mapName, Object key ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { return db.getHashMap( mapName ).containsKey( key ); } finally { db.commit(); db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Gets value for the key in a map with supplied name. * * @param <T> type of the value * @param mapName name of the map to get value from * @param key the key to look for * @param clazz type of the returned value * @return */ public <T> T get( String mapName, Object key, Class<T> clazz ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { return ( T ) db.getHashMap( mapName ).get( key ); } finally { db.commit(); db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Gets a readonly snapshot view of the map with supplied name. * * @param <K> type of map keys * @param <V> type of map values * @param mapName name of the map to get * @return readonly view of the map */ public <K, V> Map<K, V> get( String mapName ) { // it occurs when there was no map with given name and tried to get a snapshot contains( mapName, "dummy-key" ); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); Map<K, V> result = new HashMap<>(); DB db = txMaker.makeTx(); try { Map<K, V> snapshot = ( Map<K, V> ) db.getHashMap( mapName ).snapshot(); result.putAll( snapshot ); } finally { db.commit(); db.close(); } return Collections.unmodifiableMap( result ); } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Associated the key to the given value in a map with supplied name. * * @param <T> type of the value * @param mapName name of the map to put mapping to * @param key key value * @param value value to be associated with the key * @return the previous value associated with key, or null if there was no * mapping for key */ public <T> T put( String mapName, Object key, T value ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { T put = ( T ) db.getHashMap( mapName ).put( key, value ); db.commit(); return put; } finally { db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } /** * Removes mapping for the key in a map with supplied name. * * @param <T> type of the value * @param mapName map name * @param key key value to remove mapping for * @return the previous value associated with key, or null if there was no * mapping for key */ public <T> T remove( String mapName, Object key ) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); DB db = txMaker.makeTx(); try { T removed = ( T ) db.getHashMap( mapName ).remove( key ); db.commit(); return removed; } finally { db.close(); } } finally { Thread.currentThread().setContextClassLoader( tccl ); } } @Override public void close() throws IOException { if ( txMaker != null ) { txMaker.close(); } } }
package io.debezium.connector.postgresql.connection.pgoutput; import static java.util.stream.Collectors.toMap; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.postgresql.replication.fluent.logical.ChainedLogicalStreamBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.connector.postgresql.PostgresConnectorConfig; import io.debezium.connector.postgresql.PostgresStreamingChangeEventSource.PgConnectionSupplier; import io.debezium.connector.postgresql.PostgresType; import io.debezium.connector.postgresql.TypeRegistry; import io.debezium.connector.postgresql.UnchangedToastedReplicationMessageColumn; import io.debezium.connector.postgresql.connection.AbstractMessageDecoder; import io.debezium.connector.postgresql.connection.AbstractReplicationMessageColumn; import io.debezium.connector.postgresql.connection.Lsn; import io.debezium.connector.postgresql.connection.MessageDecoderContext; import io.debezium.connector.postgresql.connection.PostgresConnection; import io.debezium.connector.postgresql.connection.ReplicationMessage.Column; import io.debezium.connector.postgresql.connection.ReplicationMessage.NoopMessage; import io.debezium.connector.postgresql.connection.ReplicationMessage.Operation; import io.debezium.connector.postgresql.connection.ReplicationStream.ReplicationMessageProcessor; import io.debezium.connector.postgresql.connection.TransactionMessage; import io.debezium.connector.postgresql.connection.WalPositionLocator; import io.debezium.relational.ColumnEditor; import io.debezium.relational.Table; import io.debezium.relational.TableId; import io.debezium.util.HexConverter; import io.debezium.util.Strings; public class PgOutputMessageDecoder extends AbstractMessageDecoder { private static final Logger LOGGER = LoggerFactory.getLogger(PgOutputMessageDecoder.class); private static final Instant PG_EPOCH = LocalDate.of(2000, 1, 1).atStartOfDay().toInstant(ZoneOffset.UTC); private static final byte SPACE = 32; private final MessageDecoderContext decoderContext; private final PostgresConnection connection; private Instant commitTimestamp; private int transactionId; public enum MessageType { RELATION, BEGIN, COMMIT, INSERT, UPDATE, DELETE, TYPE, ORIGIN, TRUNCATE; public static MessageType forType(char type) { switch (type) { case 'R': return RELATION; case 'B': return BEGIN; case 'C': return COMMIT; case 'I': return INSERT; case 'U': return UPDATE; case 'D': return DELETE; case 'Y': return TYPE; case 'O': return ORIGIN; case 'T': return TRUNCATE; default: throw new IllegalArgumentException("Unsupported message type: " + type); } } } public PgOutputMessageDecoder(MessageDecoderContext decoderContext) { this.decoderContext = decoderContext; this.connection = new PostgresConnection(decoderContext.getConfig().getJdbcConfig(), decoderContext.getSchema().getTypeRegistry()); } @Override public boolean shouldMessageBeSkipped(ByteBuffer buffer, Lsn lastReceivedLsn, Lsn startLsn, WalPositionLocator walPosition) { // Cache position as we're going to peak at the first byte to determine message type // We need to reprocess all BEGIN/COMMIT messages regardless. int position = buffer.position(); try { MessageType type = MessageType.forType((char) buffer.get()); LOGGER.trace("Message Type: {}", type); final boolean candidateForSkipping = super.shouldMessageBeSkipped(buffer, lastReceivedLsn, startLsn, walPosition); switch (type) { case COMMIT: case BEGIN: case RELATION: // BEGIN // These types should always be processed due to the nature that they provide // the stream with pertinent per-transaction boundary state we will need to // always cache as we potentially might reprocess the stream from an earlier // LSN point. // RELATION // These messages are always sent with a lastReceivedLSN=0; and we need to // always accept these to keep per-stream table state cached properly. LOGGER.trace("{} messages are always reprocessed", type); return false; default: // INSERT/UPDATE/DELETE/TRUNCATE/TYPE/ORIGIN // These should be excluded based on the normal behavior, delegating to default method return candidateForSkipping; } } finally { // Reset buffer position buffer.position(position); } } @Override public void processNotEmptyMessage(ByteBuffer buffer, ReplicationMessageProcessor processor, TypeRegistry typeRegistry) throws SQLException, InterruptedException { if (LOGGER.isTraceEnabled()) { if (!buffer.hasArray()) { throw new IllegalStateException("Invalid buffer received from PG server during streaming replication"); } final byte[] source = buffer.array(); // Extend the array by two as we might need to append two chars and set them to space by default final byte[] content = Arrays.copyOfRange(source, buffer.arrayOffset(), source.length + 2); final int lastPos = content.length - 1; content[lastPos - 1] = SPACE; content[lastPos] = SPACE; LOGGER.trace("Message arrived from database {}", HexConverter.convertToHexString(content)); } final MessageType messageType = MessageType.forType((char) buffer.get()); switch (messageType) { case BEGIN: handleBeginMessage(buffer, processor); break; case COMMIT: handleCommitMessage(buffer, processor); break; case RELATION: handleRelationMessage(buffer, typeRegistry); break; case INSERT: decodeInsert(buffer, typeRegistry, processor); break; case UPDATE: decodeUpdate(buffer, typeRegistry, processor); break; case DELETE: decodeDelete(buffer, typeRegistry, processor); break; case TRUNCATE: if (decoderContext.getConfig().truncateHandlingMode() == PostgresConnectorConfig.TruncateHandlingMode.INCLUDE) { decodeTruncate(buffer, typeRegistry, processor); } else { LOGGER.trace("Message Type {} skipped, not processed.", messageType); } break; default: LOGGER.trace("Message Type {} skipped, not processed.", messageType); break; } } @Override public ChainedLogicalStreamBuilder optionsWithMetadata(ChainedLogicalStreamBuilder builder) { return builder.withSlotOption("proto_version", 1) .withSlotOption("publication_names", decoderContext.getConfig().publicationName()); } @Override public ChainedLogicalStreamBuilder optionsWithoutMetadata(ChainedLogicalStreamBuilder builder) { return builder; } /** * Callback handler for the 'B' begin replication message. * * @param buffer The replication stream buffer * @param processor The replication message processor */ private void handleBeginMessage(ByteBuffer buffer, ReplicationMessageProcessor processor) throws SQLException, InterruptedException { final Lsn lsn = Lsn.valueOf(buffer.getLong()); // LSN this.commitTimestamp = PG_EPOCH.plus(buffer.getLong(), ChronoUnit.MICROS); this.transactionId = buffer.getInt(); LOGGER.trace("Event: {}", MessageType.BEGIN); LOGGER.trace("Final LSN of transaction: {}", lsn); LOGGER.trace("Commit timestamp of transaction: {}", commitTimestamp); LOGGER.trace("XID of transaction: {}", transactionId); processor.process(new TransactionMessage(Operation.BEGIN, transactionId, commitTimestamp)); } /** * Callback handler for the 'C' commit replication message. * * @param buffer The replication stream buffer * @param processor The replication message processor */ private void handleCommitMessage(ByteBuffer buffer, ReplicationMessageProcessor processor) throws SQLException, InterruptedException { int flags = buffer.get(); // flags, currently unused final Lsn lsn = Lsn.valueOf(buffer.getLong()); // LSN of the commit final Lsn endLsn = Lsn.valueOf(buffer.getLong()); // End LSN of the transaction Instant commitTimestamp = PG_EPOCH.plus(buffer.getLong(), ChronoUnit.MICROS); LOGGER.trace("Event: {}", MessageType.COMMIT); LOGGER.trace("Flags: {} (currently unused and most likely 0)", flags); LOGGER.trace("Commit LSN: {}", lsn); LOGGER.trace("End LSN of transaction: {}", endLsn); LOGGER.trace("Commit timestamp of transaction: {}", commitTimestamp); processor.process(new TransactionMessage(Operation.COMMIT, transactionId, commitTimestamp)); } /** * Callback handler for the 'R' relation replication message. * * @param buffer The replication stream buffer * @param typeRegistry The postgres type registry */ private void handleRelationMessage(ByteBuffer buffer, TypeRegistry typeRegistry) throws SQLException { int relationId = buffer.getInt(); String schemaName = readString(buffer); String tableName = readString(buffer); int replicaIdentityId = buffer.get(); short columnCount = buffer.getShort(); LOGGER.trace("Event: {}, RelationId: {}, Replica Identity: {}, Columns: {}", MessageType.RELATION, relationId, replicaIdentityId, columnCount); LOGGER.trace("Schema: '{}', Table: '{}'", schemaName, tableName); // Perform several out-of-bands database metadata queries Map<String, Optional<Object>> columnDefaults; Map<String, Boolean> columnOptionality; List<String> primaryKeyColumns; final DatabaseMetaData databaseMetadata = connection.connection().getMetaData(); final TableId tableId = new TableId(null, schemaName, tableName); final List<io.debezium.relational.Column> readColumns = getTableColumnsFromDatabase(connection, databaseMetadata, tableId); columnDefaults = readColumns.stream() .filter(io.debezium.relational.Column::hasDefaultValue) .collect(toMap(io.debezium.relational.Column::name, column -> Optional.ofNullable(column.defaultValue()))); columnOptionality = readColumns.stream().collect(toMap(io.debezium.relational.Column::name, io.debezium.relational.Column::isOptional)); primaryKeyColumns = connection.readPrimaryKeyNames(databaseMetadata, tableId); if (primaryKeyColumns == null || primaryKeyColumns.isEmpty()) { LOGGER.warn("Primary keys are not defined for table '{}', defaulting to unique indices", tableName); primaryKeyColumns = connection.readTableUniqueIndices(databaseMetadata, tableId); } List<ColumnMetaData> columns = new ArrayList<>(); Set<String> columnNames = new HashSet<>(); for (short i = 0; i < columnCount; ++i) { byte flags = buffer.get(); String columnName = Strings.unquoteIdentifierPart(readString(buffer)); int columnType = buffer.getInt(); int attypmod = buffer.getInt(); final PostgresType postgresType = typeRegistry.get(columnType); boolean key = isColumnInPrimaryKey(schemaName, tableName, columnName, primaryKeyColumns); Boolean optional = columnOptionality.get(columnName); if (optional == null) { LOGGER.warn("Column '{}' optionality could not be determined, defaulting to true", columnName); optional = true; } final boolean hasDefault = columnDefaults.containsKey(columnName); final Object defaultValue = columnDefaults.getOrDefault(columnName, Optional.empty()).orElse(null); columns.add(new ColumnMetaData(columnName, postgresType, key, optional, hasDefault, defaultValue, attypmod)); columnNames.add(columnName); } // Remove any PKs that do not exist as part of this this relation message. This can occur when issuing // multiple schema changes in sequence since the lookup of primary keys is an out-of-band procedure, without // any logical linkage or context to the point in time the relation message was emitted. // Example DDL: // ALTER TABLE changepk.test_table DROP COLUMN pk2; -- <- relation message // ALTER TABLE changepk.test_table ADD COLUMN pk3 SERIAL; -- <- relation message // ALTER TABLE changepk.test_table ADD PRIMARY KEY(newpk,pk3); -- <- relation message // Consider the above schema changes. There's a possible temporal ordering where the messages arrive // in the replication slot data stream at time `t0`, `t1`, and `t2`. It then takes until `t10` for _this_ method // to start processing message #1. At `t10` invoking `connection.readPrimaryKeyNames()` returns the new // primary key column, 'pk3', defined by message #3. We must remove this primary key column that came // "from the future" (with temporal respect to the current relate message #1) as a best effort attempt // to reflect the actual primary key state at time `t0`. primaryKeyColumns.retainAll(columnNames); Table table = resolveRelationFromMetadata(new PgOutputRelationMetaData(relationId, schemaName, tableName, columns, primaryKeyColumns)); decoderContext.getSchema().applySchemaChangesForTable(relationId, table); } private List<io.debezium.relational.Column> getTableColumnsFromDatabase(PostgresConnection connection, DatabaseMetaData databaseMetadata, TableId tableId) throws SQLException { List<io.debezium.relational.Column> readColumns = new ArrayList<>(); try { try (ResultSet columnMetadata = databaseMetadata.getColumns(null, tableId.schema(), tableId.table(), null)) { while (columnMetadata.next()) { connection.readColumnForDecoder(columnMetadata, tableId, decoderContext.getConfig().getColumnFilter()) .ifPresent(readColumns::add); } } } catch (SQLException e) { LOGGER.error("Failed to read column metadata for '{}.{}'", tableId.schema(), tableId.table()); throw e; } return readColumns; } private boolean isColumnInPrimaryKey(String schemaName, String tableName, String columnName, List<String> primaryKeyColumns) { // todo (DBZ-766) - Discuss this logic with team as there may be a better way to handle this // Personally I think its sufficient enough to resolve the PK based on the out-of-bands call // and should any test fail due to this it should be rewritten or excluded from the pgoutput // scope. // In RecordsStreamProducerIT#shouldReceiveChangesForInsertsIndependentOfReplicaIdentity, we have // a situation where the table is replica identity full, the primary key is dropped but the replica // identity is kept and later the replica identity is changed to default. In order to support this // use case, the following abides by these rules: if (!primaryKeyColumns.isEmpty() && primaryKeyColumns.contains(columnName)) { return true; } else if (primaryKeyColumns.isEmpty()) { // The table's metadata was either not fetched or table no longer has a primary key // Lets attempt to use the known schema primary key configuration as a fallback Table existingTable = decoderContext.getSchema().tableFor(new TableId(null, schemaName, tableName)); if (existingTable != null && existingTable.primaryKeyColumnNames().contains(columnName)) { return true; } } return false; } /** * Callback handler for the 'I' insert replication stream message. * * @param buffer The replication stream buffer * @param typeRegistry The postgres type registry * @param processor The replication message processor */ private void decodeInsert(ByteBuffer buffer, TypeRegistry typeRegistry, ReplicationMessageProcessor processor) throws SQLException, InterruptedException { int relationId = buffer.getInt(); char tupleType = (char) buffer.get(); // Always 'N" for inserts LOGGER.trace("Event: {}, Relation Id: {}, Tuple Type: {}", MessageType.INSERT, relationId, tupleType); Optional<Table> resolvedTable = resolveRelation(relationId); // non-captured table if (!resolvedTable.isPresent()) { processor.process(new NoopMessage(transactionId, commitTimestamp)); } else { Table table = resolvedTable.get(); List<Column> columns = resolveColumnsFromStreamTupleData(buffer, typeRegistry, table); processor.process(new PgOutputReplicationMessage( Operation.INSERT, table.id().toDoubleQuotedString(), commitTimestamp, transactionId, null, columns)); } } /** * Callback handler for the 'U' update replication stream message. * * @param buffer The replication stream buffer * @param typeRegistry The postgres type registry * @param processor The replication message processor */ private void decodeUpdate(ByteBuffer buffer, TypeRegistry typeRegistry, ReplicationMessageProcessor processor) throws SQLException, InterruptedException { int relationId = buffer.getInt(); LOGGER.trace("Event: {}, RelationId: {}", MessageType.UPDATE, relationId); Optional<Table> resolvedTable = resolveRelation(relationId); // non-captured table if (!resolvedTable.isPresent()) { processor.process(new NoopMessage(transactionId, commitTimestamp)); } else { Table table = resolvedTable.get(); // When reading the tuple-type, we could get 3 different values, 'O', 'K', or 'N'. // 'O' (Optional) - States the following tuple-data is the key, only for replica identity index configs. // 'K' (Optional) - States the following tuple-data is the old tuple, only for replica identity full configs. // 'N' (Not-Optional) - States the following tuple-data is the new tuple. // This is always present. List<Column> oldColumns = null; char tupleType = (char) buffer.get(); if ('O' == tupleType || 'K' == tupleType) { oldColumns = resolveColumnsFromStreamTupleData(buffer, typeRegistry, table); // Read the 'N' tuple type // This is necessary so the stream position is accurate for resolving the column tuple data tupleType = (char) buffer.get(); } List<Column> columns = resolveColumnsFromStreamTupleData(buffer, typeRegistry, table); processor.process(new PgOutputReplicationMessage( Operation.UPDATE, table.id().toDoubleQuotedString(), commitTimestamp, transactionId, oldColumns, columns)); } } /** * Callback handler for the 'D' delete replication stream message. * * @param buffer The replication stream buffer * @param typeRegistry The postgres type registry * @param processor The replication message processor */ private void decodeDelete(ByteBuffer buffer, TypeRegistry typeRegistry, ReplicationMessageProcessor processor) throws SQLException, InterruptedException { int relationId = buffer.getInt(); char tupleType = (char) buffer.get(); LOGGER.trace("Event: {}, RelationId: {}, Tuple Type: {}", MessageType.DELETE, relationId, tupleType); Optional<Table> resolvedTable = resolveRelation(relationId); // non-captured table if (!resolvedTable.isPresent()) { processor.process(new NoopMessage(transactionId, commitTimestamp)); } else { Table table = resolvedTable.get(); List<Column> columns = resolveColumnsFromStreamTupleData(buffer, typeRegistry, table); processor.process(new PgOutputReplicationMessage( Operation.DELETE, table.id().toDoubleQuotedString(), commitTimestamp, transactionId, columns, null)); } } /** * Callback handler for the 'T' truncate replication stream message. * * @param buffer The replication stream buffer * @param typeRegistry The postgres type registry * @param processor The replication message processor */ private void decodeTruncate(ByteBuffer buffer, TypeRegistry typeRegistry, ReplicationMessageProcessor processor) throws SQLException, InterruptedException { // As of PG11, the Truncate message format is as described: // Byte Message Type (Always 'T') // Int32 number of relations described by the truncate message // Int8 flags for truncate; 1=CASCADE, 2=RESTART IDENTITY // Int32[] Array of number of relation ids // In short this message tells us how many relations are impacted by the truncate // call, whether its cascaded or not and then all table relation ids involved. // It seems the protocol guarantees to send the most up-to-date `R` relation // messages for the tables prior to the `T` truncation message, even if in the // same session a `R` message was followed by an insert/update/delete message. int numberOfRelations = buffer.getInt(); int optionBits = buffer.get(); // ignored / unused List<String> truncateOptions = getTruncateOptions(optionBits); int[] relationIds = new int[numberOfRelations]; for (int i = 0; i < numberOfRelations; i++) { relationIds[i] = buffer.getInt(); } List<Table> tables = new ArrayList<>(); for (int relationId : relationIds) { Optional<Table> resolvedTable = resolveRelation(relationId); resolvedTable.ifPresent(tables::add); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Event: {}, RelationIds: {}, OptionBits: {}", MessageType.TRUNCATE, Arrays.toString(relationIds), optionBits); } int noOfResolvedTables = tables.size(); for (int i = 0; i < noOfResolvedTables; i++) { Table table = tables.get(i); boolean lastTableInTruncate = (i + 1) == noOfResolvedTables; processor.process(new PgOutputTruncateReplicationMessage( Operation.TRUNCATE, table.id().toDoubleQuotedString(), commitTimestamp, transactionId, lastTableInTruncate)); } } /** * Convert truncate option bits to postgres syntax truncate options * * @param flag truncate option bits * @return truncate flags */ private List<String> getTruncateOptions(int flag) { switch (flag) { case 1: return Collections.singletonList("CASCADE"); case 2: return Collections.singletonList("RESTART IDENTITY"); case 3: return Arrays.asList("RESTART IDENTITY", "CASCADE"); default: return null; } } /** * Resolves a given replication message relation identifier to a {@link Table}. * * @param relationId The replication message stream's relation identifier * @return table resolved from a prior relation message or direct lookup from the schema * or empty when the table is filtered */ private Optional<Table> resolveRelation(int relationId) { return Optional.ofNullable(decoderContext.getSchema().tableFor(relationId)); } /** * Constructs a {@link Table} based on the supplied {@link PgOutputRelationMetaData}. * * @param metadata The relation metadata collected from previous 'R' replication stream messages * @return table based on a prior replication relation message */ private Table resolveRelationFromMetadata(PgOutputRelationMetaData metadata) { List<io.debezium.relational.Column> columns = new ArrayList<>(); for (ColumnMetaData columnMetadata : metadata.getColumns()) { ColumnEditor editor = io.debezium.relational.Column.editor() .name(columnMetadata.getColumnName()) .jdbcType(columnMetadata.getPostgresType().getRootType().getJdbcId()) .nativeType(columnMetadata.getPostgresType().getRootType().getOid()) .optional(columnMetadata.isOptional()) .type(columnMetadata.getPostgresType().getName(), columnMetadata.getTypeName()) .length(columnMetadata.getLength()) .scale(columnMetadata.getScale()); if (columnMetadata.hasDefaultValue()) { editor.defaultValue(columnMetadata.getDefaultValue()); } columns.add(editor.create()); } Table table = Table.editor() .addColumns(columns) .setPrimaryKeyNames(metadata.getPrimaryKeyNames()) .tableId(metadata.getTableId()) .create(); LOGGER.trace("Resolved '{}' as '{}'", table.id(), table); return table; } /** * Reads the replication stream up to the next null-terminator byte and returns the contents as a string. * * @param buffer The replication stream buffer * @return string read from the replication stream */ private static String readString(ByteBuffer buffer) { StringBuilder sb = new StringBuilder(); byte b = 0; while ((b = buffer.get()) != 0) { sb.append((char) b); } return sb.toString(); } /** * Reads the replication stream where the column stream specifies a length followed by the value. * * @param buffer The replication stream buffer * @return the column value as a string read from the replication stream */ private static String readColumnValueAsString(ByteBuffer buffer) { int length = buffer.getInt(); byte[] value = new byte[length]; buffer.get(value, 0, length); return new String(value, Charset.forName("UTF-8")); } /** * Resolve the replication stream's tuple data to a list of replication message columns. * * @param buffer The replication stream buffer * @param typeRegistry The database type registry * @param table The database table * @return list of replication message columns */ private static List<Column> resolveColumnsFromStreamTupleData(ByteBuffer buffer, TypeRegistry typeRegistry, Table table) { // Read number of the columns short numberOfColumns = buffer.getShort(); List<Column> columns = new ArrayList<>(numberOfColumns); for (short i = 0; i < numberOfColumns; ++i) { final io.debezium.relational.Column column = table.columns().get(i); final String columnName = column.name(); final String typeName = column.typeName(); final PostgresType columnType = typeRegistry.get(typeName); final String typeExpression = column.typeExpression(); final boolean optional = column.isOptional(); // Read the sub-message type // 't' : Value is represented as text // 'u' : An unchanged TOAST-ed value, actual value is not sent. // 'n' : Value is null. char type = (char) buffer.get(); if (type == 't') { final String valueStr = readColumnValueAsString(buffer); columns.add( new AbstractReplicationMessageColumn(columnName, columnType, typeExpression, optional, true) { @Override public Object getValue(PgConnectionSupplier connection, boolean includeUnknownDatatypes) { return PgOutputReplicationMessage.getValue(columnName, columnType, typeExpression, valueStr, connection, includeUnknownDatatypes, typeRegistry); } @Override public String toString() { return columnName + "(" + typeExpression + ")=" + valueStr; } }); } else if (type == 'u') { columns.add( new UnchangedToastedReplicationMessageColumn(columnName, columnType, typeExpression, optional, true) { @Override public String toString() { return columnName + "(" + typeExpression + ") - Unchanged toasted column"; } }); } else if (type == 'n') { columns.add( new AbstractReplicationMessageColumn(columnName, columnType, typeExpression, true, true) { @Override public Object getValue(PgConnectionSupplier connection, boolean includeUnknownDatatypes) { return null; } }); } } columns.forEach(c -> LOGGER.trace("Column: {}", c)); return columns; } @Override public void close() { connection.close(); } }
package imagej.module; import imagej.AbstractUIDetails; import imagej.ValidityProblem; import imagej.event.EventService; import imagej.module.event.ModulesUpdatedEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Default {@link ModuleInfo} implementation. * <p> * By default, {@link ModuleItem}s are stored in {@link HashMap}s and * {@link ArrayList}s, internally. The {@link Module} {@link Class} given in the * {@link #setModuleClass(Class)} method is given as the delegate class name for * {@link #getDelegateClassName()}, and instantiated using a constructor that * takes a single {@link ModuleInfo} parameter. * </p> * By default, {@link ModuleItem}s are stored in {@link HashMap}s and * {@link ArrayList}s, internally. </p> * <p> * It is important for downstream code to call the * {@link #setModuleClass(Class)} method to associate the module info with its * module class prior to using the module info for anything; the * {@link #getDelegateClassName()} and {@link #createModule()} methods will fail * if the module class has not been set. * </p> * * @author Curtis Rueden */ public class DefaultModuleInfo extends AbstractUIDetails implements ModuleInfo { /** Table of inputs, keyed on name. */ private final Map<String, ModuleItem<?>> inputMap = new HashMap<String, ModuleItem<?>>(); /** Table of outputs, keyed on name. */ private final Map<String, ModuleItem<?>> outputMap = new HashMap<String, ModuleItem<?>>(); /** Ordered list of input items. */ private final List<ModuleItem<?>> inputList = new ArrayList<ModuleItem<?>>(); /** Ordered list of output items. */ private final List<ModuleItem<?>> outputList = new ArrayList<ModuleItem<?>>(); private Class<? extends Module> moduleClass; // -- DefaultModuleInfo methods -- /** Sets the module class described by this {@link ModuleInfo}. */ public void setModuleClass(final Class<? extends Module> moduleClass) { this.moduleClass = moduleClass; } /** Gets the module class described by this {@link ModuleInfo}. */ public Class<? extends Module> getModuleClass() { return moduleClass; } /** Adds an input to the list. */ public void addInput(final ModuleItem<?> input) { inputMap.put(input.getName(), input); inputList.add(input); } /** Adds an output to the list. */ public void addOutput(final ModuleItem<?> output) { outputMap.put(output.getName(), output); outputList.add(output); } /** Removes an input from the list. */ public void removeInput(final ModuleItem<?> input) { inputMap.remove(input.getName()); inputList.remove(input); } /** Removes an output from the list. */ public void removeOutput(final ModuleItem<?> output) { outputMap.remove(output.getName()); outputList.remove(output); } // -- ModuleInfo methods -- @Override public ModuleItem<?> getInput(final String name) { return inputMap.get(name); } @Override public ModuleItem<?> getOutput(final String name) { return outputMap.get(name); } @Override public Iterable<ModuleItem<?>> inputs() { return Collections.unmodifiableList(inputList); } @Override public Iterable<ModuleItem<?>> outputs() { return Collections.unmodifiableList(outputList); } @Override public String getDelegateClassName() { return getModuleClass().getName(); } @Override public Module createModule() throws ModuleException { try { return getModuleClass().newInstance(); } catch (final Exception e) { // NB: Several types of exceptions; simpler to handle them all the same. throw new ModuleException(e); } } @Override public boolean canPreview() { return false; } @Override public boolean canCancel() { return true; } @Override public boolean canRunHeadless() { return false; } @Override public String getInitializer() { return null; } @Override public void update(final EventService eventService) { eventService.publish(new ModulesUpdatedEvent(this)); } // -- UIDetails methods -- @Override public String getTitle() { final String title = super.getTitle(); if (!title.equals(getClass().getSimpleName())) return title; // use delegate class name rather than actual class name final String className = getDelegateClassName(); final int dot = className.lastIndexOf("."); return dot < 0 ? className : className.substring(dot + 1); } // -- Validated methods -- @Override public boolean isValid() { return true; } @Override public List<ValidityProblem> getProblems() { return null; } }
package com.spaceproject.systems; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.utils.ImmutableArray; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.controllers.Controller; import com.badlogic.gdx.controllers.ControllerListener; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.math.MathUtils; import com.spaceproject.SpaceProject; import com.spaceproject.components.CameraFocusComponent; import com.spaceproject.components.ControlFocusComponent; import com.spaceproject.components.ControllableComponent; import com.spaceproject.components.DashComponent; import com.spaceproject.components.HyperDriveComponent; import com.spaceproject.components.ShieldComponent; import com.spaceproject.components.VehicleComponent; import com.spaceproject.config.EngineConfig; import com.spaceproject.math.MyMath; import com.spaceproject.screens.GameScreen; import com.spaceproject.screens.MyScreenAdapter; import com.spaceproject.ui.menu.GameMenu; import com.spaceproject.utility.Mappers; public class ControllerInputSystem extends EntitySystem implements ControllerListener { private float leftStickHorAxis; private float leftStickVertAxis; private float rightStickHorAxis; private float rightStickVertAxis; private final float deadZone = 0.25f; private final float camFocusMultiplier = 0.05f; //4 & 5 don't seem to be in controller.getMapping() private final int xboxControllerLeftTrigger = 4; private final int xboxControllerRightTrigger = 5; //private SimpleTimer doubleTap = new SimpleTimer(1000); private ImmutableArray<Entity> players; public ControllerInputSystem() { Controllers.addListener(this); for (Controller controller : Controllers.getControllers()) { Gdx.app.log(this.getClass().getSimpleName(), controller.getName()); } } private boolean playerControls(Controller controller, int buttonCode, boolean buttonDown) { //Gdx.app.log(this.getClass().getSimpleName(), "button: " + buttonCode + ": " + buttonDown); if (players.size() == 0) return false; boolean handled = false; ControllableComponent control = Mappers.controllable.get(players.first()); if (buttonCode == controller.getMapping().buttonA) { DashComponent dash = Mappers.dash.get(players.first()); if (dash != null) { dash.activate = buttonDown; handled = true; } } if (buttonCode == controller.getMapping().buttonB) { ShieldComponent shield = Mappers.shield.get(players.first()); if (shield != null) { shield.defend = buttonDown; handled = true; } } if (buttonCode == controller.getMapping().buttonY) { control.changeVehicle = buttonDown; handled = true; } if (buttonCode == controller.getMapping().buttonX) { control.alter = buttonDown; handled = true; } if (buttonCode == controller.getMapping().buttonDpadUp) { HyperDriveComponent hyperDrive = Mappers.hyper.get(players.first()); if (hyperDrive != null) { hyperDrive.activate = buttonDown; handled = true; } } if (buttonCode == controller.getMapping().buttonDpadDown) { control.transition = buttonDown; handled = true; } if (buttonCode == controller.getMapping().buttonR1) { control.movementMultiplier = 1; control.moveRight = buttonDown; /* //todo: double tap for dodge if (buttonDown) { if (doubleTap.getLastEvent() != 0 && doubleTap.canDoEvent()) { Gdx.app.log("", "double tap unlatch"); doubleTap.setLastEvent(0); } if (doubleTap.getLastEvent() == 0) { Gdx.app.log("", "double tap begin latch"); doubleTap.reset(); } else if (!doubleTap.canDoEvent()) { Gdx.app.log("", "double tap activate"); control.alter = true; } } else { control.alter = false; }*/ handled = true; } if (buttonCode == controller.getMapping().buttonL1) { control.movementMultiplier = 1; control.moveLeft = buttonDown; //control.alter = buttonDown; handled = true; } if (buttonCode == controller.getMapping().buttonStart) { if (buttonDown) { GameMenu menu = getEngine().getSystem(HUDSystem.class).getGameMenu(); if (!menu.isVisible()) { menu.show(); } else { menu.close(); } } handled = true; } if ((buttonCode == controller.getMapping().buttonRightStick) && buttonDown) { //reset cam Entity player = players.first(); CameraFocusComponent cameraFocus = player.getComponent(CameraFocusComponent.class); if (cameraFocus != null) { GameScreen.resetCamera(); EngineConfig engineConfig = SpaceProject.configManager.getConfig(EngineConfig.class); if (player.getComponent(VehicleComponent.class) != null) { cameraFocus.zoomTarget = engineConfig.defaultZoomVehicle; } else { cameraFocus.zoomTarget = engineConfig.defaultZoomCharacter; } return true; } } return handled; } @Override public void update(float deltaTime) { super.update(deltaTime); if (Math.abs(rightStickVertAxis) >= deadZone) { //Gdx.app.log(this.getClass().getSimpleName(), rightStickVertAxis + " - right vert"); if (players.size() != 0) { Entity player = players.first(); CameraFocusComponent cameraFocus = player.getComponent(CameraFocusComponent.class); if (cameraFocus != null) { float scrollAmount = rightStickVertAxis * camFocusMultiplier * MyScreenAdapter.cam.zoom; cameraFocus.zoomTarget = MyScreenAdapter.cam.zoom += scrollAmount; } } } } @Override public void addedToEngine(Engine engine) { players = engine.getEntitiesFor(Family.all(ControlFocusComponent.class, ControllableComponent.class).get()); } @Override public void connected(Controller controller) { Gdx.app.log(this.getClass().getSimpleName(), "Connected: " + controller.getName()); } @Override public void disconnected(Controller controller) { Gdx.app.log(this.getClass().getSimpleName(), "Disconnected: " + controller.getName()); } @Override public boolean buttonDown(Controller controller, int buttonCode) { return playerControls(controller, buttonCode, true); } @Override public boolean buttonUp(Controller controller, int buttonCode) { return playerControls(controller, buttonCode, false); } @Override public boolean axisMoved(Controller controller, int axisCode, float value) { //Gdx.app.log(this.getClass().getSimpleName(), controller.getName() + ": " + axisCode + ": " + value); if (axisCode == controller.getMapping().axisLeftX) { leftStickHorAxis = value; //Gdx.app.log(this.getClass().getSimpleName(), "left horizontal " + value); } if (axisCode == controller.getMapping().axisLeftY) { leftStickVertAxis = value; //Gdx.app.log(this.getClass().getSimpleName(), "left vertical " + value); } ControllableComponent control = Mappers.controllable.get(players.first()); if (axisCode == xboxControllerRightTrigger) { control.attack = (value > 0); } float dist = Math.abs(MyMath.distance(0, 0, leftStickHorAxis, leftStickVertAxis)); if (dist >= deadZone) { control.angleTargetFace = MyMath.angle2(0, 0, -leftStickVertAxis, leftStickHorAxis); control.movementMultiplier = MathUtils.clamp(dist, 0, 1); control.moveForward = true; } else { control.moveForward = false; } if (axisCode == controller.getMapping().axisRightX) { rightStickHorAxis = value; } if (axisCode == controller.getMapping().axisRightY) { rightStickVertAxis = value; } return false; } }
package org.jetel.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import org.jetel.data.Defaults; public class ByteBufferUtils { /** * This method flushes the buffer to the Channel and prepares it for next * reading * * @param buffer * @param writer * @return The number of bytes written, possibly zero * @throws IOException */ public static int flush(ByteBuffer buffer, WritableByteChannel writer) throws IOException { int write; if (buffer.position() != 0) { buffer.flip(); } write = writer.write(buffer); buffer.clear(); return write; } /** * This method reads new data to the buffer * * @param buffer * @param reader * @return The number of bytes read, possibly zero * @throws IOException */ public static int reload(ByteBuffer buffer, ReadableByteChannel reader) throws IOException{ int read; if (buffer.position() != 0) { buffer.compact(); } read = reader.read(buffer); buffer.flip(); return read; } /** * This method rewrites bytes from input stream to output stream * * @param in * @param out * @throws IOException */ public static void rewrite(InputStream in, OutputStream out)throws IOException{ ByteBuffer buffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); ReadableByteChannel reader = Channels.newChannel(in); WritableByteChannel writer = Channels.newChannel(out); while (reload(buffer,reader) > 0){ flush(buffer, writer); } } /** * This method rewrites maximum "bytes" bytes from input stream to output stream * * @param in * @param out * @param bytes number of bytes to rewrite * @throws IOException */ public static void rewrite(InputStream in, OutputStream out, long bytes)throws IOException{ if (Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE == 0){ Defaults.init(); } ByteBuffer buffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); ReadableByteChannel reader = Channels.newChannel(in); WritableByteChannel writer = Channels.newChannel(out); long b = 0; int r; while ( (r = reload(buffer,reader)) > 0 && b < bytes){ b += r; if (r == buffer.capacity()) { flush(buffer, writer); }else{ buffer.limit((int) (bytes % buffer.capacity())); flush(buffer, writer); } } } }
package org.usergrid.utils; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.codehaus.jackson.node.JsonNodeFactory; import org.codehaus.jackson.node.ObjectNode; import org.junit.Test; public class JsonUtilsTest { private static final Logger logger = Logger.getLogger(JsonUtilsTest.class); @SuppressWarnings("unchecked") @Test public void testUnroll() { Map<String, Object> json = new LinkedHashMap<String, Object>(); json.put("name", "edanuff"); json.put("cat", "fishbone"); json.put("city", "San Francisco"); json.put("car", "bmw"); json.put("stuff", Arrays.asList(1, 2, 3, 4, 5)); json.put("phones", Arrays.asList(MapUtils.map("a", "b"), MapUtils.map("a", "c"), MapUtils.map("b", MapUtils.map("d", "e", "d", "f")))); dumpJson("obj", json); dumpJson("propname", Arrays.asList(1, 2, 3, 4, 5)); dumpJson("propname", 125); System.out.println(JsonUtils.mapToJsonString(json)); Object result = JsonUtils.select(json, "phones"); System.out.println(JsonUtils.mapToJsonString(result)); result = JsonUtils.select(json, "phones.a"); System.out.println(JsonUtils.mapToJsonString(result)); } public void dumpJson(String path, Object json) { List<Map.Entry<String, Object>> list = IndexUtils.getKeyValueList(path, json, true); for (Map.Entry<String, Object> e : list) { logger.info(e.getKey() + " = " + e.getValue()); } } @Test public void testNormalize() { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("foo", "bar"); Object o = JsonUtils.normalizeJsonTree(node); assertEquals(java.util.LinkedHashMap.class, o.getClass()); } }
package org.jetel.test; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.GraphConfigurationException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.TransformationGraphXMLReaderWriter; import org.jetel.graph.runtime.EngineInitializer; import org.jetel.graph.runtime.GraphRuntimeContext; import org.jetel.graph.runtime.SimpleThreadManager; import org.jetel.graph.runtime.WatchDog; public abstract class CloverTestCase extends TestCase { public CloverTestCase() { super(); } public CloverTestCase(String name) { super(name); } private static final String PLUGINS_KEY = "cloveretl.plugins"; private static final String PLUGINS_DEFAULT_DIR = ".."; protected void initEngine() { initEngine(null); } protected void initEngine(String defaultPropertiesFile) { final String pluginsDir; final String pluginsProperty = System.getenv(PLUGINS_KEY); if (pluginsProperty != null) { pluginsDir = pluginsProperty; } else { pluginsDir = PLUGINS_DEFAULT_DIR; } System.out.println("Cloveretl plugins: " + pluginsDir); EngineInitializer.initEngine(pluginsDir, defaultPropertiesFile, null); EngineInitializer.forceActivateAllPlugins(); } @Override protected void setUp() throws Exception { if (!EngineInitializer.isInitialized()) { initEngine(getCloverPropertiesFile()); } } protected String getCloverPropertiesFile() { return null; } protected TransformationGraph createTransformationGraph(String path, GraphRuntimeContext context) throws FileNotFoundException, GraphConfigurationException, XMLConfigurationException, ComponentNotReadyException { InputStream in = new BufferedInputStream(new FileInputStream(path)); try { context.setUseJMX(false); TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(in, context); EngineInitializer.initGraph(graph, context); return graph; } finally { IOUtils.closeQuietly(in); } } protected Result runGraph(TransformationGraph graph) throws ExecutionException, InterruptedException { WatchDog watchDog = new WatchDog(graph, graph.getRuntimeContext()); watchDog.init(); SimpleThreadManager manager = new SimpleThreadManager(); Future<Result> result = manager.executeWatchDog(watchDog); Result value = result.get(); if (value == Result.ERROR) { if (watchDog.getCauseException() != null) { rethrowRuntime(watchDog.getCauseException()); } } return value; } protected static void rethrowRuntime(Throwable throwable) { if (throwable instanceof RuntimeException) { throw (RuntimeException)throwable; } else if (throwable instanceof Error) { throw (Error)throwable; } else { throw new RuntimeException(throwable.getMessage(), throwable); } } }
package filodb.standalone; import java.io.File; import java.io.FileOutputStream; import java.io.InterruptedIOException; import java.io.IOException; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Method; import java.time.Instant; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; /** * Simple profiler which samples threads and periodically logs a report to a file. When the * process is cleanly shutdown, the profiler stops and reports what it has immediately. This * makes it possible to use a very long report interval without data loss. */ public class SimpleProfiler { /** * Launches a global profiler, based on config. Typically, these are nested under the * "filodb.profiler" path: * * sample-rate = 10ms * report-interval = 60s * top-count = 50 * out-file = "filodb.prof" * * In order for profiling to be enabled, all of the above properies must be set except for * the file. If no file is provided, then a temporary file is created, whose name is logged. * * @return false if not configured * @throws IOException if file cannot be opened */ public static boolean launch(Config config) throws IOException { try { long sampleRateMillis = config.getDuration("sample-rate", TimeUnit.MILLISECONDS); long reportIntervalSeconds = config.getDuration("report-interval", TimeUnit.SECONDS); int topCount = config.getInt("top-count"); File outFile = selectProfilerFile(config.getString("out-file")); FileOutputStream out = new FileOutputStream(outFile); new SimpleProfiler(sampleRateMillis, reportIntervalSeconds, topCount, out).start(); return true; } catch (ConfigException e) { LoggerFactory.getLogger(SimpleProfiler.class).debug("Not profiling: " + e); return false; } } /** * @param fileName candidate file name; if null, a temp file is created */ private static File selectProfilerFile(String fileName) throws IOException { if (fileName != null) { return new File(fileName); } File file = File.createTempFile("filodb.SimpleProfiler", ".txt"); LoggerFactory.getLogger(SimpleProfiler.class).info ("Created temp file for profile reporting: " + file); return file; } private final long mSampleRateMillis; private final long mReportIntervalMillis; private final int mTopCount; private final OutputStream mOut; private Sampler mSampler; private Thread mShutdownHook; private long mNextReportAtMillis; /** * Reports to System.out. */ public SimpleProfiler(long sampleRateMillis, long reportIntervalSeconds, int topCount) { this(sampleRateMillis, reportIntervalSeconds, topCount, System.out); } /** * @param sampleRateMillis how often to perform a thread dump (10 millis is good) * @param reportIntervalSeconds how often to write a report to the output stream * @param topCount number of methods to report * @param out where to write the report */ public SimpleProfiler(long sampleRateMillis, long reportIntervalSeconds, int topCount, OutputStream out) { mSampleRateMillis = sampleRateMillis; mReportIntervalMillis = reportIntervalSeconds * 1000; mTopCount = topCount; mOut = out; } /** * Start the profiler. Calling a second time does nothing unless stopped. */ public synchronized void start() { if (mSampler == null) { Sampler s = new Sampler(); s.start(); mSampler = s; mNextReportAtMillis = System.currentTimeMillis() + mReportIntervalMillis; try { mShutdownHook = new Thread(this::shutdown); Runtime.getRuntime().addShutdownHook(mShutdownHook); } catch (Throwable e) { // Ignore. mShutdownHook = null; } } } /** * Stop the profiler. Calling a second time does nothing unless started again. */ public void stop() { Sampler s; synchronized (this) { s = mSampler; if (s != null) { s.mShouldStop = true; s.interrupt(); if (mShutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(mShutdownHook); } catch (Throwable e) { // Ignore. } finally { mShutdownHook = null; } } } } if (s != null) { while (true) { try { s.join(); break; } catch (InterruptedException e) { // Ignore. } } synchronized (this) { if (mSampler == s) { mSampler = null; } } } } private void analyze(Map<StackTraceElement, Counter> samples, ThreadInfo[] infos) throws IOException { for (ThreadInfo info : infos) { StackTraceElement[] trace = examine(info); if (trace != null) { StackTraceElement elem = trace[0]; Counter c = samples.get(elem); if (c == null) { c = new Counter(elem); samples.put(elem, c); } c.mValue++; } } synchronized (this) { long now = System.currentTimeMillis(); if (now >= mNextReportAtMillis && mSampler == Thread.currentThread()) { mNextReportAtMillis = Math.max(now, mNextReportAtMillis + mReportIntervalMillis); report(samples); } } } private void report(Map<StackTraceElement, Counter> samples) throws IOException { int size = samples.size(); if (size == 0) { return; } Counter[] top = new Counter[size]; samples.values().toArray(top); Arrays.sort(top); double sum = 0; for (Counter c : top) { sum += c.mValue; } int limit = Math.min(mTopCount, size); StringBuilder b = new StringBuilder(limit * 80); b.append(Instant.now()).append(' ').append(getClass().getName()).append('\n'); for (int i=0; i<limit; i++) { Counter c = top[i]; if (c.mValue == 0) { // No more to report. break; } String percentStr = String.format("%1$7.3f%%", 100.0 * (c.mValue / sum)); b.append(percentStr); StackTraceElement elem = c.mElem; b.append(' ').append(elem.getClassName()).append('.').append(elem.getMethodName()); String fileName = elem.getFileName(); int lineNumber = elem.getLineNumber(); if (fileName == null) { if (lineNumber >= 0) { b.append("(:").append(lineNumber).append(')'); } } else { b.append('(').append(fileName); if (lineNumber >= 0) { b.append(':').append(lineNumber); } b.append(')'); } b.append('\n'); // Reset for next report. c.mValue = 0; } report(b.toString()); } /** * Override this method to report somewhere else. */ protected void report(String s) throws IOException { mOut.write(s.getBytes(StandardCharsets.UTF_8)); mOut.flush(); } /** * @return null if rejected */ private StackTraceElement[] examine(ThreadInfo info) { // Reject the sampler thread itself. if (info.getThreadId() == Thread.currentThread().getId()) { return null; } // Reject threads which aren't doing any real work. if (!info.getThreadState().equals(Thread.State.RUNNABLE)) { return null; } StackTraceElement[] trace = info.getStackTrace(); // Reject internal threads which have no trace at all. if (trace == null || trace.length == 0) { return null; } // Reject some special internal native methods which aren't actually running. StackTraceElement elem = trace[0]; if (elem.isNativeMethod()) { String className = elem.getClassName(); // Reject threads which appeared as doing work only because they unparked another // thread, effectively yielding due to priority boosting. if (className.endsWith("misc.Unsafe")) { if (elem.getMethodName().equals("unpark")) { return null; } // Sometimes the thread state is runnable for this method. Filter it out. if (elem.getMethodName().equals("park")) { return null; } } switch (className) { case "java.lang.Object": // Reject threads which appeared as doing work only because they notified // another thread, effectively yielding due to priority boosting. if (elem.getMethodName().startsWith("notify")) { return null; } break; case "java.lang.ref.Reference": // Reject threads waiting for GC'd objects to clean up. return null; case "java.lang.Thread": /* Track yield, since it's used by the ChunkMap lock. // Reject threads which appeared as doing work only because they yielded. if (elem.getMethodName().equals("yield")) { return null; } */ // Sometimes the thread state is runnable for this method. Filter it out. if (elem.getMethodName().equals("sleep")) { return null; } break; case "java.net.PlainSocketImpl": // Reject threads blocked while accepting sockets. if (elem.getMethodName().startsWith("accept") || elem.getMethodName().startsWith("socketAccept")) { return null; } break; case "sun.nio.ch.ServerSocketChannelImpl": // Reject threads blocked while accepting sockets. if (elem.getMethodName().startsWith("accept")) { return null; } break; case "java.net.SocketInputStream": // Reject threads blocked while reading sockets. This also rejects threads // which are actually reading, but it's more common for threads to block. if (elem.getMethodName().startsWith("socketRead")) { return null; } break; case "sun.nio.ch.SocketDispatcher": // Reject threads blocked while reading sockets. This also rejects threads // which are actually reading, but it's more common for threads to block. if (elem.getMethodName().startsWith("read")) { return null; } break; case "sun.nio.ch.EPoll": // Reject threads blocked while selecting sockets. if (elem.getMethodName().startsWith("wait")) { return null; } break; case "sun.nio.ch.KQueue": // Reject threads blocked while selecting sockets. if (elem.getMethodName().startsWith("poll")) { return null; } break; case "sun.nio.ch.KQueueArrayWrapper": // Reject threads blocked while selecting sockets. if (elem.getMethodName().startsWith("kevent")) { return null; } break; case "sun.nio.ch.WindowsSelectorImpl$SubSelector": // Reject threads blocked while selecting sockets. if (elem.getMethodName().startsWith("poll")) { return null; } break; } // Reject threads blocked while selecting sockets. Match just on method name here, // to capture multiple epoll library implementations. if (elem.getMethodName().startsWith("epollWait")) { return null; } } return trace; } private void shutdown() { synchronized (this) { mShutdownHook = null; mNextReportAtMillis = Long.MIN_VALUE; } stop(); } private static class Counter implements Comparable<Counter> { final StackTraceElement mElem; long mValue; Counter(StackTraceElement elem) { mElem = elem; } @Override public int compareTo(Counter other) { // Descending order. return Long.compare(other.mValue, mValue); } } private class Sampler extends Thread { private final Map<StackTraceElement, Counter> mSamples; volatile boolean mShouldStop; Sampler() { super(SimpleProfiler.class.getName()); try { setDaemon(true); setPriority(Thread.MAX_PRIORITY); } catch (SecurityException e) { // Ignore. } mSamples = new HashMap<>(); } @Override public void run() { ThreadMXBean tb = ManagementFactory.getThreadMXBean(); Method dumpMethod = null; try { dumpMethod = ThreadMXBean.class.getMethod ("dumpAllThreads", boolean.class, boolean.class, int.class); } catch (NoSuchMethodException e) { // Oh well, we tried. } while (!mShouldStop) { try { try { Thread.sleep(mSampleRateMillis); } catch (InterruptedException e) { // Probably should report upon JVM shutdown and then stop. } ThreadInfo[] infos; if (dumpMethod == null) { // Use the slow version. // lockMonitors=false, lockedSynchronizers=false infos = tb.dumpAllThreads(false, false); } else { // Use the fast version. // lockMonitors=false, lockedSynchronizers=false, maxDepth=1 infos = (ThreadInfo[]) dumpMethod.invoke(tb, false, false, 1); } analyze(mSamples, infos); } catch (InterruptedIOException e) { // Probably should stop. } catch (Throwable e) { Thread t = Thread.currentThread(); t.getThreadGroup().uncaughtException(t, e); } } } } }
package VASSAL.launch; import VASSAL.configure.StringConfigurer; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Stream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.text.html.HTMLEditorKit; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import net.miginfocom.swing.MigLayout; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import VASSAL.Info; import VASSAL.build.module.Documentation; import VASSAL.build.module.ExtensionsManager; import VASSAL.build.module.metadata.AbstractMetaData; import VASSAL.build.module.metadata.ExtensionMetaData; import VASSAL.build.module.metadata.MetaDataFactory; import VASSAL.build.module.metadata.ModuleMetaData; import VASSAL.build.module.metadata.SaveMetaData; import VASSAL.chat.CgiServerStatus; import VASSAL.chat.ui.ServerStatusView; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.DirectoryConfigurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.ShowHelpAction; import VASSAL.configure.StringArrayConfigurer; import VASSAL.i18n.Resources; import VASSAL.preferences.PositionOption; import VASSAL.preferences.Prefs; import VASSAL.tools.ApplicationIcons; import VASSAL.tools.BrowserSupport; import VASSAL.tools.ErrorDialog; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.WriteErrorDialog; import VASSAL.tools.filechooser.FileChooser; import VASSAL.tools.filechooser.ModuleExtensionFileFilter; import VASSAL.tools.logging.LogPane; import VASSAL.tools.menu.CheckBoxMenuItemProxy; import VASSAL.tools.menu.MenuBarProxy; import VASSAL.tools.menu.MenuItemProxy; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.menu.MenuProxy; import VASSAL.tools.swing.Dialogs; import VASSAL.tools.swing.SplitPane; import VASSAL.tools.swing.SwingUtils; import VASSAL.tools.version.UpdateCheckAction; public class ModuleManagerWindow extends JFrame { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(ModuleManagerWindow.class); private static final String SHOW_STATUS_KEY = "showServerStatus"; //NON-NLS private static final String DIVIDER_LOCATION_KEY = "moduleManagerDividerLocation"; //NON-NLS private static final String DEVELOPER_INFO_KEY = "moduleManagerDeveloperInfo"; //NON-NLS private static final String COLUMN_WIDTHS_KEY = "moduleManagerColumnWidths"; //NON-NLS private static final int COLUMNS = 5; private static final int KEY_COLUMN = 0; private static final int VERSION_COLUMN = 1; private static final int SPARE_COLUMN = 2; private static final int VASSAL_COLUMN = 3; private static final int SAVED_COLUMN = 4; private static final String[] columnHeadings = new String[COLUMNS]; private static final TableColumn[] columns = new TableColumn[COLUMNS]; private final ImageIcon moduleIcon; private final ImageIcon activeExtensionIcon; private final ImageIcon inactiveExtensionIcon; private final ImageIcon openGameFolderIcon; private final ImageIcon closedGameFolderIcon; private final ImageIcon fileIcon; private StringArrayConfigurer recentModuleConfig; private StringArrayConfigurer moduleConfig; private File selectedModule; private final CardLayout modulePanelLayout; private final JPanel moduleView; private final SplitPane splitPane; private MyTreeNode rootNode; private MyTree tree; private MyTreeTableModel treeModel; protected MyTreeNode selectedNode; private long lastExpansionTime; private TreePath lastExpansionPath; private final IntConfigurer dividerLocationConfig; private static final long doubleClickInterval; static { final Object dci = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); doubleClickInterval = dci instanceof Integer ? (Integer) dci : 200L; } public static ModuleManagerWindow getInstance() { return instance; } private static final ModuleManagerWindow instance = new ModuleManagerWindow(); public ModuleManagerWindow() { setTitle("VASSAL " + Info.getVersion()); //NON-NLS setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); ApplicationIcons.setFor(this); final AbstractAction shutDownAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { saveColumnWidths(); final Prefs gp = Prefs.getGlobalPrefs(); try { gp.close(); } catch (IOException ex) { WriteErrorDialog.error(ex, gp.getFile()); } try { ModuleManager.getInstance().shutDown(); } catch (IOException ex) { ErrorDialog.bug(ex); } logger.info("Exiting"); //NON-NLS System.exit(0); } }; shutDownAction.putValue(Action.NAME, Resources.getString(Resources.QUIT)); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { shutDownAction.actionPerformed(null); } }); // setup menubar and actions final MenuManager mm = MenuManager.getInstance(); final MenuBarProxy mb = mm.getMenuBarProxyFor(this); // file menu final MenuProxy fileMenu = new MenuProxy(Resources.getString("General.file")); fileMenu.setMnemonic(Resources.getString("General.file.shortcut").charAt(0)); fileMenu.add(mm.addKey("Main.play_module")); fileMenu.add(mm.addKey("Main.edit_module")); fileMenu.add(mm.addKey("Main.new_module")); fileMenu.addSeparator(); if (!SystemUtils.IS_OS_MAC) { fileMenu.add(mm.addKey("Prefs.edit_preferences")); fileMenu.addSeparator(); fileMenu.add(mm.addKey("General.quit")); } // tools menu final MenuProxy toolsMenu = new MenuProxy(Resources.getString("General.tools")); // Initialize Global Preferences Prefs.getGlobalPrefs().getEditor().initDialog(this); Prefs.initSharedGlobalPrefs(); final BooleanConfigurer serverStatusConfig = new BooleanConfigurer(SHOW_STATUS_KEY, null, Boolean.FALSE); Prefs.getGlobalPrefs().addOption(null, serverStatusConfig); dividerLocationConfig = new IntConfigurer(DIVIDER_LOCATION_KEY, null, -10); Prefs.getGlobalPrefs().addOption(null, dividerLocationConfig); final BooleanConfigurer developerInfoConfig = new BooleanConfigurer(DEVELOPER_INFO_KEY, Resources.getString("Prefs.developer_info"), false); Prefs.getGlobalPrefs().addOption(Resources.getString("Prefs.general_tab"), developerInfoConfig); developerInfoConfig.addPropertyChangeListener(e1 -> updateColumnDisplay()); toolsMenu.add(new CheckBoxMenuItemProxy(new AbstractAction( Resources.getString("Chat.server_status")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { splitPane.toggleRight(); serverStatusConfig.setValue( serverStatusConfig.booleanValue() ? Boolean.FALSE : Boolean.TRUE); if (splitPane.isRightVisible()) { splitPane.setDividerLocation(getPreferredDividerLocation()); } } }, serverStatusConfig.booleanValue())); toolsMenu.add(mm.addKey("Main.import_module")); toolsMenu.add(new MenuItemProxy(new AbstractAction( Resources.getString("ModuleManager.clear_tilecache")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { final int dialogResult = Dialogs.showConfirmDialog( ModuleManagerWindow.this, Resources.getString("ModuleManager.clear_tilecache_title"), Resources.getString("ModuleManager.clear_tilecache_heading"), Resources.getString("ModuleManager.clear_tilecache_message"), JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION); if (dialogResult == JOptionPane.OK_OPTION) { final File tdir = new File(Info.getConfDir(), "tiles"); if (tdir.exists()) { try { FileUtils.forceDelete(tdir); FileUtils.forceMkdir(tdir); } catch (IOException e) { WriteErrorDialog.error(e, tdir); } } } } })); // help menu final MenuProxy helpMenu = new MenuProxy(Resources.getString("General.help")); helpMenu.setMnemonic(Resources.getString("General.help.shortcut").charAt(0)); helpMenu.add(mm.addKey("General.help")); helpMenu.add(mm.addKey("Main.tour")); helpMenu.add(mm.addKey("Help.user_guide")); helpMenu.addSeparator(); helpMenu.add(mm.addKey("UpdateCheckAction.update_check")); helpMenu.add(mm.addKey("Help.error_log")); if (!SystemUtils.IS_OS_MAC) { helpMenu.addSeparator(); helpMenu.add(mm.addKey("AboutScreen.about_vassal")); } mb.add(fileMenu); mb.add(toolsMenu); mb.add(helpMenu); // add actions mm.addAction("Main.play_module", new Player.PromptLaunchAction(this)); mm.addAction("Main.edit_module", new Editor.PromptLaunchAction(this)); mm.addAction("Main.new_module", new Editor.NewModuleLaunchAction(this)); mm.addAction("Main.import_module", new Editor.PromptImportLaunchAction(this)); mm.addAction("Prefs.edit_preferences", Prefs.getGlobalPrefs().getEditor().getEditAction()); mm.addAction("General.quit", shutDownAction); try { final URL url = new File(Documentation.getDocumentationBaseDir(), "README.html").toURI().toURL(); mm.addAction("General.help", new ShowHelpAction(url, null)); } catch (MalformedURLException e) { ErrorDialog.bug(e); } try { final URL url = new File(Documentation.getDocumentationBaseDir(), "userguide/userguide.pdf").toURI().toURL(); mm.addAction("Help.user_guide", new ShowHelpAction("Help.user_guide", url, null)); } catch (MalformedURLException e) { ErrorDialog.bug(e); } mm.addAction("Main.tour", new LaunchTourAction(this)); mm.addAction("AboutScreen.about_vassal", new AboutVASSALAction(this)); mm.addAction("UpdateCheckAction.update_check", new UpdateCheckAction(this)); mm.addAction("Help.error_log", new ShowErrorLogAction(this)); setJMenuBar(mm.getMenuBarFor(this)); // Load Icons moduleIcon = new ImageIcon( getClass().getResource("/images/mm-module.png")); //NON-NLS activeExtensionIcon = new ImageIcon( getClass().getResource("/images/mm-extension-active.png")); //NON-NLS inactiveExtensionIcon = new ImageIcon( getClass().getResource("/images/mm-extension-inactive.png")); //NON-NLS openGameFolderIcon = new ImageIcon( getClass().getResource("/images/mm-gamefolder-open.png")); //NON-NLS closedGameFolderIcon = new ImageIcon( getClass().getResource("/images/mm-gamefolder-closed.png")); //NON-NLS fileIcon = new ImageIcon(getClass().getResource("/images/mm-file.png")); //NON-NLS // build module controls final JPanel moduleControls = new JPanel(new BorderLayout()); modulePanelLayout = new CardLayout(); moduleView = new JPanel(modulePanelLayout); buildTree(); final JScrollPane scroll = new JScrollPane(tree); moduleView.add(scroll, "modules"); //NON-NLS final JEditorPane l = new JEditorPane("text/html", Resources.getString("ModuleManager.quickstart")); l.setEditable(false); // Try to get background color and font from LookAndFeel; // otherwise, use dummy JLabel to get color and font. Color bg = UIManager.getColor("control"); Font font = UIManager.getFont("Label.font"); if (bg == null || font == null) { final JLabel dummy = new JLabel(); if (bg == null) bg = dummy.getBackground(); if (font == null) font = dummy.getFont(); } l.setBackground(bg); ((HTMLEditorKit) l.getEditorKit()).getStyleSheet().addRule( "body { font: " + font.getFamily() + " " + font.getSize() + "pt }"); l.addHyperlinkListener(BrowserSupport.getListener()); // FIXME: use MigLayout for this! // this is necessary to get proper vertical alignment final JPanel p = new JPanel(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; p.add(l, c); moduleView.add(p, "quickStart"); //NON-NLS modulePanelLayout.show( moduleView, getModuleCount() == 0 ? "quickStart" : "modules"); moduleControls.add(moduleView, BorderLayout.CENTER); moduleControls.setBorder(new TitledBorder( Resources.getString("ModuleManager.recent_modules"))); add(moduleControls); // build server status controls final ServerStatusView serverStatusControls = new ServerStatusView(new CgiServerStatus()); serverStatusControls.setBorder( new TitledBorder(Resources.getString("Chat.server_status"))); splitPane = new SplitPane( SplitPane.HORIZONTAL_SPLIT, moduleControls, serverStatusControls ); // show the server status controls according to the prefs splitPane.setRightVisible(serverStatusConfig.booleanValue()); splitPane.setResizeWeight(1.0); splitPane.setDividerLocation(getPreferredDividerLocation()); splitPane.addPropertyChangeListener( "dividerLocation", e -> setPreferredDividerLocation((Integer) e.getNewValue()) ); add(splitPane); final Rectangle r = SwingUtils.getScreenBounds(this); serverStatusControls.setPreferredSize( new Dimension((int) (r.width / 3.5), 0)); setSize(3 * r.width / 4, 3 * r.height / 4); // Save/load the window position and size in prefs final PositionOption option = new PositionOption(PositionOption.key + "ModuleManager", this); //NON-NLS Prefs.getGlobalPrefs().addOption(option); } public void setWaitCursor(boolean wait) { setCursor(Cursor.getPredefinedCursor( wait ? Cursor.WAIT_CURSOR : Cursor.DEFAULT_CURSOR )); } protected void setPreferredDividerLocation(int i) { dividerLocationConfig.setValue(i); } protected int getPreferredDividerLocation() { return dividerLocationConfig.getIntValue(500); } // Show/Hide the two 'developer' columns depending on the pref value private void updateColumnDisplay() { final boolean showDeveloperInfo = (Boolean) Prefs.getGlobalPrefs().getValue(DEVELOPER_INFO_KEY); final TableColumnModel model = tree.getColumnModel(); if (showDeveloperInfo) { if (model.getColumnCount() < COLUMNS) { model.addColumn(columns[VASSAL_COLUMN]); model.addColumn(columns[SAVED_COLUMN]); } } else { model.removeColumn(columns[VASSAL_COLUMN]); model.removeColumn(columns[SAVED_COLUMN]); } } protected void buildTree() { final List<ModuleInfo> moduleList = new ArrayList<>(); final List<String> missingModules = new ArrayList<>(); // RecentModules key was used through 3.5.1, but 3.2 can't read the // buildFile.xml for 3.5+ modules. Hence we've switched to the Modules // key, but still collect whatever is in RecentModules for compatibility. recentModuleConfig = new StringArrayConfigurer("RecentModules", null); //NON-NLS Prefs.getGlobalPrefs().addOption(null, recentModuleConfig); moduleConfig = new StringArrayConfigurer("Modules", null); //NON-NLS Prefs.getGlobalPrefs().addOption(null, moduleConfig); Stream.concat( Arrays.stream(recentModuleConfig.getStringArray()), Arrays.stream(moduleConfig.getStringArray()) ).sorted().distinct().forEach(s -> { final ModuleInfo module = new ModuleInfo(s); if (module.getFile().exists() && module.isValid()) { moduleList.add(module); } else { missingModules.add(s); } }); for (final String s : missingModules) { logger.info(Resources.getString("ModuleManager.removing_module", s)); final ModuleInfo toRemove = moduleList .stream() .filter(moduleInfo -> moduleInfo.getModuleName().equals(s)) .findFirst() .orElse(null); moduleList.remove(toRemove); recentModuleConfig.removeValue(s); moduleConfig.removeValue(s); } moduleList.sort(AbstractInfo::compareTo); rootNode = new MyTreeNode(new RootInfo()); for (final ModuleInfo moduleInfo : moduleList) { final MyTreeNode moduleNode = new MyTreeNode(moduleInfo); for (final ExtensionInfo ext : moduleInfo.getExtensions()) { final MyTreeNode extensionNode = new MyTreeNode(ext); moduleNode.add(extensionNode); } final ArrayList<File> missingFolders = new ArrayList<>(); for (final File f : moduleInfo.getFolders()) { if (f.exists() && f.isDirectory()) { final GameFolderInfo folderInfo = new GameFolderInfo(f, moduleInfo); final MyTreeNode folderNode = new MyTreeNode(folderInfo); moduleNode.add(folderNode); final ArrayList<File> l = new ArrayList<>(); final File[] files = f.listFiles(); if (files == null) continue; for (final File f1 : files) { if (f1.isFile()) { l.add(f1); } } Collections.sort(l); for (final File f2 : l) { final SaveFileInfo fileInfo = new SaveFileInfo(f2, folderInfo); if (fileInfo.isValid() && fileInfo.belongsToModule()) { final MyTreeNode fileNode = new MyTreeNode(fileInfo); folderNode.add(fileNode); } } } else { missingFolders.add(f); } } for (final File mf : missingFolders) { logger.info( Resources.getString("ModuleManager.removing_folder", mf.getPath())); moduleInfo.removeFolder(mf); } rootNode.add(moduleNode); } updateModuleList(); treeModel = new MyTreeTableModel(rootNode); tree = new MyTree(treeModel); tree.setRootVisible(false); tree.setEditable(false); tree.setTreeCellRenderer(new MyTreeCellRenderer()); tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && SwingUtils.isMainMouseButtonDown(e)) { final TreePath path = tree.getPathForLocation(e.getPoint().x, e.getPoint().y); // do nothing if not on a node, or if this node was expanded // or collapsed during the past doubleClickInterval milliseconds if (path == null || (lastExpansionPath == path && e.getWhen() - lastExpansionTime <= doubleClickInterval)) return; tree.activateOrExpandNode(path); } } @Override public void mousePressed(MouseEvent e) { maybePopup(e); } @Override public void mouseReleased(MouseEvent e) { maybePopup(e); } private void maybePopup(MouseEvent e) { if (e.isPopupTrigger()) { final TreePath path = tree.getPathForLocation(e.getPoint().x, e.getPoint().y); if (path == null) return; final int row = tree.getRowForPath(path); if (row >= 0) { selectedNode = (MyTreeNode) path.getLastPathComponent(); tree.clearSelection(); tree.addRowSelectionInterval(row, row); final AbstractInfo target = (AbstractInfo) selectedNode.getUserObject(); target.buildPopup(row).show(tree, e.getX(), e.getY()); } } } }); // We capture the time and location of clicks which would cause // expansion in order to distinguish these from clicks which // might launch a module or game. tree.addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillCollapse(TreeExpansionEvent e) { lastExpansionTime = System.currentTimeMillis(); lastExpansionPath = e.getPath(); } @Override public void treeWillExpand(TreeExpansionEvent e) { lastExpansionTime = System.currentTimeMillis(); lastExpansionPath = e.getPath(); } }); // This ensures that double-clicks always start the module but // doesn't prevent single-clicks on the handles from working. tree.setToggleClickCount(3); tree.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tree.addTreeSelectionListener(e -> { final MyTreeNode node = (MyTreeNode) e.getPath().getLastPathComponent(); final AbstractInfo target = node.getNodeInfo(); if (target instanceof ModuleInfo) { setSelectedModule(target.getFile()); } else { if (node.getParent() != null) { setSelectedModule(node.getParentModuleFile()); } } }); // Pref to hold the column widths. final StringConfigurer widthsConfig = new StringConfigurer(COLUMN_WIDTHS_KEY, null, ""); Prefs.getGlobalPrefs().addOption(null, widthsConfig); setColumnWidths(); // Set cell renderers for centered fields final TableColumnModel model = tree.getColumnModel(); final DefaultTableCellRenderer centerRenderer = new CenteringCellRenderer(); model.getColumn(VERSION_COLUMN).setCellRenderer(centerRenderer); model.getColumn(SAVED_COLUMN).setCellRenderer(centerRenderer); model.getColumn(VASSAL_COLUMN).setCellRenderer(centerRenderer); tree.getTableHeader().setAlignmentX(JComponent.CENTER_ALIGNMENT); // Save the columns so they can be removed/restored as needed for (int i = 0; i < COLUMNS; i++) { columns[i] = tree.getColumnModel().getColumn(i); } // Show/hide the developer columns updateColumnDisplay(); } // Set the preferred widths of the columns based on the recorded preference // All 5 columns are guaranteed to exist at this point. private void setColumnWidths() { final String widths = Prefs.getGlobalPrefs().getValue(COLUMN_WIDTHS_KEY).toString(); final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(widths, ','); final TableColumnModel model = tree.getColumnModel(); model.getColumn(0).setPreferredWidth(sd.nextInt(250)); model.getColumn(0).setMinWidth(200); model.getColumn(1).setPreferredWidth(sd.nextInt(100)); model.getColumn(1).setMinWidth(100); model.getColumn(2).setPreferredWidth(sd.nextInt(500)); model.getColumn(2).setMinWidth(200); model.getColumn(3).setPreferredWidth(sd.nextInt(100)); model.getColumn(3).setMinWidth(100); model.getColumn(4).setPreferredWidth(sd.nextInt(100)); model.getColumn(4).setMinWidth(100); } // Save the current column widths in the preference // The Developer columns may not exist at this point. private void saveColumnWidths() { final SequenceEncoder se = new SequenceEncoder(','); final TableColumnModel model = tree.getColumnModel(); for (int i = 0; i < model.getColumnCount(); i++) { se.append(model.getColumn(i).getWidth()); } Prefs.getGlobalPrefs().setValue(COLUMN_WIDTHS_KEY, se.toString()); } public void updateRequest(File f) { SwingUtilities.invokeLater(() -> update(f)); } public void update(File f) { final AbstractMetaData data = MetaDataFactory.buildMetaData(f); if (data instanceof ModuleMetaData) { // Module. // If we already have this module, refresh it, otherwise add it. final MyTreeNode moduleNode = rootNode.findNode(f); if (moduleNode == null) { addModule(f); } else { moduleNode.refresh(); } } else if (data instanceof ExtensionMetaData) { // Extension. // Check if it has been saved into one of the extension directories // for any module we already know of. Refresh the module for (int i = 0; i < rootNode.getChildCount(); i++) { final MyTreeNode moduleNode = rootNode.getChild(i); final ModuleInfo moduleInfo = (ModuleInfo) moduleNode.getNodeInfo(); for (final ExtensionInfo ext : moduleInfo.getExtensions()) { if (ext.getFile().equals(f)) { moduleNode.refresh(); return; } } } } else if (data instanceof SaveMetaData) { // Save Game or Log file. // If the parent of the save file is already recorded as a Game Folder, // pass the file off to the Game Folder to handle. Otherwise, ignore it. for (int i = 0; i < rootNode.getChildCount(); i++) { final MyTreeNode moduleNode = rootNode.getChild(i); final MyTreeNode folderNode = moduleNode.findNode(f.getParentFile()); if (folderNode != null && folderNode.getNodeInfo() instanceof GameFolderInfo) { ((GameFolderInfo) folderNode.getNodeInfo()).update(f); return; } } } tree.repaint(); } /** * Return the number of Modules added to the Module Manager * * @return Number of modules */ private int getModuleCount() { return rootNode.getChildCount(); } public File getSelectedModule() { return selectedModule; } private void setSelectedModule(File selectedModule) { this.selectedModule = selectedModule; } public void addModule(File f) { if (!rootNode.contains(f)) { final ModuleInfo moduleInfo = new ModuleInfo(f); if (moduleInfo.isValid()) { final MyTreeNode moduleNode = new MyTreeNode(moduleInfo); treeModel.insertNodeInto(moduleNode, rootNode, rootNode.findInsertIndex(moduleInfo)); for (final ExtensionInfo ext : moduleInfo.getExtensions()) { final MyTreeNode extensionNode = new MyTreeNode(ext); treeModel.insertNodeInto(extensionNode, moduleNode, moduleNode.findInsertIndex(ext)); } updateModuleList(); } } } public void removeModule(File f) { final MyTreeNode moduleNode = rootNode.findNode(f); treeModel.removeNodeFromParent(moduleNode); updateModuleList(); } public File getModuleByName(String name) { if (name == null) return null; for (int i = 0; i < rootNode.getChildCount(); i++) { final ModuleInfo module = (ModuleInfo) rootNode.getChild(i).getNodeInfo(); if (name.equals(module.getModuleName())) return module.getFile(); } return null; } private void updateModuleList() { final List<String> l = new ArrayList<>(); for (int i = 0; i < rootNode.getChildCount(); i++) { final ModuleInfo module = (ModuleInfo) (rootNode.getChild(i)).getNodeInfo(); l.add(module.encode()); } recentModuleConfig.setValue(l.toArray(new String[0])); moduleConfig.setValue(l.toArray(new String[0])); modulePanelLayout.show( moduleView, getModuleCount() == 0 ? "quickStart" : "modules"); } private static class MyTreeTableModel extends DefaultTreeTableModel { public MyTreeTableModel(MyTreeNode rootNode) { super(rootNode); columnHeadings[KEY_COLUMN] = Resources.getString("ModuleManager.module"); columnHeadings[VERSION_COLUMN] = Resources.getString("ModuleManager.version"); columnHeadings[VASSAL_COLUMN] = Resources.getString("ModuleManager.created_by"); columnHeadings[SPARE_COLUMN] = Resources.getString("ModuleManager.description"); columnHeadings[SAVED_COLUMN] = Resources.getString("ModuleManager.last_saved"); } @Override public int getColumnCount() { return COLUMNS; } @Override public String getColumnName(int col) { return columnHeadings[col]; } @Override public Object getValueAt(Object node, int column) { return ((MyTreeNode) node).getValueAt(column); } } private static class MyTree extends JXTreeTable { private static final long serialVersionUID = 1L; public MyTree(MyTreeTableModel treeModel) { super(treeModel); createKeyBindings(this); } public void activateOrExpandNode(TreePath path) { final ModuleManagerWindow mmw = ModuleManagerWindow.getInstance(); mmw.selectedNode = (MyTreeNode) path.getLastPathComponent(); final AbstractInfo target = (AbstractInfo) mmw.selectedNode.getUserObject(); final int row = mmw.tree.getRowForPath(path); if (row < 0) return; // launch module or load save, otherwise expand or collapse node if (target instanceof ModuleInfo) { final ModuleInfo modInfo = (ModuleInfo) target; if (modInfo.isModuleTooNew()) { ErrorDialog.show( "Error.module_too_new", modInfo.getFile().getPath(), modInfo.getVassalVersion(), Info.getVersion() ); return; } else { ((ModuleInfo) target).play(); } } else if (target instanceof SaveFileInfo) { ((SaveFileInfo) target).play(); } else if (isExpanded(row)) { collapseRow(row); } else { expandRow(row); } } private void createKeyBindings(JTable table) { table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { //do something meaningful on JTable enter pressed final MyTree tree = ModuleManagerWindow.getInstance().tree; final int row = tree.getSelectedRow(); final TreePath path = tree.getPathForRow(row); if (path != null) { tree.activateOrExpandNode(path); } } }); } // FIXME: Where's the rest of the comment??? /** * There appears to be a bug/strange interaction between JXTreetable and the ComponentSplitter * when the Component */ @Override public String getToolTipText(MouseEvent event) { if (getComponentAt(event.getPoint().x, event.getPoint().y) == null) return null; return super.getToolTipText(event); } } /** * Custom Tree cell renderer:- * - Add file name as tooltip * - Handle expanded display (some nodes use the same icon for expanded/unexpanded) * - Gray out inactive extensions * - Gray out Save Games that belong to other modules */ private static class MyTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); final AbstractInfo info = ((MyTreeNode) value).getNodeInfo(); setText(info.toString()); setToolTipText(info.getToolTipText()); setIcon(info.getIcon(expanded)); setForeground(info.getTreeCellFgColor()); return this; } } private static class CenteringCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; public CenteringCellRenderer() { super(); this.setHorizontalAlignment(CENTER); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); return this; } } private static class MyTreeNode extends DefaultMutableTreeTableNode { public MyTreeNode(AbstractInfo nodeInfo) { super(nodeInfo); nodeInfo.setTreeNode(this); } public AbstractInfo getNodeInfo() { return (AbstractInfo) getUserObject(); } public File getFile() { return getNodeInfo().getFile(); } public void refresh() { getNodeInfo().refresh(); } @Override public void setValueAt(Object aValue, int column) { } @Override public Object getValueAt(int column) { return getNodeInfo().getValueAt(column); } public MyTreeNode getChild(int index) { return (MyTreeNode) super.getChildAt(index); } public MyTreeNode findNode(File f) { for (int i = 0; i < getChildCount(); i++) { final MyTreeNode moduleNode = getChild(i); // NB: we canonicalize because File.equals() does not // always return true when one File is a relative path. try { f = f.getCanonicalFile(); } catch (IOException e) { f = f.getAbsoluteFile(); } if (f.equals(moduleNode.getNodeInfo().getFile())) { return moduleNode; } } return null; } public boolean contains(File f) { return findNode(f) != null; } public int findInsertIndex(AbstractInfo info) { for (int i = 0; i < getChildCount(); i++) { final MyTreeNode childNode = getChild(i); if (childNode.getNodeInfo().compareTo(info) >= 0) { return i; } } return getChildCount(); } /** * Return the Module node enclosing this node * * @return Parent Tree Node */ public MyTreeNode getParentModuleNode() { final AbstractInfo info = getNodeInfo(); if (info instanceof RootInfo) { return null; } else if (info instanceof ModuleInfo) { return this; } else if (getParent() == null) { return null; } else { return ((MyTreeNode) getParent()).getParentModuleNode(); } } /** * Return the Module file of the Module node enclosing this node * * @return Module File */ public File getParentModuleFile() { final MyTreeNode parentNode = getParentModuleNode(); return parentNode == null ? null : parentNode.getFile(); } } private abstract class AbstractInfo implements Comparable<AbstractInfo> { protected File file; protected Icon openIcon; protected Icon closedIcon; protected boolean valid = true; protected String error = ""; protected MyTreeNode node; public AbstractInfo(File f, Icon open, Icon closed) { setFile(f); setIcon(open, closed); } public AbstractInfo(File f, Icon i) { this (f, i, i); } public AbstractInfo(File f) { this(f, null); } public AbstractInfo() { } @Override public String toString() { return file == null ? "" : file.getName(); } public File getFile() { return file; } public void setFile(File f) { if (f == null) return; try { file = f.getCanonicalFile(); } catch (IOException e) { file = f.getAbsoluteFile(); } } public String getToolTipText() { if (file == null) { return ""; } else { return file.getPath(); } } @Override public int compareTo(AbstractInfo info) { return getSortKey().compareTo(info.getSortKey()); } public JPopupMenu buildPopup(int row) { return null; } public Icon getIcon(boolean expanded) { return expanded ? openIcon : closedIcon; } public void setIcon(Icon i) { setIcon(i, i); } public void setIcon(Icon open, Icon closed) { openIcon = open; closedIcon = closed; } public String getValueAt(int column) { switch (column) { case KEY_COLUMN: return toString(); case VERSION_COLUMN: return getVersion(); case VASSAL_COLUMN: return getVassalVersion(); case SAVED_COLUMN: return getLastSaved(); default: return null; } } public void setValid(boolean b) { valid = b; } public boolean isValid() { return valid; } public void setError(String s) { error = s; } public String getError() { return error; } public String getVersion() { return ""; } public String getVassalVersion() { return ""; } public String getComments() { return ""; } public String getLastSaved() { return ""; } public MyTreeNode getTreeNode() { return node; } public void setTreeNode(MyTreeNode n) { node = n; } /** * Return a String used to sort different types of AbstractInfo's that are * children of the same parent. * * @return sort key */ public abstract String getSortKey(); /** * Return the color of the text used to display the name in column 1. * Over-ride this to change color depending on item state. * * @return cell text color */ public Color getTreeCellFgColor() { return Color.black; } /** * Refresh yourself and any children */ public void refresh() { refreshChildren(); } public void refreshChildren() { for (int i = 0; i < node.getChildCount(); i++) { (node.getChild(i)).refresh(); } } } private class RootInfo extends AbstractInfo { public RootInfo() { super(null); } @Override public String getSortKey() { return ""; } } public class ModuleInfo extends AbstractInfo { private final ExtensionsManager extMgr; private final SortedSet<File> gameFolders = new TreeSet<>(); private ModuleMetaData metadata; private final Action newExtensionAction = new NewExtensionLaunchAction(ModuleManagerWindow.this); private final AbstractAction addExtensionAction = new AbstractAction( Resources.getString("ModuleManager.add_extension")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final FileChooser fc = FileChooser.createFileChooser( ModuleManagerWindow.this, (DirectoryConfigurer) Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY)); if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) { final File selectedFile = fc.getSelectedFile(); final ExtensionInfo testExtInfo = new ExtensionInfo(selectedFile, true, null); if (testExtInfo.isValid()) { final File f = getExtensionsManager().setActive(fc.getSelectedFile(), true); final MyTreeNode moduleNode = rootNode.findNode(selectedModule); final ExtensionInfo extInfo = new ExtensionInfo(f, true, (ModuleInfo) moduleNode.getNodeInfo()); if (extInfo.isValid()) { final MyTreeNode extNode = new MyTreeNode(extInfo); treeModel.insertNodeInto(extNode, moduleNode, moduleNode.findInsertIndex(extInfo)); } } else { JOptionPane.showMessageDialog(ModuleManagerWindow.this, testExtInfo.getError(), null, JOptionPane.ERROR_MESSAGE); } } } }; private final AbstractAction addFolderAction = new AbstractAction( Resources.getString("ModuleManager.add_save_game_folder")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final FileChooser fc = FileChooser.createFileChooser( ModuleManagerWindow.this, (DirectoryConfigurer) Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY), FileChooser.DIRECTORIES_ONLY); if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) { addFolder(fc.getSelectedFile()); } } }; public ModuleInfo(File f) { super(f, moduleIcon); extMgr = new ExtensionsManager(f); loadMetaData(); } protected void loadMetaData() { final AbstractMetaData data = MetaDataFactory.buildMetaData(file); if (data instanceof ModuleMetaData) { setValid(true); metadata = (ModuleMetaData) data; } else { setValid(false); } } protected boolean isModuleTooNew() { return metadata != null && Info.isModuleTooNew(metadata.getVassalVersion()); } @Override public String getVassalVersion() { return metadata == null ? "" : metadata.getVassalVersion(); } @Override public String getLastSaved() { return metadata == null ? "" : metadata.formatLastSaved(); } /** * Initialise ModuleInfo based on a saved preference string. * See encode(). * * @param s Preference String */ public ModuleInfo(String s) { final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ';'); setFile(new File(sd.nextToken())); setIcon(moduleIcon); loadMetaData(); extMgr = new ExtensionsManager(getFile()); while (sd.hasMoreTokens()) { gameFolders.add(new File(sd.nextToken())); } } /** * Refresh this module and all children */ @Override public void refresh() { loadMetaData(); // Remove any missing children final MyTreeNode[] nodes = new MyTreeNode[getTreeNode().getChildCount()]; for (int i = 0; i < getTreeNode().getChildCount(); i++) { nodes[i] = getTreeNode().getChild(i); } for (final MyTreeNode myTreeNode : nodes) { if (!myTreeNode.getFile().exists()) { treeModel.removeNodeFromParent(myTreeNode); } } // Refresh or add any existing children for (final ExtensionInfo ext : getExtensions()) { MyTreeNode extNode = getTreeNode().findNode(ext.getFile()); if (extNode == null) { if (ext.isValid()) { extNode = new MyTreeNode(ext); treeModel.insertNodeInto(extNode, getTreeNode(), getTreeNode().findInsertIndex(ext)); } } else { extNode.refresh(); } } } /** * Encode any information which needs to be recorded in the Preference entry for this module:- * - Path to Module File * - Paths to any child Save Game Folders * * @return encoded data */ public String encode() { final SequenceEncoder se = new SequenceEncoder(file.getPath(), ';'); for (final File f : gameFolders) { se.append(f.getPath()); } return se.getValue(); } public ExtensionsManager getExtensionsManager() { return extMgr; } public void addFolder(File f) { // try to create the directory if it doesn't exist if (!f.exists() && !f.mkdirs()) { JOptionPane.showMessageDialog( ModuleManagerWindow.this, Resources.getString("Install.error_unable_to_create", f.getPath()), "Error", //NON-NLS JOptionPane.ERROR_MESSAGE ); return; } gameFolders.add(f); final MyTreeNode moduleNode = rootNode.findNode(selectedModule); final GameFolderInfo folderInfo = new GameFolderInfo(f, (ModuleInfo) moduleNode.getNodeInfo()); final MyTreeNode folderNode = new MyTreeNode(folderInfo); final int idx = moduleNode.findInsertIndex(folderInfo); treeModel.insertNodeInto(folderNode, moduleNode, idx); for (final File file : f.listFiles()) { if (file.isFile()) { final SaveFileInfo fileInfo = new SaveFileInfo(file, folderInfo); if (fileInfo.isValid() && fileInfo.belongsToModule()) { final MyTreeNode fileNode = new MyTreeNode(fileInfo); treeModel.insertNodeInto(fileNode, folderNode, folderNode.findInsertIndex(fileInfo)); } } } updateModuleList(); } public void removeFolder(File f) { gameFolders.remove(f); } public SortedSet<File> getFolders() { return gameFolders; } public List<ExtensionInfo> getExtensions() { final List<ExtensionInfo> l = new ArrayList<>(); for (final File f : extMgr.getActiveExtensions()) { l.add(new ExtensionInfo(f, true, this)); } for (final File f : extMgr.getInactiveExtensions()) { l.add(new ExtensionInfo(f, false, this)); } Collections.sort(l); return l; } public void play() { new Player.LaunchAction( ModuleManagerWindow.this, file).actionPerformed(null); } @Override public JPopupMenu buildPopup(int row) { final boolean tooNew = Info.isModuleTooNew(metadata.getVassalVersion()); final JPopupMenu m = new JPopupMenu(); final Action playAction = new Player.LaunchAction(ModuleManagerWindow.this, file); playAction.setEnabled(playAction.isEnabled() && !tooNew); m.add(playAction); final Action editAction = new Editor.ListLaunchAction(ModuleManagerWindow.this, file); editAction.setEnabled(editAction.isEnabled() && !tooNew); m.add(editAction); m.add(new AbstractAction(Resources.getString("General.remove")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { removeModule(file); cleanupTileCache(); } }); m.addSeparator(); m.add(addFolderAction); addFolderAction.setEnabled(!tooNew); m.addSeparator(); m.add(newExtensionAction); newExtensionAction.setEnabled(!tooNew); m.add(addExtensionAction); addExtensionAction.setEnabled(!tooNew); return m; } public void cleanupTileCache() { final String hstr = DigestUtils.sha1Hex( metadata.getName() + "_" + metadata.getVersion() ); final File tdir = new File(Info.getConfDir(), "tiles/" + hstr); if (tdir.exists()) { try { FileUtils.forceDelete(tdir); } catch (IOException e) { WriteErrorDialog.error(e, tdir); } } } /* * Is the module currently being Played or Edited? */ public boolean isInUse() { return AbstractLaunchAction.isInUse(file) || AbstractLaunchAction.isEditing(file); } @Override public String getVersion() { return metadata.getVersion(); } public String getLocalizedDescription() { return metadata.getLocalizedDescription(); } public String getModuleName() { return metadata.getName(); } @Override public String toString() { return metadata.getLocalizedName(); } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? getLocalizedDescription() : super.getValueAt(column); } @Override public String getSortKey() { return metadata == null ? "" : metadata.getLocalizedName(); } @Override public Color getTreeCellFgColor() { return Info.isModuleTooNew(getVassalVersion()) ? Color.GRAY : Color.BLACK; } } private class ExtensionInfo extends AbstractInfo { private boolean active; private final ModuleInfo moduleInfo; private ExtensionMetaData metadata; public ExtensionInfo(File file, boolean active, ModuleInfo module) { super(file, active ? activeExtensionIcon : inactiveExtensionIcon); this.active = active; moduleInfo = module; loadMetaData(); } protected void loadMetaData() { final AbstractMetaData data = MetaDataFactory.buildMetaData(file); if (data instanceof ExtensionMetaData) { setValid(true); metadata = (ExtensionMetaData) data; } else { setError(Resources.getString("ModuleManager.invalid_extension")); setValid(false); } } @Override public void refresh() { loadMetaData(); setActive(getExtensionsManager().isExtensionActive(getFile())); tree.repaint(); } public boolean isActive() { return active; } public void setActive(boolean b) { active = b; setIcon(active ? activeExtensionIcon : inactiveExtensionIcon); } @Override public String getVersion() { return metadata == null ? "" : metadata.getVersion(); } @Override public String getVassalVersion() { return metadata == null ? "" : metadata.getVassalVersion(); } @Override public String getLastSaved() { return metadata == null ? "" : metadata.formatLastSaved(); } public String getDescription() { return metadata == null ? "" : metadata.getDescription(); } public ExtensionsManager getExtensionsManager() { return moduleInfo == null ? null : moduleInfo.getExtensionsManager(); } @Override public String toString() { String s = getFile().getName(); String st = ""; if (metadata == null) { st = Resources.getString("ModuleManager.invalid"); } if (!active) { st += st.length() > 0 ? "," : ""; st += Resources.getString("ModuleManager.inactive"); } if (st.length() > 0) { s += " (" + st + ")"; } return s; } @Override public JPopupMenu buildPopup(int row) { final JPopupMenu m = new JPopupMenu(); final boolean tooNew = Info.isModuleTooNew(metadata.getVassalVersion()); final Action activateAction = new ActivateExtensionAction( Resources.getString(isActive() ? "ModuleManager.deactivate" : "ModuleManager.activate") ); activateAction.setEnabled(!tooNew); m.add(activateAction); final Action editAction = new EditExtensionLaunchAction( ModuleManagerWindow.this, getFile(), getSelectedModule()); editAction.setEnabled(!tooNew); m.add(editAction); return m; } @Override public Color getTreeCellFgColor() { // FIXME: should get colors from LAF if (isActive()) { return metadata == null ? Color.red : Color.black; } else { return metadata == null ? Color.pink : Color.gray; } } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? getDescription() : super.getValueAt(column); } /* * Is the extension, or its owning module currently being Played or Edited? */ public boolean isInUse() { return AbstractLaunchAction.isInUse(file) || AbstractLaunchAction.isEditing(file); } private class ActivateExtensionAction extends AbstractAction { private static final long serialVersionUID = 1L; public ActivateExtensionAction(String s) { super(s); setEnabled(!isInUse() && ! moduleInfo.isInUse()); } @Override public void actionPerformed(ActionEvent evt) { setFile(getExtensionsManager().setActive(getFile(), !isActive())); setActive(getExtensionsManager().isExtensionActive(getFile())); final TreePath path = tree.getPathForRow(tree.getSelectedRow()); final MyTreeNode extNode = (MyTreeNode) path.getLastPathComponent(); treeModel.setValueAt("", extNode, 0); } } /** * Sort Extensions by File Name */ @Override public String getSortKey() { return getFile().getName(); } } private class GameFolderInfo extends AbstractInfo { protected String comment; protected ModuleInfo moduleInfo; protected long dtm; public GameFolderInfo(File f, ModuleInfo m) { super(f, openGameFolderIcon, closedGameFolderIcon); moduleInfo = m; dtm = f.lastModified(); } @Override public JPopupMenu buildPopup(int row) { final boolean tooNew = Info.isModuleTooNew(moduleInfo.getVassalVersion()); final JPopupMenu m = new JPopupMenu(); final Action refreshAction = new AbstractAction(Resources.getString("General.refresh")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { refresh(); } }; refreshAction.setEnabled(!tooNew); m.add(refreshAction); m.addSeparator(); final Action removeAction = new AbstractAction(Resources.getString("General.remove")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final MyTreeNode moduleNode = rootNode.findNode(moduleInfo.getFile()); final MyTreeNode folderNode = moduleNode.findNode(getFile()); treeModel.removeNodeFromParent(folderNode); moduleInfo.removeFolder(getFile()); updateModuleList(); } }; removeAction.setEnabled(!tooNew); m.add(removeAction); return m; } public ModuleInfo getModuleInfo() { return moduleInfo; } @Override public void refresh() { // Remove any files that no longer exist for (int i = getTreeNode().getChildCount() - 1; i >= 0; i final MyTreeNode fileNode = getTreeNode().getChild(i); final SaveFileInfo fileInfo = (SaveFileInfo) fileNode.getNodeInfo(); if (!fileInfo.getFile().exists()) { treeModel.removeNodeFromParent(fileNode); } } // Refresh any that are. Only include Save files belonging to this // module, or that are pre vassal 3.1 final File[] files = getFile().listFiles(); if (files == null) return; for (final File f : files) { final AbstractMetaData fdata = MetaDataFactory.buildMetaData(f); if (fdata != null) { if (fdata instanceof SaveMetaData) { final String moduleName = ((SaveMetaData) fdata).getModuleName(); if (moduleName == null || moduleName.length() == 0 || moduleName.equals(getModuleInfo().getModuleName())) { update(f); } } } } } /** * Update the display for the specified save File, or add it in if * we don't already know about it. * @param f Save File */ public void update(File f) { for (int i = 0; i < getTreeNode().getChildCount(); i++) { final SaveFileInfo fileInfo = (SaveFileInfo) (getTreeNode().getChild(i)).getNodeInfo(); if (fileInfo.getFile().equals(f)) { fileInfo.refresh(); return; } } final SaveFileInfo fileInfo = new SaveFileInfo(f, this); final MyTreeNode fileNode = new MyTreeNode(fileInfo); treeModel.insertNodeInto(fileNode, getTreeNode(), getTreeNode().findInsertIndex(fileInfo)); } /** * Force Game Folders to sort after extensions */ @Override public String getSortKey() { return "~~~" + getFile().getName(); } } private class SaveFileInfo extends AbstractInfo { protected GameFolderInfo folderInfo; // Owning Folder protected SaveMetaData metadata; // Save file metadata public SaveFileInfo(File f, GameFolderInfo folder) { super(f, fileIcon); folderInfo = folder; loadMetaData(); } protected void loadMetaData() { final AbstractMetaData data = MetaDataFactory.buildMetaData(file); if (data instanceof SaveMetaData) { metadata = (SaveMetaData) data; setValid(true); } else { setValid(false); } } @Override public void refresh() { loadMetaData(); tree.repaint(); } @Override public JPopupMenu buildPopup(int row) { final boolean tooNew = Info.isModuleTooNew(metadata.getVassalVersion()); final JPopupMenu m = new JPopupMenu(); final Action launchAction = new Player.LaunchAction( ModuleManagerWindow.this, getModuleFile(), file ); launchAction.setEnabled(!tooNew); m.add(launchAction); return m; } protected File getModuleFile() { return folderInfo.getModuleInfo().getFile(); } public void play() { new Player.LaunchAction( ModuleManagerWindow.this, getModuleFile(), file).actionPerformed(null); } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? buildComments() : super.getValueAt(column); } private String buildComments() { String comments = ""; if (!belongsToModule()) { if (metadata != null && metadata.getModuleName().length() > 0) { comments = "[" + metadata.getModuleName() + "] "; } } comments += (metadata == null ? "" : metadata.getDescription()); return comments; } private boolean belongsToModule() { return metadata != null && (metadata.getModuleName().length() == 0 || folderInfo.getModuleInfo().getModuleName().equals( metadata.getModuleName())); } @Override public Color getTreeCellFgColor() { // FIXME: should get colors from LAF return belongsToModule() ? Color.black : Color.gray; } @Override public String getVersion() { return metadata == null ? "" : metadata.getModuleVersion(); } /** * Sort Save Files by file name */ @Override public String getSortKey() { return this.getFile().getName(); } } /** * Action to create a New Extension and edit it in another process. */ private class NewExtensionLaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public NewExtensionLaunchAction(Frame frame) { super(Resources.getString("ModuleManager.new_extension"), frame, Editor.class.getName(), new LaunchRequest(LaunchRequest.Mode.NEW_EXT) ); } @Override public void actionPerformed(ActionEvent e) { lr.module = getSelectedModule(); // register that this module is being used if (isEditing(lr.module)) return; incrementUsed(lr.module); super.actionPerformed(e); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count decrementUsed(lr.module); } }; } } /** * Action to Edit an Extension in another process */ private static class EditExtensionLaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public EditExtensionLaunchAction(Frame frame, File extension, File module) { super(Resources.getString("Editor.edit_extension"), frame, Editor.class.getName(), new LaunchRequest(LaunchRequest.Mode.EDIT_EXT, module, extension) ); setEnabled(!isInUse(module) && !isInUse(extension)); } @Override public void actionPerformed(ActionEvent e) { // check that neither this module nor this extension is being edited if (isInUse(lr.module) || isInUse(lr.extension)) return; // register that this module is being used incrementUsed(lr.module); // register that this extension is being edited markEditing(lr.module); super.actionPerformed(e); setEnabled(false); } @Override protected void addFileFilters(FileChooser fc) { fc.addChoosableFileFilter(new ModuleExtensionFileFilter()); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count for module decrementUsed(lr.module); // register that this extension is done being edited unmarkEditing(lr.extension); setEnabled(true); } }; } } private static class ShowErrorLogAction extends AbstractAction { private static final long serialVersionUID = 1L; private final Frame frame; public ShowErrorLogAction(Frame frame) { super(Resources.getString("Help.error_log")); this.frame = frame; } @Override public void actionPerformed(ActionEvent e) { // FIXME: don't create a new one each time! final File logfile = Info.getErrorLogPath(); final LogPane lp = new LogPane(logfile); // FIXME: this should have its own key. Probably keys should be renamed // to reflect what they are labeling, e.g., Help.show_error_log_menu_item, // Help.error_log_dialog_title. final JDialog d = new JDialog(frame, Resources.getString("Help.error_log")); d.setLayout(new MigLayout("insets 0")); //NON-NLS d.add(new JScrollPane(lp), "grow, push, w 500, h 600"); //NON-NLS d.setLocationRelativeTo(frame); d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); SwingUtils.repack(d); d.setVisible(true); } } }
package com.akjava.gwt.three.client.js.extras.animation; import com.akjava.gwt.three.client.gwt.animation.AnimationData; import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem; import com.akjava.gwt.three.client.gwt.animation.AnimationKey; import com.akjava.gwt.three.client.js.core.Object3D; import com.akjava.gwt.three.client.js.math.Vector3; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayNumber; public class Animation extends JavaScriptObject{ protected Animation(){} public final native Object3D getRoot()/*-{ return this.root; }-*/; public final native AnimationData getData()/*-{ return this.data; }-*/; public final native JsArray<AnimationHierarchyItem> getHierarchy()/*-{ return this.hierarchy; }-*/; public final native double getCurrentTime()/*-{ return this.currentTime; }-*/; public final native void setCurrentTime(double currentTime)/*-{ this.currentTime = currentTime; }-*/; public final native double getTimeScale()/*-{ return this.timeScale; }-*/; public final native void setTimeScale(double timeScale)/*-{ this.timeScale = timeScale; }-*/; public final native boolean isIsPlaying()/*-{ return this.isPlaying; }-*/; public final native void setIsPlaying(boolean isPlaying)/*-{ this.isPlaying = isPlaying; }-*/; /** * @deprecated * on r68 dropped */ public final native boolean isIsPaused()/*-{ return this.isPaused; }-*/; /** * @deprecated * on r68 dropped */ public final native void setIsPaused(boolean isPaused)/*-{ this.isPaused = isPaused; }-*/; public final native boolean isLoop()/*-{ return this.loop; }-*/; public final native void setLoop(boolean loop)/*-{ this.loop = loop; }-*/; public final native int getInterpolationType()/*-{ return this.interpolationType; }-*/; public final native void setInterpolationType(int interpolationType)/*-{ this.interpolationType = interpolationType; }-*/; public final native JsArrayNumber getPoints()/*-{ return this.points; }-*/; public final native Vector3 getTarget()/*-{ return this.target; }-*/; public final native void setTarget(Vector3 target)/*-{ this.target = target; }-*/; /** * @deprecated no more support loop * @param loop * @param startTimeMS */ public final native void play(boolean loop,double startTimeMS)/*-{ this.play(loop,startTimeMS); }-*/; /** * @deprecated * on r68 dropped */ public final native void pause()/*-{ this.pause(); }-*/; public final native void stop()/*-{ this.stop(); }-*/; public final native void update(double deltaTimeMS)/*-{ this.update(deltaTimeMS); }-*/; public final native Vector3 interpolateCatmullRom(JsArrayNumber points,double scale)/*-{ return this.interpolateCatmullRom(points,scale); }-*/; public final native double interpolate(double p0,double p1,double p2,double p3,double t,double t2,double t3)/*-{ return this.interpolate(p0,p1,p2,p3,t,t2,t3); }-*/; public final native AnimationKey getNextKeyWith(int type,int h,int key)/*-{ return this.getNextKeyWith(type,h,key); }-*/; public final native AnimationKey getPrevKeyWith(int type,int h,int key)/*-{ return this.getPrevKeyWith(type,h,key); }-*/; public native final void play()/*-{ this.play(); }-*/; public native final void play(double startTime)/*-{ this.play(startTime); }-*/; public native final void play(double startTime,double weight)/*-{ this.play(startTime,weight); }-*/; public native final void resetBlendWeights()/*-{ this.resetBlendWeights(); }-*/; }
package org.vrjuggler.tweek.gui; import java.awt.*; import java.awt.event.*; import java.util.Iterator; import java.util.List; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import org.vrjuggler.tweek.services.GlobalPreferencesService; /** * @since 1.0 */ public class PrefsDialog extends JDialog implements TableModelListener { public PrefsDialog (Frame owner, String title, GlobalPreferencesService prefs) { super(owner, title); mPrefs = prefs; userLevel = mPrefs.getUserLevel(); lookAndFeel = mPrefs.getLookAndFeel(); beanViewer = mPrefs.getBeanViewer(); windowWidth = new Integer(mPrefs.getWindowWidth()); windowHeight = new Integer(mPrefs.getWindowHeight()); chooserStartDir = mPrefs.getChooserStartDir(); chooserOpenStyle = mPrefs.getChooserOpenStyle(); defaultCorbaHost = mPrefs.getDefaultCorbaHost(); defaultCorbaPort = mPrefs.getDefaultCorbaPort(); WindowSizeTableModel table_model = new WindowSizeTableModel(windowWidth, windowHeight); table_model.addTableModelListener(this); mWinSizeTable = new JTable(table_model); try { jbInit(); } catch(Exception e) { e.printStackTrace(); } this.configComboBoxes(); mCorbaHostField.setText(String.valueOf(defaultCorbaHost)); mCorbaPortField.setText(String.valueOf(defaultCorbaPort)); switch ( chooserOpenStyle ) { case GlobalPreferencesService.EMACS_CHOOSER: mEmacsStyleButton.setSelected(true); break; case GlobalPreferencesService.WINDOWS_CHOOSER: default: mWindowsStyleButton.setSelected(true); break; } this.setModal(true); this.setLocationRelativeTo(owner); } public void display () { this.pack(); this.setVisible(true); } public void setBeanViewer (String v) { mPrefs.setBeanViewer(v); } public int getStatus () { return status; } public void tableChanged(TableModelEvent e) { WindowSizeTableModel model = (WindowSizeTableModel) e.getSource(); switch (e.getColumn()) { case 0: windowWidth = (Integer) model.getValueAt(0, 0); break; case 1: windowHeight = (Integer) model.getValueAt(0, 1); break; } } public static final int OK_OPTION = JOptionPane.OK_OPTION; public static final int CANCEL_OPTION = JOptionPane.CANCEL_OPTION; public static final int CLOSED_OPTION = JOptionPane.CLOSED_OPTION; protected void processWindowEvent (WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { status = CLOSED_OPTION; } } private void jbInit() throws Exception { mOkButton.setMnemonic('O'); mOkButton.setText("OK"); mOkButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { okButtonAction(e); } }); mSaveButton.setMnemonic('S'); mSaveButton.setText("Save"); mSaveButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { saveButtonAction(e); } }); mCancelButton.setMnemonic('C'); mCancelButton.setText("Cancel"); mCancelButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { cancelButtonAction(e); } }); mFileChooserPanel.setLayout(mFileChooserLayout); mFcConfigPanel.setLayout(mFcConfigLayout); mFcStartDirLabel.setMaximumSize(new Dimension(24, 13)); mFcStartDirLabel.setMinimumSize(new Dimension(24, 13)); mFcStartDirLabel.setPreferredSize(new Dimension(24, 13)); mFcStartDirLabel.setHorizontalAlignment(SwingConstants.RIGHT); mFcStartDirLabel.setText("Start Directory"); mFcStartDirBox.setMinimumSize(new Dimension(126, 10)); mFcStartDirBox.setPreferredSize(new Dimension(130, 10)); mFcStartDirBox.setEditable(true); mFcOpenStyleTitleLabel.setMaximumSize(new Dimension(24, 13)); mFcOpenStyleTitleLabel.setMinimumSize(new Dimension(24, 13)); mFcOpenStyleTitleLabel.setPreferredSize(new Dimension(24, 13)); mFcOpenStyleTitleLabel.setHorizontalAlignment(SwingConstants.RIGHT); mFcOpenStyleTitleLabel.setText("Open Style"); mEmacsStyleButton.setMinimumSize(new Dimension(109, 15)); mEmacsStyleButton.setPreferredSize(new Dimension(109, 15)); mEmacsStyleButton.setText("Emacs Style"); mEmacsStyleButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { chooserOpenStyle = GlobalPreferencesService.EMACS_CHOOSER; } }); mWindowsStyleButton.setMinimumSize(new Dimension(128, 15)); mWindowsStyleButton.setPreferredSize(new Dimension(128, 15)); mWindowsStyleButton.setText("Windows Style"); mWindowsStyleButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { chooserOpenStyle = GlobalPreferencesService.WINDOWS_CHOOSER; } }); mFcOpenStyleButtonPanel.setLayout(mFcOpenStyleButtonLayout); mFcOpenStyleButtonLayout.setColumns(1); mFcOpenStyleButtonLayout.setRows(0); mFcOpenStyleButtonPanel.setMinimumSize(new Dimension(128, 50)); mFcOpenStyleButtonPanel.setPreferredSize(new Dimension(128, 50)); mLazyInstanceButton.setSelected(mPrefs.getLazyPanelBeanInstantiation()); mLazyInstanceButton.setText("Lazy Panel Bean Instantiaion"); mLevelBox.setMinimumSize(new Dimension(126, 10)); mLevelBox.setPreferredSize(new Dimension(130, 10)); mViewerBox.setMinimumSize(new Dimension(126, 10)); mViewerBox.setPreferredSize(new Dimension(130, 10)); mGeneralPanel.setToolTipText("General Tweek interface configuration"); mGeneralPanel.setLayout(mGenLayout); mLevelLabel.setMinimumSize(new Dimension(24, 13)); mLevelLabel.setPreferredSize(new Dimension(24, 13)); mLevelLabel.setHorizontalAlignment(SwingConstants.RIGHT); mLevelLabel.setLabelFor(mLevelBox); mLevelLabel.setText("User Level"); mViewerLabel.setMaximumSize(new Dimension(24, 13)); mViewerLabel.setMinimumSize(new Dimension(24, 13)); mViewerLabel.setPreferredSize(new Dimension(24, 13)); mViewerLabel.setHorizontalAlignment(SwingConstants.RIGHT); mViewerLabel.setLabelFor(mViewerBox); mViewerLabel.setText("Bean Viewer"); mGenConfigPanel.setLayout(mGenConfigLayout); mLafBox.setMinimumSize(new Dimension(126, 10)); mLafBox.setPreferredSize(new Dimension(130, 10)); mLafLabel.setMaximumSize(new Dimension(74, 13)); mLafLabel.setMinimumSize(new Dimension(24, 13)); mLafLabel.setPreferredSize(new Dimension(24, 13)); mLafLabel.setHorizontalAlignment(SwingConstants.RIGHT); mLafLabel.setLabelFor(mLafBox); mLafLabel.setText("Look and Feel"); mCorbaPortField.setMaximumSize(new Dimension(15, 17)); mCorbaPortField.setMinimumSize(new Dimension(15, 17)); mCorbaPortField.setPreferredSize(new Dimension(15, 17)); mCorbaPortField.setToolTipText("The port number of the CORBA Naming Service"); mCorbaPortField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { corbaPortFieldChanged(e); } }); mCorbaPortLabel.setMaximumSize(new Dimension(77, 13)); mCorbaPortLabel.setMinimumSize(new Dimension(77, 13)); mCorbaPortLabel.setPreferredSize(new Dimension(77, 13)); mCorbaPortLabel.setHorizontalAlignment(SwingConstants.RIGHT); mCorbaPortLabel.setLabelFor(mCorbaPortField); mCorbaPortLabel.setText("Port Number"); mCorbaPanel.setLayout(mCorbaLayout); mCorbaHostField.setMaximumSize(new Dimension(120, 17)); mCorbaHostField.setMinimumSize(new Dimension(85, 17)); mCorbaHostField.setPreferredSize(new Dimension(85, 17)); mCorbaHostField.setToolTipText("The hostname for the CORBA Naming Service"); mCorbaHostField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { corbaHostFieldChanged(e); } }); mCorbaHostLabel.setHorizontalAlignment(SwingConstants.RIGHT); mCorbaHostLabel.setLabelFor(mCorbaHostField); mCorbaHostLabel.setText("Host Name"); mWinSizeLabel.setHorizontalAlignment(SwingConstants.RIGHT); mWinSizeLabel.setText("Window Size"); mWinSizeTable.setCellSelectionEnabled(true); mWinSizeTable.setRowSelectionAllowed(false); mWinSizeTablePane.setMaximumSize(new Dimension(32767, 16)); mWinSizeTablePane.setMinimumSize(new Dimension(150, 16)); mWinSizeTablePane.setPreferredSize(new Dimension(150, 16)); mButtonPanel.add(mOkButton, null); mButtonPanel.add(mSaveButton, null); mButtonPanel.add(mCancelButton, null); this.getContentPane().add(mContentPane, BorderLayout.NORTH); mContentPane.add(mGeneralPanel, "General"); mGeneralPanel.add(mGenConfigPanel, BorderLayout.CENTER); mGenConfigPanel.add(mLevelLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 3), 95, 23)); mGenConfigPanel.add(mLevelBox, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 64, 14)); mGenConfigPanel.add(mLafLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 3), 95, 23)); mGenConfigPanel.add(mLafBox, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 64, 14)); mGenConfigPanel.add(mViewerLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 3), 95, 23)); mGenConfigPanel.add(mViewerBox, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 64, 14)); mGenConfigPanel.add(mLazyInstanceButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); mGenConfigPanel.add(mWinSizeLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 3), 0, 23)); mContentPane.add(mCorbaPanel, "CORBA"); mCorbaPanel.add(mCorbaHostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 40, 9)); mCorbaPanel.add(mCorbaHostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 4), 112, 9)); mCorbaPanel.add(mCorbaPortLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(4, 0, 1, 2), 40, 9)); mCorbaPanel.add(mCorbaPortField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(4, 0, 1, 1), 45, 9)); this.getContentPane().add(mButtonPanel, BorderLayout.SOUTH); mFileChooserPanel.add(mFcConfigPanel, BorderLayout.CENTER); mFcConfigPanel.add(mFcStartDirLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 95, 23)); mFcConfigPanel.add(mFcStartDirBox, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 64, 14)); mFcConfigPanel.add(mFcOpenStyleTitleLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 3), 95, 23)); mFcConfigPanel.add(mFcOpenStyleButtonPanel, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 66, 0)); mFcOpenStyleButtonPanel.add(mWindowsStyleButton, null); mFcOpenStyleButtonPanel.add(mEmacsStyleButton, null); mOpenStyleButtonGroup.add(mWindowsStyleButton); mOpenStyleButtonGroup.add(mEmacsStyleButton); mContentPane.add(mFileChooserPanel, "File Chooser"); mWinSizeTablePane.getViewport().add(mWinSizeTable); mGenConfigPanel.add(mWinSizeTablePane, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 16)); } /** * Adds items to all the combo boxes. In some cases, other modifications * to a combo box will be made. These can include setting the default * selected value and/or adding action listeners. */ private void configComboBoxes () { // Add all the known Bean viewers to mViewerBox. java.util.Vector viewers = mPrefs.getBeanViewers(); for ( int i = 0; i < viewers.size(); i++ ) { mViewerBox.addItem(viewers.elementAt(i)); } mViewerBox.setSelectedItem(mPrefs.getBeanViewer()); mViewerBox.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { beanViewer = (String) mViewerBox.getSelectedItem(); } }); // Add user level options to mLevelBox. for ( int i = GlobalPreferencesService.MIN_USER_LEVEL; i <= GlobalPreferencesService.MAX_USER_LEVEL; i++ ) { mLevelBox.addItem(String.valueOf(i)); } mLevelBox.setSelectedIndex(mPrefs.getUserLevel() - 1); mLevelBox.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { userLevel = mLevelBox.getSelectedIndex() + 1; } }); // Handle the Look-and-Feel box. UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); int selected_index = 0; String cur_laf = mPrefs.getLookAndFeel(); // Add the available look-and-feel objects to the combo box. for ( int i = 0; i < lafs.length; ++i ) { mLafBox.addItem(lafs[i]); if ( lafs[i].getClassName().equals(cur_laf) ) { selected_index = i; } } mLafBox.setSelectedIndex(selected_index); mLafBox.setRenderer(new LAFBoxRenderer()); mLafBox.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { UIManager.LookAndFeelInfo val = (UIManager.LookAndFeelInfo) mLafBox.getSelectedItem(); lookAndFeel = val.getClassName(); } }); // Handle the file chooser starting directory box stuff. Iterator i = GlobalPreferencesService.getStartDirList().iterator(); boolean has_start_dir = false; while ( i.hasNext() ) { String dir = (String) i.next(); if ( dir.equals(chooserStartDir) ) { has_start_dir = true; } mFcStartDirBox.addItem(dir); } if ( ! has_start_dir ) { mFcStartDirBox.addItem(chooserStartDir); } mFcStartDirBox.setSelectedItem(chooserStartDir); mFcStartDirBox.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { chooserStartDir = (String) mFcStartDirBox.getSelectedItem(); } }); } private void okButtonAction (ActionEvent e) { status = OK_OPTION; commit(); mPrefs.save(); setVisible(false); } private void saveButtonAction (ActionEvent e) { commit(); mPrefs.save(); } private void cancelButtonAction (ActionEvent e) { status = CANCEL_OPTION; setVisible(false); } private void commit () { mPrefs.setUserLevel(userLevel); mPrefs.setLookAndFeel(lookAndFeel); mPrefs.setBeanViewer(beanViewer); mPrefs.setWindowWidth(windowWidth.intValue()); mPrefs.setWindowHeight(windowHeight.intValue()); mPrefs.setChooserStartDir(chooserStartDir); mPrefs.setChooserOpenStyle(chooserOpenStyle); mPrefs.setLazyPanelBeanInstantiation(mLazyInstanceButton.isSelected()); mPrefs.setDefaultCorbaHost(defaultCorbaHost); mPrefs.setDefaultCorbaPort(defaultCorbaPort); } /** * Action taken when the user changes the text field containing the default * CORBA port. This validates the entered port number to ensure that it is * valid. */ private void corbaHostFieldChanged(ActionEvent e) { defaultCorbaHost = mCorbaHostField.getText(); } /** * Action taken when the user changes the text field containing the default * CORBA port. This validates the entered port number to ensure that it is * valid. */ private void corbaPortFieldChanged(ActionEvent e) { try { int port = Integer.parseInt(mCorbaPortField.getText()); if ( port > 0 && port < 65536 ) { defaultCorbaPort = port; } else { mCorbaPortField.setText(String.valueOf(defaultCorbaPort)); } } catch (Exception ex) { mCorbaPortField.setText(String.valueOf(defaultCorbaPort)); } } private class WindowSizeTableModel extends AbstractTableModel { public WindowSizeTableModel(Integer width, Integer height) { this.width = width; this.height = height; } public int getRowCount() { return 1; } public int getColumnCount() { return 2; } public String getColumnName(int col) { return (col == 0 ? "Width" : "Height"); } public Object getValueAt(int row, int column) { return (column == 0 ? width : height); } public void setValueAt(Object newVal, int row, int column) { switch (column) { case 0: width = (Integer) newVal; break; case 1: height = (Integer) newVal; break; } fireTableCellUpdated(row, column); } /** * Overrides the default getColumnClass(). This method is critical for * getting cell renderers to work. */ public Class getColumnClass(int column) { return Integer.class; } public boolean isCellEditable(int row, int col) { return true; } private Integer width; private Integer height; } private static class LAFBoxRenderer extends JLabel implements ListCellRenderer { public LAFBoxRenderer() { setOpaque(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if ( isSelected ) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } UIManager.LookAndFeelInfo laf = (UIManager.LookAndFeelInfo) value; setText(laf.getName()); return this; } } // Private data members. private int status; private int userLevel = 0; private String lookAndFeel = null; private String beanViewer = null; private Integer windowWidth = new Integer(1024); private Integer windowHeight = new Integer(768); private String chooserStartDir = GlobalPreferencesService.DEFAULT_START; private int chooserOpenStyle = GlobalPreferencesService.DEFAULT_CHOOSER; private String defaultCorbaHost = ""; private int defaultCorbaPort = 0; private GlobalPreferencesService mPrefs = null; private JPanel mFileChooserPanel = new JPanel(); private BorderLayout mFileChooserLayout = new BorderLayout(); private JPanel mFcConfigPanel = new JPanel(); private GridBagLayout mFcConfigLayout = new GridBagLayout(); private JLabel mFcStartDirLabel = new JLabel(); private JComboBox mFcStartDirBox = new JComboBox(); private JLabel mFcOpenStyleTitleLabel = new JLabel(); private JPanel mFcOpenStyleButtonPanel = new JPanel(); private GridLayout mFcOpenStyleButtonLayout = new GridLayout(); private ButtonGroup mOpenStyleButtonGroup = new ButtonGroup(); private JRadioButton mWindowsStyleButton = new JRadioButton(); private JRadioButton mEmacsStyleButton = new JRadioButton(); private JPanel mButtonPanel = new JPanel(); private JButton mCancelButton = new JButton(); private JButton mSaveButton = new JButton(); private JButton mOkButton = new JButton(); private JTabbedPane mContentPane = new JTabbedPane(); private JCheckBox mLazyInstanceButton = new JCheckBox(); private JComboBox mLevelBox = new JComboBox(); private JComboBox mViewerBox = new JComboBox(); private JPanel mGeneralPanel = new JPanel(); private JLabel mLevelLabel = new JLabel(); private BorderLayout mGenLayout = new BorderLayout(); private JLabel mViewerLabel = new JLabel(); private GridBagLayout mGenConfigLayout = new GridBagLayout(); private JPanel mGenConfigPanel = new JPanel(); private JComboBox mLafBox = new JComboBox(); private JLabel mLafLabel = new JLabel(); private JTextField mCorbaPortField = new JTextField(); private JLabel mCorbaPortLabel = new JLabel(); private JPanel mCorbaPanel = new JPanel(); private JTextField mCorbaHostField = new JTextField(); private JLabel mCorbaHostLabel = new JLabel(); private GridBagLayout mCorbaLayout = new GridBagLayout(); private JLabel mWinSizeLabel = new JLabel(); private JTable mWinSizeTable = null; private JScrollPane mWinSizeTablePane = new JScrollPane(); }
package org.mindtrails.service; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.util.JSONPObject; import org.apache.tomcat.jni.Error; import org.mindtrails.domain.*; import org.mindtrails.domain.importData.ImportError; import lombok.Data; import org.apache.tomcat.util.codec.binary.Base64; import org.mindtrails.domain.importData.Scale; import org.mindtrails.persistence.ParticipantExportDAO; import org.mindtrails.persistence.ParticipantRepository; import org.mindtrails.persistence.StudyRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.ParameterizedTypeReference; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.support.Repositories; import org.springframework.http.*; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import sun.rmi.runtime.Log; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.net.URI; //@Data @Service public class ImportService { private static final Logger LOGGER = LoggerFactory.getLogger(ImportService.class); @Value("${import.username}") private String username; @Value("${import.password}") private String password; @Value("${import.url}") private String url; @Value("${import.path}") private String path; @Autowired ExportService exportService; @Autowired StudyRepository studyRepository; @Autowired ParticipantRepository participantRepository; /** * Class finder. * */ /** * Setup the headers for authorization. * * */ private HttpHeaders headers() { String plainCreds = username + ":" + password; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + base64Creds); return headers; } /** * Here is the function to get a complete list of scale from api/export. * * */ public List<Scale> importList(String path) { LOGGER.info("Get into the original methods"); RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> request = new HttpEntity<String>(headers()); URI uri = URI.create(path + "/api/export/"); LOGGER.info("calling url:" + uri.toString()); ResponseEntity<List<Scale>> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, request, new ParameterizedTypeReference<List<Scale>>() { }); LOGGER.info("Get something?"); try { List<Scale> response = responseEntity.getBody(); return response; } catch (HttpClientErrorException e) { throw new ImportError(e);} } /** * The function that can get data from the online api, according to the name you fill * in. * * */ public String getOnline(String path, String scale) { LOGGER.info("Get into the getOnline function"); RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> request = new HttpEntity<String>(headers()); URI uri = URI.create(path + "/api/export/" + scale); LOGGER.info("calling url:" + uri.toString()); ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, request, new ParameterizedTypeReference<String>() { }); LOGGER.info("Get some items?"); try { String response = responseEntity.getBody(); return response; } catch (HttpClientErrorException e) { throw new ImportError(e); } } /** * This is the function that used to delete information from the client site. * @param path * @param scale * @return */ @ClientOnly public Boolean deleteOnline(String path, String scale) { return false; } /** * * * Backup from local. * * */ @DataOnly public boolean localBackup(String scale, File[] list) { LOGGER.info("Successfully launch local backup"); int error = 0; if (list != null) { for (File is:list) { if (!parseDatabase(scale,readJSON(is))) error += 1; } LOGGER.info("Error: " + Integer.toString(error) + "/" + list.length); if (list.length>error) return true; } return false; } /** * * Get data from local folder, according to the name you fill in. * */ public String readJSON(File file){ LOGGER.info("Try to read a JSON file"); try { String contents = new String(Files.readAllBytes(file.toPath())); return contents; } catch (IOException e) { LOGGER.error(e.toString()); return null; } } public File[] getFileList(String scale) { LOGGER.info("Get into the getLocal function"); File folder = new File(path); String pattern = scale.toLowerCase(); File[] files = folder.listFiles((dir,name) -> name.toLowerCase().contains(pattern)); LOGGER.info("Here are the files that I found:" + files.toString()); return files; } /** * Get the type/class/object for a name. This is much more difficult that I thought. * * */ public Class<?> getClass(String scale) { LOGGER.info("What happens here?"); Class<?> clz = exportService.getDomainType(scale); if (clz != null) { LOGGER.info(clz.getName()); return clz; } LOGGER.info("Did not find it."); return null; } /*** * Saving the participant data */ @DataOnly public boolean saveParticipant(String is){ LOGGER.info("Try to save the participant table after saving the study table."); ObjectMapper mapper = new ObjectMapper(); JpaRepository rep = exportService.getRepositoryForName("participant"); if (rep != null) { Class<?> clz = exportService.getDomainType("participant"); if (clz != null) { try { JsonNode pObj = mapper.readTree(is); Iterator itr = pObj.elements(); while (itr.hasNext()) { JsonNode elm = (JsonNode) itr.next(); long index = elm.path("study").asLong(); try { Study s = studyRepository.findById(index); ObjectNode p = elm.deepCopy(); p.remove("study"); Participant participant = mapper.readValue(p.toString(), Participant.class); participant.setStudy(s); rep.save(participant); } catch (Exception e) { e.printStackTrace(); return false; } } } catch (Exception e) { e.printStackTrace(); return false; } return true; } } return false; } /** * * Save all the questionnaire and mindtrails logs */ public boolean linkParticipant(JsonNode obj, Class clz, JpaRepository rep) { LOGGER.info("Try to link a questionnaire or log with the participant"); Iterator itr = obj.elements(); ObjectMapper mapper = new ObjectMapper(); while (itr.hasNext()) { JsonNode elm = (JsonNode) itr.next(); long index = elm.path("participant").asLong(); try { Participant s = participantRepository.findOne(index); ObjectNode p = elm.deepCopy(); p.remove("participant"); Object object = mapper.readValue(p.toString(),clz); if (object instanceof hasParticipant) ((hasParticipant) object).setParticipant(s); rep.save(object); } catch (Exception e) { e.printStackTrace(); return false; } } return true; } /** * * Save all the questionnaire and mindtrails logs */ public boolean linkStudy(JsonNode obj, Class clz, JpaRepository rep) { LOGGER.info("Try to link a questionnaire or log with the study"); Iterator itr = obj.elements(); ObjectMapper mapper = new ObjectMapper(); while (itr.hasNext()) { JsonNode elm = (JsonNode) itr.next(); long index = elm.path("study").asLong(); try { Study s = studyRepository.findById(index); ObjectNode p = elm.deepCopy(); // p.set("study",null); Object object = mapper.readValue(p.toString(),clz); if (object instanceof hasStudy) ((hasStudy) object).setStudy(s); rep.save(object); } catch (Exception e) { e.printStackTrace(); return false; } } return true; } /** * parse the data you get into the database. * * */ @DataOnly public boolean parseDatabase(String scale, String is){ LOGGER.info("Get into the parseDatabase function"); ObjectMapper mapper = new ObjectMapper(); JpaRepository rep = exportService.getRepositoryForName(scale); if (rep != null) { LOGGER.info("Found " + scale + " repository."); Class<?> clz = exportService.getDomainType(scale); if (clz != null) { LOGGER.info("Found " + clz.getName() + " class."); try { JsonNode obj = mapper.readTree(is); if (hasStudy.class.isInstance(clz.newInstance())) { return linkStudy(obj,clz,rep); } else if (hasParticipant.class.isInstance(clz.newInstance())){ return linkParticipant(obj, clz, rep); } else { Iterator itr = obj.elements(); while (itr.hasNext()) { JsonNode elm = (JsonNode) itr.next(); ObjectNode p = elm.deepCopy(); Object object = mapper.readValue(p.toString(),clz); rep.save(object); }; }; } catch (Exception e) { e.printStackTrace(); return false; }; return true; }; }; return false; } @DataOnly public boolean updateParticipantLocal() { LOGGER.info("Get into the updateParticipant function."); File[] files = getFileList("ParticipantExportDAO"); for (File file:files) { return parseDatabase("ParticipantExportDAO",readJSON(file)); } return false; } @DataOnly public boolean updateStudyLocal() { LOGGER.info("Get into the updateStudy function."); File[] files = getFileList("StudyExportDAO"); for (File file:files) { return parseDatabase("StudyExportDAO",readJSON(file)); } return false; } @DataOnly public boolean updateParticipantOnline() { LOGGER.info("Get into the updateParticipant function"); String newParticipant = getOnline(url,"ParticipantExportDAO"); if (newParticipant != null) { LOGGER.info("Successfully read participant table"); return saveParticipant(newParticipant); } return false; } @DataOnly public boolean updateStudyOnline() { LOGGER.info("Get into the updatestudy function"); String newStudy = getOnline(url,"study"); if (newStudy != null) { LOGGER.info("Successfully read study table"); return parseDatabase("study",newStudy); } return false; } /** * Every five minutes the program will try to download all the data. * */ @DataOnly @Scheduled(cron = "0 5 * * * *") public void importData() { LOGGER.info("Trying to download data from api/export."); boolean newStudy = updateStudyOnline(); if (newStudy) LOGGER.info("Successfully logged new studies"); boolean newParticipant = updateParticipantOnline(); if (newParticipant) LOGGER.info("Successfully logged new participants"); int i = 0; List<String> good = new ArrayList<String>(); List<String> bad = new ArrayList<String>(); List<Scale> list = importList(url); for (Scale scale:list) { if (!scale.getName().toLowerCase().contains("exportdao")) { String is = getOnline(url, scale.getName()); if (parseDatabase(scale.getName(), is)) { i += 1; good.add(scale.getName()); } else { bad.add(scale.getName()); } } } LOGGER.info("Here is the good list:"); for (String flag:good) LOGGER.info(flag); LOGGER.info("Here is the bad list:"); for (String flag:bad) LOGGER.info(flag); LOGGER.info("Let's review all the error messages:"); } /** * * * The backup routine. */ @DataOnly @Scheduled(cron = "0 0 0 * * *") public void backUpData() { LOGGER.info("Try to backup data from local."); int i = 0; List<String> good = new ArrayList<String>(); List<String> bad = new ArrayList<String>(); List<Scale> list = importList(url); for (Scale scale:list) { File[] is = getFileList(scale.getName()); if (localBackup(scale.getName(),is)) { i += 1; good.add(scale.getName()); } else { bad.add(scale.getName()); } } LOGGER.info("Here is the good list:"); for (String flag:good) LOGGER.info(flag); LOGGER.info("Here is the bad list:"); for (String flag:bad) LOGGER.info(flag); } }
package jlibs.nblr.editor.layout; /** * @author Santhosh Kumar T */ import jlibs.core.lang.NotImplementedException; import jlibs.nblr.editor.RuleScene; import jlibs.nblr.rules.Edge; import jlibs.nblr.rules.Node; import org.netbeans.api.visual.graph.layout.GraphLayout; import org.netbeans.api.visual.graph.layout.UniversalGraph; import org.netbeans.api.visual.widget.LabelWidget; import org.netbeans.api.visual.widget.Widget; import java.awt.*; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * @author Santhosh Kumar T */ public class RuleLayout extends GraphLayout<Node, Edge>{ private boolean animated; public static final int originX = 100; public static final int originY = 50; public static final int horizontalGap = 100; public static final int verticalGap = 25; public RuleLayout(boolean animated){ this.animated = animated; } private List<List<Node>> coordinates; @Override protected void performGraphLayout(UniversalGraph<Node, Edge> graph){ RuleScene scene = (RuleScene)graph.getScene(); if(scene.getRule()==null) return; coordinates = scene.getRule().node.coordinates(); List<Integer> columns = new ArrayList<Integer>(); columns.add(originX); for(List<Node> nodes: coordinates){ for(int col=1; col<nodes.size(); col++){ while(columns.size()<=col) columns.add(horizontalGap); Node minNode = nodes.get(col-1); Node maxNode = nodes.get(col); int width = horizontalGap; if(maxNode!=null && minNode!=null){ int middleWidth = 0; for(Edge edge: minNode.outgoing){ if(edge.target==maxNode){ LabelWidget label = (LabelWidget)scene.findWidget(edge).getChildren().get(0); if(label.getLabel()!=null) middleWidth = Math.max(middleWidth, 30+label.getPreferredBounds().width); } } for(Edge edge: maxNode.outgoing){ if(edge.target==minNode){ LabelWidget label = (LabelWidget)scene.findWidget(edge).getChildren().get(0); if(label.getLabel()!=null) middleWidth = Math.max(middleWidth, 30+label.getPreferredBounds().width); } } middleWidth = Math.max(horizontalGap, middleWidth); int minWidth = scene.findWidget(minNode).getPreferredBounds().width/2; int minLoopWidth = 0; for(Edge edge: minNode.outgoing){ if(edge.loop()){ LabelWidget label = (LabelWidget)scene.findWidget(edge).getChildren().get(0); if(label.getLabel()!=null) minLoopWidth = Math.max(minLoopWidth, label.getPreferredBounds().width/2); } } int maxWidth = scene.findWidget(maxNode).getPreferredBounds().width/2; int maxLoopWidth = 0; for(Edge edge: maxNode.outgoing){ if(edge.loop()){ LabelWidget label = (LabelWidget)scene.findWidget(edge).getChildren().get(0); if(label.getLabel()!=null) maxLoopWidth = Math.max(maxLoopWidth, label.getPreferredBounds().width/2); } } width = Math.max(horizontalGap, Math.max(minWidth, minLoopWidth) + middleWidth + Math.max(maxWidth, maxLoopWidth)); } columns.set(col, Math.max(columns.get(col), width)); } } for(int i=1; i<columns.size(); i++) columns.set(i, columns.get(i-1)+columns.get(i)); analyzeEdges(graph, columns.size()); int rowCount = coordinates.size(); int rows[] = new int[rowCount]; for(int row=0; row<rowCount; row++){ int top = 0; for(Node node: coordinates.get(row)){ if(node!=null){ top = Math.max(top, node.conLeftTop); top = Math.max(top, node.conRightTop); int loop = 0; for(Edge edge: node.outgoing){ if(edge.loop()) loop++; } top = Math.max(top, loop); } } int bottom = 0; if(row>0){ for(Node node: coordinates.get(row-1)){ if(node!=null){ bottom = Math.max(bottom, node.conLeftBottom); bottom = Math.max(bottom, node.conRightBottom); } } } int height = top+bottom; rows[row] = 50*height; if(row>0) rows[row] += rows[row-1]; if(height==0) rows[row] += originY; else rows[row] += verticalGap; } for(Node node: graph.getNodes()){ Widget widget = scene.findWidget(node); Point location = new Point(columns.get(node.col), rows[node.row]/*originY + node.row * verticalGap*/); if(animated) scene.getSceneAnimator().animatePreferredLocation(widget, location); else widget.setPreferredLocation(location); } } private void analyzeEdges(UniversalGraph<Node, Edge> graph, int colCount){ for(Node node: graph.getNodes()){ node.conLeft = false; node.conRight = false; node.conTop = false; node.conBottom = false; node.conLeftTop = 0; node.conLeftBottom = 0; node.conRightTop = 0; node.conRightBottom = 0; } int rowCount = coordinates.size(); ArrayList<Edge> edgesList = new ArrayList<Edge>(graph.getEdges()); for(int row=0; row<rowCount; row++){ for(int jump=0; jump<colCount-1; jump++){ Iterator<Edge> edges = edgesList.iterator(); while(edges.hasNext()){ Edge edge = edges.next(); if(edge.forward() && edge.sameRow(row) && edge.jump()==jump){ analyzeEdge(row, jump, edge); edges.remove(); } } edges = edgesList.iterator(); while(edges.hasNext()){ Edge edge = edges.next(); if(edge.backward() && edge.sameRow(row) && edge.jump()==jump){ analyzeEdge(row, jump, edge); edges.remove(); } } } } } private void analyzeEdge(int row, int jump, Edge edge){ Node minNode = edge.min(); Node maxNode = edge.max(); if(jump==0 && !minNode.conRight && !maxNode.conLeft){ edge.con = 0; minNode.conRight = maxNode.conLeft = true; }else{ boolean topPossible = !minNode.conTop && !maxNode.conTop; if(topPossible){ int topHeight = Math.max(minNode.conRightTop, maxNode.conLeftTop); List<Node> nodes = coordinates.get(row); for(int i=minNode.col+1; i<maxNode.col; i++){ Node node = nodes.get(i); topHeight = Math.max(topHeight, node.conRightTop); topHeight = Math.max(topHeight, node.conLeftTop); } topHeight++; edge.con = -topHeight; minNode.conRightTop = maxNode.conLeftTop = topHeight; for(int i=minNode.col+1; i<maxNode.col; i++){ Node node = nodes.get(i); node.conTop = true; } }else{ //boolean bottomPossible = minNode.conBottom==0 && maxNode.conBottom==0; int bottomHeight = Math.max(minNode.conRightBottom, maxNode.conLeftBottom); List<Node> nodes = coordinates.get(row); for(int i=minNode.col+1; i<maxNode.col; i++){ Node node = nodes.get(i); bottomHeight = Math.max(bottomHeight, node.conRightBottom); bottomHeight = Math.max(bottomHeight, node.conLeftBottom); } bottomHeight++; edge.con = +bottomHeight; minNode.conRightBottom = maxNode.conLeftBottom = bottomHeight; for(int i=minNode.col+1; i<maxNode.col; i++){ Node node = nodes.get(i); node.conBottom = true; } } } } @Override protected void performNodesLayout(UniversalGraph<Node, Edge> neUniversalGraph, Collection<Node> ns){ throw new NotImplementedException(); } }
package org.radargun.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.lang.annotation.Annotation; import java.nio.file.Files; import java.util.function.Consumer; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.radargun.logging.Log; import org.radargun.logging.LogFactory; /** * Helper for listing classes on classpath. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public final class ClasspathScanner { private static final Log log = LogFactory.getLog(ClasspathScanner.class); private static final String CLASS_SUFFIX = ".class"; private static final String JAR_SUFFIX = ".jar"; private static final PrintStream NULL_PRINT_STREAM = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException {} }); private static final PrintStream ERR_PRINT_STREAM = System.err; private ClasspathScanner() {} public static <TClass, TAnnotation extends Annotation> void scanClasspath( Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { String classPath = System.getProperty("java.class.path"); String[] classPathParts = classPath.split(File.pathSeparator); for (String resource : classPathParts) { File resourceFile = new File(resource); if (resourceFile.isFile()) { scanFile(resource, 0, superClass, annotationClass, requirePackage, consumer); } else if (resourceFile.isDirectory()) { int prefixLength = resource.length() + 1; try { Files.find(resourceFile.toPath(), Integer.MAX_VALUE, (path, attrs) -> attrs.isRegularFile() && (path.toString().endsWith(CLASS_SUFFIX) || path.toString().endsWith(JAR_SUFFIX))).forEach(file -> { scanFile(file.toString(), prefixLength, superClass, annotationClass, requirePackage, consumer); }); } catch (IOException e) { throw new RuntimeException(e); } } } } protected static <TClass, TAnnotation extends Annotation> void scanFile(String resource, int prefixLength, Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { if (resource.endsWith(".jar")) { scanJar(resource, superClass, annotationClass, requirePackage, consumer); } else if (resource.endsWith(CLASS_SUFFIX)) { String className = resource.substring(prefixLength, resource.length() - CLASS_SUFFIX.length()).replaceAll("/", "."); scanClass(className, superClass, annotationClass, requirePackage, consumer); } } public static <TClass, TAnnotation extends Annotation> void scanJar(String path, Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { log.tracef("Looking for @%s %s, loading classes from %s", annotationClass.getSimpleName(), superClass.getSimpleName(), path); try (ZipInputStream inputStream = new ZipInputStream(new FileInputStream(path))) { for(;;) { ZipEntry entry = inputStream.getNextEntry(); if (entry == null) break; if (!entry.getName().endsWith(CLASS_SUFFIX)) continue; String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - CLASS_SUFFIX.length()); scanClass(className, superClass, annotationClass, requirePackage, consumer); } } catch (FileNotFoundException e) { log.error("Cannot load executed JAR file '" + path + "'to find stages."); } catch (IOException e) { log.error("Cannot open/read JAR '" + path + "'"); } } protected static <TClass, TAnnotation extends Annotation> void scanClass(String className, Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { if (requirePackage != null && !className.startsWith(requirePackage)) return; Class<?> clazz; try { System.setErr(NULL_PRINT_STREAM); // suppress any error output clazz = Class.forName(className); System.setErr(ERR_PRINT_STREAM); } catch (ClassNotFoundException e) { log.trace("Cannot load class " + className, e); return; } catch (NoClassDefFoundError e) { log.trace("Cannot load class " + className, e); return; } catch (LinkageError e) { log.trace("Cannot load class " + className, e); return; } TAnnotation annotation = clazz.getAnnotation(annotationClass); if (annotation != null) { if (!superClass.isAssignableFrom(clazz)) { return; } consumer.accept((Class<? extends TClass>) clazz); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.cantab.hayward.george.OCS; import VASSAL.build.Buildable; import VASSAL.build.module.map.boardPicker.board.HexGrid; import VASSAL.build.module.map.boardPicker.board.mapgrid.HexGridNumbering; import VASSAL.counters.Labeler; import VASSAL.tools.ScrollPane; import VASSAL.tools.logging.Logger; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Toolkit; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; /** * * @author george */ public class HexGridNumberingOverride extends HexGridNumbering { private HexGrid grid; private boolean stagger = true; public void addTo(Buildable parent) { grid = (HexGrid) parent; grid.setGridNumbering(this); } public static final String STAGGER = "stagger"; public HexGrid getGrid() { return grid; } public String[] getAttributeDescriptions() { String[] s = super.getAttributeDescriptions(); String[] val = new String[s.length + 1]; System.arraycopy(s, 0, val, 0, s.length); val[s.length] = "Odd-numbered rows numbered higher?"; return val; } public String[] getAttributeNames() { String[] s = super.getAttributeNames(); String[] val = new String[s.length + 1]; System.arraycopy(s, 0, val, 0, s.length); val[s.length] = STAGGER; return val; } public Class<?>[] getAttributeTypes() { final Class<?>[] s = super.getAttributeTypes(); final Class<?>[] val = new Class<?>[s.length + 1]; System.arraycopy(s, 0, val, 0, s.length); val[s.length] = Boolean.class; return val; } public void setAttribute(String key, Object value) { if (STAGGER.equals(key)) { if (value instanceof String) { value = Boolean.valueOf((String) value); } stagger = ((Boolean) value).booleanValue(); } else { super.setAttribute(key, value); } } public String getAttributeValueString(String key) { if (STAGGER.equals(key)) { return String.valueOf(stagger); } else { return super.getAttributeValueString(key); } } /** Draw the numbering if visible */ public void draw(Graphics g, Rectangle bounds, Rectangle visibleRect, double scale, boolean reversed) { if (visible) { forceDraw(g, bounds, visibleRect, scale, reversed); } } /** Draw the numbering, even if not visible */ public void forceDraw(Graphics g, Rectangle bounds, Rectangle visibleRect, double scale, boolean reversed) { int size = (int) (scale * fontSize + 0.5); if (size < 5) { return; } Graphics2D g2d = (Graphics2D) g; AffineTransform oldT = g2d.getTransform(); if (reversed) { AffineTransform t = AffineTransform.getRotateInstance(Math.PI, bounds.x + .5 * bounds.width, bounds.y + .5 * bounds.height); g2d.transform(t); visibleRect = t.createTransformedShape(visibleRect).getBounds(); } if (!bounds.intersects(visibleRect)) { return; } Rectangle region = bounds.intersection(visibleRect); Shape oldClip = g.getClip(); if (oldClip != null) { Area clipArea = new Area(oldClip); clipArea.intersect(new Area(region)); g.setClip(clipArea); } double deltaX = scale * grid.getHexWidth(); double deltaY = scale * grid.getHexSize(); if (grid.isSideways()) { bounds = new Rectangle(bounds.y, bounds.x, bounds.height, bounds.width); region = new Rectangle(region.y, region.x, region.height, region.width); } int minCol = 2 * (int) Math.floor((region.x - bounds.x - scale * grid.getOrigin().x) / (2 * deltaX)); double xmin = bounds.x + scale * grid.getOrigin().x + deltaX * minCol; double xmax = region.x + region.width + deltaX; int minRow = (int) Math.floor((region.y - bounds.y - scale * grid.getOrigin().y) / deltaY); double ymin = bounds.y + scale * grid.getOrigin().y + deltaY * minRow; double ymax = region.y + region.height + deltaY; Font f = new Font("Dialog", Font.PLAIN, size); Point p = new Point(); int alignment = Labeler.TOP; int offset = -(int) Math.round(deltaY / 2); if (grid.isSideways() || rotateTextDegrees != 0) { alignment = Labeler.CENTER; offset = 0; } Point gridp = new Point(); Point centerPoint = null; double radians = 0; if (rotateTextDegrees != 0) { radians = Math.toRadians(rotateTextDegrees); g2d.rotate(radians); } for (double x = xmin; x < xmax; x += 2 * deltaX) { for (double y = ymin; y < ymax; y += deltaY) { p.setLocation((int) Math.round(x), (int) Math.round(y) + offset); gridp = new Point(p.x, p.y - offset); grid.rotateIfSideways(p); // Convert from map co-ordinates to board co-ordinates gridp.translate(-bounds.x, -bounds.y); grid.rotateIfSideways(gridp); gridp.x = (int) Math.round(gridp.x / scale); gridp.y = (int) Math.round(gridp.y / scale); centerPoint = offsetLabelCenter(p, scale); Labeler.drawLabel(g2d, getName(getRow(gridp), getColumn(gridp)), centerPoint.x, centerPoint.y, f, Labeler.CENTER, alignment, color, null, null); p.setLocation((int) Math.round(x + deltaX), (int) Math.round(y + deltaY / 2) + offset); gridp = new Point(p.x, p.y - offset); grid.rotateIfSideways(p); // Convert from map co-ordinates to board co-ordinates gridp.translate(-bounds.x, -bounds.y); grid.rotateIfSideways(gridp); gridp.x = (int) Math.round(gridp.x / scale); gridp.y = (int) Math.round(gridp.y / scale); centerPoint = offsetLabelCenter(p, scale); Labeler.drawLabel(g2d, getName(getRow(gridp), getColumn(gridp)), centerPoint.x, centerPoint.y, f, Labeler.CENTER, alignment, color, null, null); } } if (rotateTextDegrees != 0) { g2d.rotate(-radians); } g.setClip(oldClip); g2d.setTransform(oldT); } @Override public Point getCenterPoint(int col, int row) { if (grid.isSideways()) { if (vDescending) col = getMaxRows() - col; if (hDescending) row = getMaxColumns() - row; } else { if (hDescending) col = getMaxColumns() - col; if (vDescending) row = getMaxRows() - row; } if (stagger && col % 2 != 0) { row } Point p = new Point(); p.x = (int) (col * grid.getHexWidth()); p.x += grid.getOrigin().x; if (col % 2 == 0) p.y = (int) (row * grid.getHexSize()); else p.y = (int) (row * grid.getHexSize() + grid.getHexSize()/2); p.y += grid.getOrigin().y; grid.rotateIfSideways(p); return p; } public int getColumn(Point p) { int x = getRawColumn(p); if (vDescending && grid.isSideways()) { x = (getMaxRows() - x); } if (hDescending && !grid.isSideways()) { x = (getMaxColumns() - x); } return x; } public int getRawColumn(Point p) { p = new Point(p); grid.rotateIfSideways(p); int x = p.x - grid.getOrigin().x; x = (int) Math.floor(x / grid.getHexWidth() + 0.5); return x; } protected JComponent getGridVisualizer() { if (visualizer == null) { visualizer = new JPanel() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { g.clearRect(0, 0, getWidth(), getHeight()); Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight()); grid.forceDraw(g, bounds, bounds, 1.0, false); forceDraw(g, bounds, bounds, 1.0, false); } public Dimension getPreferredSize() { return new Dimension(4 * (int) grid.getHexSize(), 4 * (int) grid.getHexWidth()); } }; } return visualizer; } public int getRow(Point p) { int ny = getRawRow(p); if (vDescending && !grid.isSideways()) { ny = (getMaxRows() - ny); } if (hDescending && grid.isSideways()) { ny = (getMaxColumns() - ny); } if (stagger) { if (grid.isSideways()) { if (getRawColumn(p) % 2 != 0) { if (hDescending) { ny } else { ny++; } } } else { if (getRawColumn(p) % 2 != 0) { if (vDescending) { ny } else { ny++; } } } } return ny; } protected int getRawRow(Point p) { p = new Point(p); grid.rotateIfSideways(p); Point origin = grid.getOrigin(); double dx = grid.getHexWidth(); double dy = grid.getHexSize(); int nx = (int) Math.round((p.x - origin.x) / dx); int ny; if (nx % 2 == 0) { ny = (int) Math.round((p.y - origin.y) / dy); } else { ny = (int) Math.round((p.y - origin.y - dy / 2) / dy); } return ny; } public void removeFrom(Buildable parent) { grid.setGridNumbering(null); } protected int getMaxRows() { return (int) Math.floor(grid.getContainer().getSize().height / grid.getHexWidth() + 0.5); } protected int getMaxColumns() { return (int) Math.floor(grid.getContainer().getSize().width / grid.getHexSize() + 0.5); } public static void main(String[] args) { class TestPanel extends JPanel { private static final long serialVersionUID = 1L; private boolean reversed; private double scale = 1.0; private HexGrid grid; private HexGridNumbering numbering; private TestPanel() { setLayout(new BorderLayout()); Box b = Box.createHorizontalBox(); final JTextField tf = new JTextField("1.0"); b.add(tf); tf.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { try { scale = Double.parseDouble(tf.getText()); repaint(); } // FIXME: review error message catch (NumberFormatException e1) { Logger.log(e1); } } }); final JCheckBox reverseBox = new JCheckBox("Reversed"); reverseBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { reversed = reverseBox.isSelected(); repaint(); } }); b.add(reverseBox); final JCheckBox sidewaysBox = new JCheckBox("Sideways"); sidewaysBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { grid.setAttribute(HexGrid.SIDEWAYS, sidewaysBox.isSelected() ? Boolean.TRUE : Boolean.FALSE); repaint(); } }); b.add(sidewaysBox); add(BorderLayout.NORTH, b); grid = new HexGrid(); grid.setAttribute(HexGrid.COLOR, Color.black); numbering = new HexGridNumbering(); numbering.setAttribute(HexGridNumbering.COLOR, Color.black); numbering.addTo(grid); JPanel p = new JPanel() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { Rectangle r = new Rectangle(0, 0, getWidth(), getHeight()); g.clearRect(r.x, r.y, r.width, r.height); grid.forceDraw(g, r, getVisibleRect(), scale, reversed); numbering.forceDraw(g, getBounds(), getVisibleRect(), scale, reversed); } }; Dimension d = new Dimension(4000, 4000); p.setPreferredSize(d); add(BorderLayout.CENTER, new ScrollPane(p)); } } JFrame f = new JFrame(); f.add(new TestPanel()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); screenSize.height -= 100; screenSize.width -= 100; f.setSize(screenSize); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
// BDReader.java package loci.formats.in; import java.io.*; import java.util.*; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.IniList; import loci.common.IniParser; import loci.common.IniTable; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; import loci.formats.tiff.IFD; import loci.formats.tiff.TiffParser; public class BDReader extends FormatReader { // -- Constants -- private static final String EXPERIMENT_FILE = "Experiment.exp"; private static final String[] META_EXT = {"drt","dye","exp","plt"}; // -- Fields -- private Vector<String> metadataFiles = new Vector<String>(); private Vector<String> channelNames = new Vector<String>(); private Vector<String> wellLabels = new Vector<String>(); private String plateName, plateDescription; private String[] tiffs; private MinimalTiffReader reader; // -- Constructor -- /** Constructs a new ScanR reader. */ public BDReader() { super("BD Pathway", new String[] {"exp", "tif"}); domains = new String[] {FormatTools.HCS_DOMAIN}; suffixSufficient = false; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { String id = new Location(name).getAbsolutePath(); try { id = locateExperimentFile(id); } catch (FormatException f) { return false; } catch (IOException f) { return false; } if (id.endsWith(EXPERIMENT_FILE)) { return true; } return super.isThisType(name, open); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser p = new TiffParser(stream); IFD ifd = p.getFirstIFD(); if (ifd == null) return false; String software = ifd.getIFDTextValue(IFD.SOFTWARE); return software.trim().startsWith("MATROX Imaging Library"); } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); Vector<String> files = new Vector<String>(); for (String file : metadataFiles) { if (file != null) files.add(file); } if (!noPixels && tiffs != null) { int offset = getSeries() * getImageCount(); for (int i = 0; i<getImageCount(); i++) { if (tiffs[offset + i] != null) { files.add(tiffs[offset + i]); } } } return files.toArray(new String[files.size()]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { if (reader != null) reader.close(); reader = null; tiffs = null; plateName = null; plateDescription = null; channelNames.clear(); metadataFiles.clear(); wellLabels.clear(); } } /* @see IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); int index = getSeries() * getImageCount() + no; if (tiffs[index] != null) { reader.setId(tiffs[index]); reader.openBytes(0, buf, x, y, w, h); reader.close(); } return buf; } // -- Internal FormatReader API methods -- public IniList readMetaData(String id) throws IOException { IniList exp = (new IniParser()).parseINI( new BufferedReader(new FileReader(id))); IniList plate = null; // Read Plate File for (String filename : metadataFiles) { if (filename.endsWith(".plt")) { plate = (new IniParser()).parseINI( new BufferedReader(new FileReader(filename))); } else if (filename.endsWith("RoiSummary.txt")) { RandomAccessInputStream s = new RandomAccessInputStream(filename); String line = s.readLine().trim(); while (!line.endsWith(".adf\"")) { line = s.readLine().trim(); } plateName = line.substring(line.indexOf(":")).trim(); plateName = plateName.replace('/', File.separatorChar); plateName = plateName.replace('\\', File.separatorChar); for (int i=0; i<3; i++) { plateName = plateName.substring(0, plateName.lastIndexOf(File.separator)); } plateName = plateName.substring(plateName.lastIndexOf(File.separator) + 1); s.close(); } } if (plate == null) throw new IOException("No Plate File"); IniTable plateType = plate.getTable("PlateType"); if (plateName == null) { plateName = plateType.get("Brand"); } plateDescription = plateType.get("Brand") + " " + plateType.get("Description"); Location dir = new Location(id).getAbsoluteFile().getParentFile(); for (String filename : dir.list()) { if (filename.startsWith("Well ")) { wellLabels.add(filename.split("\\s|\\.")[1]); } } core = new CoreMetadata[wellLabels.size()]; core[0] = new CoreMetadata(); // Hack for current testing/development purposes // Not all channels have the same Z!!! How to handle??? // FIXME FIXME FIXME core[0].sizeZ=1; // FIXME FIXME FIXME // END OF HACK core[0].sizeC = Integer.parseInt(exp.getTable("General").get("Dyes")); for (int i=1; i<=core[0].sizeC; i++) { channelNames.add(exp.getTable("Dyes").get(Integer.toString(i))); } // Count Images core[0].sizeT = 0; Location well = new Location(dir.getAbsolutePath(), "Well " + wellLabels.get(1)); for (String filename : well.list()) { if (filename.startsWith(channelNames.get(0)) && filename.endsWith(".tif")) { core[0].sizeT++; } } return exp; } /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { // make sure we have the experiment file id = locateExperimentFile(id); super.initFile(id); Location dir = new Location(id).getAbsoluteFile().getParentFile(); for (String file : dir.list(true)) { Location f = new Location(dir, file); if (!f.isDirectory()) { for (String ext : META_EXT) { if (checkSuffix(id, ext)) { metadataFiles.add(f.getAbsolutePath()); } } } } // parse Experiment metadata IniList experiment = readMetaData(id); Vector<String> uniqueRows = new Vector<String>(); Vector<String> uniqueColumns = new Vector<String>(); for (String well : wellLabels) { String row = well.substring(0, 1).trim(); String column = well.substring(1).trim(); if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row); if (!uniqueColumns.contains(column) && column.length() > 0) { uniqueColumns.add(column); } } int nSlices = getSizeZ() == 0 ? 1 : getSizeZ(); int nTimepoints = getSizeT(); int nWells = wellLabels.size(); int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC(); if (nChannels == 0) nChannels = 1; tiffs = getTiffs(dir.getAbsoluteFile().toString()); // [] files = new String[nChannels * nWells * nTimepoints * nSlices]; reader = new MinimalTiffReader(); reader.setId(tiffs[0]); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int pixelType = reader.getPixelType(); boolean rgb = reader.isRGB(); boolean interleaved = reader.isInterleaved(); boolean indexed = reader.isIndexed(); boolean littleEndian = reader.isLittleEndian(); reader.close(); for (int i=0; i<getSeriesCount(); i++) { core[i] = new CoreMetadata(); core[i].sizeC = nChannels; core[i].sizeZ = nSlices; core[i].sizeT = nTimepoints; core[i].sizeX = sizeX; core[i].sizeY = sizeY; core[i].pixelType = pixelType; core[i].rgb = rgb; core[i].interleaved = interleaved; core[i].indexed = indexed; core[i].littleEndian = littleEndian; core[i].dimensionOrder = "XYZTC"; core[i].imageCount = nSlices * nTimepoints * nChannels; } MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this); // populate LogicalChannel data for (int i=0; i<getSeriesCount(); i++) { for (int c=0; c<getSizeC(); c++) { store.setLogicalChannelName(channelNames.get(c), i, c); } } store.setPlateRowNamingConvention("A", 0); store.setPlateColumnNamingConvention("01", 0); store.setPlateName(plateName, 0); store.setPlateDescription(plateDescription, 0); for (int i=0; i<getSeriesCount(); i++) { MetadataTools.setDefaultCreationDate(store, id, i); String name = wellLabels.get(i); String row = name.substring(0, 1); Integer col = Integer.parseInt(name.substring(1)); store.setWellColumn(col - 1, 0, i); store.setWellRow(row.charAt(0)-'A', 0, i); store.setWellSampleIndex(i, 0, i, 0); String imageID = MetadataTools.createLSID("Image", i); store.setWellSampleImageRef(imageID, 0, i, 0); store.setImageID(imageID, i); store.setImageName(name, i); } } /* Locate the experiment file given any file in set */ private String locateExperimentFile(String id) throws FormatException, IOException { if (!checkSuffix(id, "exp")) { Location parent = new Location(id).getAbsoluteFile().getParentFile(); if (checkSuffix(id, "tif")) parent = parent.getParentFile(); for (String file : parent.list()) { if (file.equals(EXPERIMENT_FILE)) { id = new Location(parent, file).getAbsolutePath(); break; } } if (!checkSuffix(id, "exp")) { throw new FormatException("Could not find " + EXPERIMENT_FILE + " in " + parent.getAbsolutePath()); } } return id; } public String[] getTiffs(String dir) { LinkedList<String> files = new LinkedList<String>(); FileFilter wellDirFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory() && file.getName().startsWith("Well "); } }; FileFilter tiffFilter = new FileFilter() { public boolean accept(File file) { return file.getName().matches(".* - n\\d\\d\\d\\d\\d\\d\\.tif"); } }; File[] dirs = (new File(dir)).listFiles(wellDirFilter); Arrays.sort(dirs); for (File well : dirs) { File[] found = well.listFiles(tiffFilter); Arrays.sort(found); for (File file : found) { files.add(file.getAbsolutePath()); } } return files.toArray(new String[files.size()]); } }
package de.fau.cs.mad.gamekobold.template_generator; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import de.fau.cs.mad.gamekobold.R; import de.fau.cs.mad.gamekobold.R.color; import de.fau.cs.mad.gamekobold.jackson.ColumnHeader; import de.fau.cs.mad.gamekobold.jackson.StringClass; import de.fau.cs.mad.gamekobold.jackson.Table; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.NumberPicker; import android.widget.ScrollView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TableRow.LayoutParams; import android.widget.TextView; @SuppressLint("NewApi") public class TableFragment extends GeneralFragment implements NumberPicker.OnValueChangeListener{ /* * JACKSON START */ Table jacksonTable; boolean jacksonHasBeenInflated = false; /* * JACKSON END */ View view; TableLayout table; TableLayout headerTable; int amountColumns = 2; AlertDialog dialogTableView; View dialogViewTableView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainTemplateGenerator.theActiveActivity); LayoutInflater inflater = MainTemplateGenerator.theActiveActivity.getLayoutInflater(); dialogViewTableView = inflater.inflate(R.layout.alertdialog_template_generator_tableview, null); alertDialogBuilder.setView(dialogViewTableView); final NumberPicker np = ((NumberPicker) dialogViewTableView.findViewById(R.id.numberPicker1)); np.setMaxValue(99); np.setMinValue(0); np.setOnValueChangedListener(this); // np.setValue(((TableFragment) currentFragment).amountColumns); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton("Tabelle speichern",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { setAmountOfColumns(np.getValue()); } }) .setNegativeButton("Zurück",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); // create alert dialog dialogTableView = alertDialogBuilder.create(); } protected TableLayout createTableHeader() { headerTable = (TableLayout) view.findViewById(R.id.header_table); // private static TableLayout addRowToTable(TableLayout table, String contentCol1, String contentCol2) { Context context = getActivity(); final TableRow row = new TableRow(context); TableRow.LayoutParams rowParams = new TableRow.LayoutParams(); // Wrap-up the content of the row rowParams.height = TableRow.LayoutParams.MATCH_PARENT; rowParams.width = TableRow.LayoutParams.MATCH_PARENT; // The simplified version of the table of the picture above will have two columns // FIRST COLUMN TableRow.LayoutParams colParams = new TableRow.LayoutParams(); // // Wrap-up the content of the row colParams.height = TableRow.LayoutParams.MATCH_PARENT; colParams.width = TableRow.LayoutParams.MATCH_PARENT; // Set the gravity to center the gravity of the column // col1Params.gravity = TableRow.Gravity.CENTER; final ResizingEditText col1 = new ResizingEditText(context, row, this); // col1.setText("Headline1"); col1.setHint("Headline1"); setHeaderTableStyle(col1); col1.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { checkResize(0, 0, col1, row); /* * JACKSON START */ jacksonTable.setColumnTitle(0, s.toString()); Log.d("TABLE_FRAGMENT", "title changed - saved"); MainTemplateGenerator.saveTemplate(); /* * JACKSON END */ } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); row.addView(col1); // SECOND COLUMN // TableRow.LayoutParams col2Params = new TableRow.LayoutParams(); // // Wrap-up the content of the row // col2Params.height = TableRow.LayoutParams.WRAP_CONTENT; // col2Params.width = TableRow.LayoutParams.WRAP_CONTENT; // Set the gravity to center the gravity of the column // col2Params.gravity = Gravity.CENTER; final ResizingEditText col2 = new ResizingEditText(context, row, this); setHeaderTableStyle(col2); col2.setHint("Headline2"); col2.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { checkResize(0, 0, col2, row); /* * JACKSON START */ jacksonTable.setColumnTitle(1, s.toString()); Log.d("TABLE_FRAGMENT", "title changed - saved"); MainTemplateGenerator.saveTemplate(); /* * JACKSON END */ } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); row.addView(col2); headerTable.addView(row); // col1.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); // int elementSize = col1.getMeasuredWidth(); // Log.d("width", "INITAL WDTH: " + elementSize); return headerTable; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = (RelativeLayout) inflater.inflate(R.layout.template_generator_table_view, null); createTableHeader(); Button buttonAdd = (Button)view.findViewById(R.id.add); buttonAdd.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addItemList(); } }); table = (TableLayout) view.findViewById(R.id.template_generator_table); Button addColumnButton = (Button)view.findViewById(R.id.add_Column); addColumnButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addColumn(); } }); Button removeColumnButton = (Button)view.findViewById(R.id.remove_Column); removeColumnButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { removeColumn(); } }); //addItemList(); TextView addRowBelow = (TextView)view.findViewById(R.id.add_below); addRowBelow.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addItemList(); } }); setAddButtonStyle(addRowBelow); /* * JACKSON START */ Log.d("TableFragment", "jacksonHasBeenInflated:"+jacksonHasBeenInflated); final int jacksonTableColumnNumber = jacksonTable.numberOfColumns; // check if we have inflated the table with some data // BUT also check if we got any saved columns (they are only created if user goes into table!) // so if there are no saved columns or we didn't load any data we add the default columns if(jacksonHasBeenInflated && (jacksonTableColumnNumber > 0)) { // create the right amount of columns Log.d("jackson table inflating","jacksonNumberCol:"+jacksonTableColumnNumber); Log.d("jackson table inflating","amountCol:"+amountColumns); while(amountColumns < jacksonTableColumnNumber) { Log.d("jackson table inflating","addColumn()"); addColumn(); } while(amountColumns > jacksonTableColumnNumber) { Log.d("jackson table inflating","removeColumn()"); removeColumn(); } // set titles TableRow headerRow = (TableRow) headerTable.getChildAt(0); for(int i = 0; i < amountColumns; i++) { View view = headerRow.getChildAt(i); Log.d("TABLE INFLATING", "setting column header title:"+jacksonTable.columnHeaders.get(i).name); ((EditText)view).setText(jacksonTable.columnHeaders.get(i).name); setHeaderTableStyle((EditText)view); // check size checkResize(0, 0, (EditText)view, headerRow); int width = getNeededWidth(i); int height = getNeededHeight(0, headerRow); final LayoutParams lparams = new LayoutParams(width, height); view.setLayoutParams(lparams); view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); } Log.d("TABLE_FRAGMENT", "loaded table header data"); jacksonHasBeenInflated = false; } else { // add the 2 default columns jacksonTable.addColumn(new ColumnHeader("Headline1", StringClass.TYPE_STRING)); jacksonTable.addColumn(new ColumnHeader("Headline2", StringClass.TYPE_STRING)); // save template Log.d("TableFragment", "added default columns"); MainTemplateGenerator.saveTemplate(); } /* * JACKSON END */ addItemList(); return view; } //adds a new row to the listview protected void addItemList() { TableRow row= new TableRow(getActivity()); // TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT); // row.setLayoutParams(lp); table.addView(row); for(int i=0; i<amountColumns; ++i){ addColumnToRow(row); } final ScrollView sv = (ScrollView) view.findViewById(R.id.table_scroll); //invalidating didnt change anything // table.invalidate(); // table.refreshDrawableState(); // sv.invalidate(); // sv.requestLayout(); // row.invalidate(); // row.requestLayout(); // sv.scrollTo(0, sv.getBottom()); // sv.fullScroll(ScrollView.FOCUS_DOWN); //we have to do scrolling in seperate thread to make sure the new item is already inserted sv.post(new Runnable() { @Override public void run() { sv.fullScroll(ScrollView.FOCUS_DOWN); } }); } //adds a new row to the listview @Override protected void addItemList(int selected) { addItemList(); } private int getNeededWidth(int columnIndex) { int longestWidth = -1; for (int i = 0; i < headerTable.getChildCount(); i++) { View child = headerTable.getChildAt(i); TableRow oneRow = (TableRow) child; if (child instanceof TableRow) { View view = oneRow.getChildAt(columnIndex); if(view != null){ view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int elementSize = view.getMeasuredWidth(); if(elementSize > longestWidth){ longestWidth = elementSize; } } } } for (int i = 0; i < table.getChildCount(); i++) { View child = table.getChildAt(i); TableRow oneRow = (TableRow) child; if (child instanceof TableRow) { View view = oneRow.getChildAt(columnIndex); if(view != null){ view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int elementSize = view.getMeasuredWidth(); if(elementSize > longestWidth){ longestWidth = elementSize; } } } } return longestWidth; } private int getNeededHeight(int rowIndex, TableRow row) { int maxHeight = -1; for (int i = 0; i < row.getChildCount(); i++) { View child = row.getChildAt(i); if(child != null){ child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int elementSize = child.getMeasuredHeight(); if(elementSize > maxHeight){ maxHeight = elementSize; } } } return maxHeight; } protected void checkResize(int width, int height, EditText textEdited, TableRow row){ TableLayout usedTable; usedTable = table; int indexOfRow = table.indexOfChild(row); if(indexOfRow == -1){ indexOfRow = headerTable.indexOfChild(row); if(indexOfRow == -1){ Log.d("critical", "table to search for element not known!"); } else{ usedTable = headerTable; } } Log.d("index", "index == " + indexOfRow); int indexOfColumn = -1; if(usedTable.getChildAt(indexOfRow) instanceof TableRow){ indexOfColumn = ((TableRow) usedTable.getChildAt(indexOfRow)).indexOfChild(textEdited); } int longestWidth = 0; int ownColumnNumber = indexOfColumn; View longestView = null; for (int i = 0; i < table.getChildCount(); i++) { View child = table.getChildAt(i); TableRow oneRow = (TableRow) child; if (child instanceof TableRow) { View view = oneRow.getChildAt(ownColumnNumber); int elementSize = 0; if(view instanceof EditText){ //todo view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); elementSize = view.getMeasuredWidth(); if(elementSize > longestWidth){ longestWidth = elementSize; longestView = view; } } //no need to traverse over all columns, the column we just changed is enough to adapt // for (int x = 0; x < row.getChildCount(); x++) { // View view = row.getChildAt(x); // int lengthRow = 0; // if(view instanceof EditText){ // lengthRow = ((EditText) view).length(); // if(lengthRow > longestRow){ // longestRow = lengthRow; // columnNumber = x; // longestView = view; } } for (int i = 0; i < headerTable.getChildCount(); i++) { View child = headerTable.getChildAt(i); TableRow oneRow = (TableRow) child; if (child instanceof TableRow) { View view = oneRow.getChildAt(ownColumnNumber); int elementSize = 0; if(view instanceof EditText){ //todo view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); elementSize = view.getMeasuredWidth(); if(elementSize > longestWidth){ longestWidth = elementSize; longestView = view; } } } } if(longestView != null){ //force layout is needed! view has old size if we don't do it! //but problem: edittext doesnt resize anymore if we do it // longestView.forceLayout(); longestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); // int width = longestView.getMeasuredWidth(); int longestHeight = longestView.getMeasuredHeight(); if(longestWidth < width){ longestWidth = width; } if(longestHeight < height){ longestHeight = height; } adaptAllColumnsToSize(ownColumnNumber, longestWidth, longestHeight); } } protected void adaptAllColumnsToSize(int column, int width, int height){ // Log.d("width", "to adapt width == " + width); View singleRow = headerTable.getChildAt(0); if(singleRow instanceof TableRow){ View theChildToResize = ((TableRow) singleRow).getChildAt(column); if(theChildToResize instanceof EditText){ Log.d("width", "to adapt width == " + width); Log.d("width", "headline width before == " + ((EditText) theChildToResize).getWidth()); final TableRow.LayoutParams lparams = new TableRow.LayoutParams(width,((EditText) theChildToResize).getHeight()); // Width , height ((EditText) theChildToResize).setLayoutParams(lparams); Log.d("width", "headline width after == " + ((EditText) theChildToResize).getWidth()); setHeaderTableStyle((EditText) theChildToResize); // textField.invalidate(); // textField.forceLayout(); Log.d("header table", "size is set!!!"); } } for(int i=0; i<table.getChildCount(); i++){ View oneRow = table.getChildAt(i); if(oneRow instanceof TableRow){ View theChildToResize = ((TableRow) oneRow).getChildAt(column); if(theChildToResize instanceof EditText){ final TableRow.LayoutParams lparams = new TableRow.LayoutParams(width,((EditText) theChildToResize).getHeight()); // Width , height ((EditText) theChildToResize).setLayoutParams(lparams); setTableStyle((EditText) theChildToResize); } } } } protected void setAmountOfColumns(int amount){ int amountToAdd = amount - amountColumns; if(amountToAdd > 0){ for(int i=0; i<amountToAdd; i++){ addColumn(); } } else{ for(int i=amountToAdd; i<0; i++){ removeColumn(); } } } protected void addColumnToRow(final TableRow row){ final ResizingEditText oneColumn = new ResizingEditText(getActivity(), row, this); oneColumn.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { checkResize(0, 0, oneColumn, row); } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); /* * JACKSON START */ // only add to header cells if(row == headerTable.getChildAt(0)) { oneColumn.addTextChangedListener(new TextWatcher(){ // column index for this header cell !index! no + 1 needed private final int columnIndex = ((TableRow)headerTable.getChildAt(0)).getChildCount(); // callback public void afterTextChanged(Editable s) { if(!jacksonHasBeenInflated) { jacksonTable.setColumnTitle(columnIndex, s.toString()); } Log.d("TABLE_FRAGMENT", "title changed - save"); MainTemplateGenerator.saveTemplate(); } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); } /* * JACKSON END */ if(headerTable.indexOfChild(row) != -1){ setHeaderTableStyle(oneColumn); oneColumn.setText("Headline " + (((TableRow) headerTable.getChildAt(0)).getChildCount()+1)); oneColumn.setHint(oneColumn.getEditableText().toString()); } else{ setTableStyle(oneColumn); oneColumn.setText(" } row.addView(oneColumn); int columnIndex = row.indexOfChild(oneColumn); int rowIndex = table.indexOfChild(row); if(rowIndex == -1){ rowIndex = headerTable.indexOfChild(row); if(rowIndex == -1) Log.d("critical", "cant find row!"); } int width = getNeededWidth(columnIndex); int height = getNeededHeight(rowIndex, row); int oldWidth = oneColumn.getMeasuredWidth(); int oldHeight = oneColumn.getMeasuredWidth(); Log.d("width", "before w : " + oldWidth); Log.d("width", "before h : " + oldHeight); // Log.d("width", "before w: " + oneColumn.getWidth()); // Log.d("width", "before h: " + oneColumn.getHeight()); Log.d("width", "setting w: " + width); Log.d("width", "setting h: " + height); // oneColumn.setWidth(width); final LayoutParams lparams = new LayoutParams(width, height); oneColumn.setLayoutParams(lparams); oneColumn.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); // Log.d("width", "after h: " + oneColumn.getHeight()); // final TableRow.LayoutParams lparams = new TableRow.LayoutParams(width, height); // ((EditText) oneColumn).setLayoutParams(lparams); } // protected void removeColumnFromRow(TableRow row){ // int elements = row.getChildCount(); protected void addColumn() { amountColumns++; View headerRow = headerTable.getChildAt(0); TableRow row = (TableRow) headerRow; /* * JACKSON START */ // only add column if were are not loading our inflated data if(!jacksonHasBeenInflated) { jacksonTable.addColumn(new ColumnHeader("", StringClass.TYPE_STRING)); Log.d("TABLE_FRAGMENT", "added column - save"); MainTemplateGenerator.saveTemplate(); } /* * JACKSON END */ addColumnToRow(row); for (int i = 0; i < table.getChildCount(); i++) { View child = table.getChildAt(i); if (child instanceof TableRow) { row = (TableRow) child; // EditText newColumn = new EditText(getActivity()); // newColumn.setText("empty"); // newColumn.setSingleLine(); addColumnToRow(row); // row.addView(newColumn); // table.addView(row); // for (int x = 0; x < row.getChildCount(); x++) { // View view = row.getChildAt(x); // view.setEnabled(false); } } Log.d("columns", "amount == " + amountColumns); } protected void removeColumn(){ amountColumns if(amountColumns < 1){ amountColumns = 1; } else{ for (int i = 0; i < table.getChildCount(); i++) { View child = table.getChildAt(i); if (child instanceof TableRow) { TableRow row = (TableRow) child; row.removeView(row.getChildAt(row.getChildCount()-1)); // for (int x = 0; x < row.getChildCount(); x++) { // View view = row.getChildAt(x); // row.removeView(view); //// view.setEnabled(false); } } View headerRow = headerTable.getChildAt(0); TableRow row = (TableRow) headerRow; row.removeView(row.getChildAt(row.getChildCount()-1)); /* * JACKSON START */ // only remove column if we are not inflating if(!jacksonHasBeenInflated) { jacksonTable.removeColumn(); Log.d("TABLE_FRAGMENT", "removed column - save"); MainTemplateGenerator.saveTemplate(); } /* * JACKSON END */ Log.d("columns", "amount == " + amountColumns); } } /** * @param dialogTable * Method to set up the table for showing it in AlertDialog */ protected void prepareTableForDialog(TableLayout dialogTable) { dialogTable.removeAllViews(); for(int i=-1; i<amountColumns; i++){ final TableRow row = new TableRow(MainTemplateGenerator.theActiveActivity); TableRow.LayoutParams rowParams = new TableRow.LayoutParams(); rowParams.height = TableRow.LayoutParams.WRAP_CONTENT; rowParams.width = TableRow.LayoutParams.WRAP_CONTENT; //use k columns for(int k=0; k<3; k++){ final EditText oneColumn = new EditText(MainTemplateGenerator.theActiveActivity); setTableStyle(oneColumn); //TODO: how to resize the table if too big? oneColumn.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { // checkResize(0, 0, oneColumn, row); } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); //first row -> insert column descriptions if(i==-1){ if(k==0){ oneColumn.setText("Nr."); } else if(k==1){ oneColumn.setText("Spaltenname"); } else{ oneColumn.setText("Spaltentyp"); } } //insert the number of the column in the first row else if(k ==0){ oneColumn.setText(i+"."); } else if(k==1){ TableRow headerRow = (TableRow) headerTable.getChildAt(0); EditText headerText = (EditText) headerRow.getChildAt(i); Log.d("i,k", "i==" + i + ", k==" +k); oneColumn.setText(headerText.getText()); } row.addView(oneColumn); } dialogTable.addView(row); } // return table; } /* * JACKSON START */ public void jacksonInflate(Table myTable, Activity activity) { jacksonTable = myTable; jacksonHasBeenInflated = true; } /* * JACKSON END */ @Override public void showDialog() { // dialogTableView.setTitle(elementName); NumberPicker np = ((NumberPicker) dialogViewTableView.findViewById(R.id.numberPicker1)); np.setValue(amountColumns); TableLayout table = ((TableLayout) dialogViewTableView.findViewById(R.id.tableView_alert_table)); // prepareTableForDialog(table); adaptDialogTable(table); dialogTableView.show(); } protected void initializeDialogTable(TableLayout dialogTable){ final TableRow row = new TableRow(MainTemplateGenerator.theActiveActivity); TableRow.LayoutParams rowParams = new TableRow.LayoutParams(); rowParams.height = TableRow.LayoutParams.WRAP_CONTENT; rowParams.width = TableRow.LayoutParams.WRAP_CONTENT; //use k columns for(int k=0; k<3; k++){ final EditText oneColumn = new EditText(MainTemplateGenerator.theActiveActivity); String uri = "@drawable/cell_shape"; int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName()); Drawable res = getResources().getDrawable(imageResource); if (android.os.Build.VERSION.SDK_INT >= 16){ oneColumn.setBackground(res); } else{ oneColumn.setBackgroundDrawable(res); } oneColumn.setSingleLine(); View theText = oneColumn; //TODO: how to resize the table if too big? oneColumn.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { // checkResize(0, 0, oneColumn, row); } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); //first row -> insert column descriptions if(k==0){ oneColumn.setText("Nr."); } else if(k==1){ oneColumn.setText("Spaltenname"); } else{ oneColumn.setText("Spaltentyp"); } row.addView(oneColumn); } dialogTable.addView(row); } // protected void adaptDialogTable(TableLayout dialogTable){ // int rowsNeeded = ((TableRow) headerTable.getChildAt(0)).getChildCount(); // adaptDialogTable(dialogTable, rowsNeeded); protected void setTableStyle(EditText text){ String uri = "@drawable/cell_shape"; int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName()); Drawable res = getResources().getDrawable(imageResource); if (android.os.Build.VERSION.SDK_INT >= 16){ text.setBackground(res); } else{ text.setBackgroundDrawable(res); } text.setTextColor(getResources().getColor(R.color.background)); text.setSingleLine(); } protected void setAddButtonStyle(TextView text){ TableRow.LayoutParams textViewParams = new TableRow.LayoutParams(); // View theLayout = view.findViewById(R.id.main_view); // theLayout.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); // int width = theLayout.getMeasuredWidth(); // int height = theLayout.getMeasuredHeight(); Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; textViewParams.height = height; textViewParams.width = width; Log.d("width", "SCREEN.x == " + width); text.setMaxWidth(width); // text.setLayoutParams(textViewParams); // text.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large); String uri = "@drawable/cell_shape_add"; int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName()); Drawable res = getResources().getDrawable(imageResource); if (android.os.Build.VERSION.SDK_INT >= 16){ text.setBackground(res); } else{ text.setBackgroundDrawable(res); } text.setTextColor(getResources().getColor(R.color.own_grey)); text.setSingleLine(); } protected void setHeaderTableStyle(EditText text){ text.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small); String uri = "@drawable/cell_shape_green"; int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName()); Drawable res = getResources().getDrawable(imageResource); if (android.os.Build.VERSION.SDK_INT >= 16){ text.setBackground(res); } else{ text.setBackgroundDrawable(res); } text.setTextColor(getResources().getColor(R.color.white)); text.setSingleLine(); } protected void adaptDialogTable(TableLayout dialogTable){ int firstRowToAdd = dialogTable.getChildCount(); int rowsNeeded = ((TableRow) headerTable.getChildAt(0)).getChildCount();; //first step: adapt all needed Column-names from headerTable int oldColumnsToAdept = (firstRowToAdd<rowsNeeded? firstRowToAdd:rowsNeeded); for(int i=1; i<oldColumnsToAdept; i++){ TableRow headerRow = (TableRow) headerTable.getChildAt(0); EditText headerText = (EditText) headerRow.getChildAt(i-1); EditText nameFromHeaderColumn = (EditText) ((TableRow) dialogTable.getChildAt(i)).getChildAt(1); nameFromHeaderColumn.setText(headerText.getText()); } //test if header is set // if(dialogTable.getChildCount() == 0){ //// Log.e("TableFragment.java", "dialog table of Table Fragment should be initialisized, but already has children!"); //// dialogTable.removeAllViews(); // initializeDialogTable(dialogTable); //second step: add rows if needed for(int i=firstRowToAdd-1; i<rowsNeeded; i++){ Log.d("dialog", "add"); final TableRow row = new TableRow(MainTemplateGenerator.theActiveActivity); TableRow.LayoutParams rowParams = new TableRow.LayoutParams(); rowParams.height = TableRow.LayoutParams.WRAP_CONTENT; rowParams.width = TableRow.LayoutParams.WRAP_CONTENT; //use k columns for(int k=0; k<3; k++){ final EditText oneColumn = new EditText(MainTemplateGenerator.theActiveActivity); setTableStyle(oneColumn); // View theText = oneColumn; // //TODO: how to resize the table if too big? // oneColumn.addTextChangedListener(new TextWatcher(){ // public void afterTextChanged(Editable s) { // // checkResize(0, 0, oneColumn, row); // public void beforeTextChanged(CharSequence s, int start, int count, int after){ // public void onTextChanged(CharSequence s, int start, int before, int count){ //first row -> insert column descriptions if(i==-1){ if(k==0){ oneColumn.setText("Nr."); } else if(k==1){ oneColumn.setText("Spaltenname"); } else{ oneColumn.setText("Spaltentyp"); } } //insert the number of the column in the first row else if(k ==0){ oneColumn.setText((i+1)+"."); } else if(k==1){ TableRow headerRow = (TableRow) headerTable.getChildAt(0); EditText headerText = (EditText) headerRow.getChildAt(i); // Log.d("i,k", "i==" + ", k==" +k); oneColumn.setText(headerText.getText()); final int index = i; oneColumn.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { TableRow headerRow = (TableRow) headerTable.getChildAt(0); EditText headerText = (EditText) headerRow.getChildAt(index); headerText.setText(s); // checkResize(0, 0, oneColumn, row); } public void beforeTextChanged(CharSequence s, int start, int count, int after){ } public void onTextChanged(CharSequence s, int start, int before, int count){ } }); } row.addView(oneColumn); } dialogTable.addView(row); } //last step: remove rows if needed for(int i=rowsNeeded+1; i<firstRowToAdd; i++){ Log.d("dialog", "remove"); dialogTable.removeView(dialogTable.getChildAt(dialogTable.getChildCount()-1)); } } @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { setAmountOfColumns(newVal); // adaptDialogTable(((TableLayout) dialogViewTableView.findViewById(R.id.tableView_alert_table)), newVal); adaptDialogTable(((TableLayout) dialogViewTableView.findViewById(R.id.tableView_alert_table))); } }
package com.opensymphony.workflow.designer; import java.util.List; import javax.swing.JOptionPane; import com.opensymphony.workflow.loader.AbstractDescriptor; import com.opensymphony.workflow.loader.ActionDescriptor; import com.opensymphony.workflow.loader.DescriptorBuilder; import com.opensymphony.workflow.loader.JoinDescriptor; import com.opensymphony.workflow.loader.ResultDescriptor; import com.opensymphony.workflow.loader.SplitDescriptor; import com.opensymphony.workflow.loader.StepDescriptor; /** * @author baab */ public class ConnectHelper { private static final int CONDITIONAL = 0; private static final int UNCONDITIONAL = 1; private static final int UNKNOWN = -1; private static boolean isConnectable(WorkflowCell source, WorkflowCell target) { if(source == null || target == null) { return false; } if(source instanceof InitialActionCell && target instanceof StepCell) { return true; } else if(source instanceof StepCell && !(target instanceof InitialActionCell)) { return true; } else if(source instanceof JoinCell && target instanceof StepCell) { return true; } else if(source instanceof SplitCell && target instanceof StepCell) { return true; } return false; } public static boolean connect(WorkflowCell source, WorkflowCell target, WorkflowGraphModel model) { if(!isConnectable(source, target)) { return false; } if(source instanceof SplitCell && target instanceof StepCell) { return connectSplitToStep((SplitCell)source, (StepCell)target, model); } else if(source instanceof InitialActionCell && target instanceof StepCell) { return connectStartToStep((InitialActionCell)source, (StepCell)target, model); } else if(source instanceof JoinCell && target instanceof StepCell) { return connectJoinToStep((JoinCell)source, (StepCell)target, model); } else if(source instanceof StepCell && !(target instanceof InitialActionCell)) { return connectStepTo((StepCell)source, target, model); } return true; } private static boolean isConnected(List results, AbstractDescriptor desc) { if(results == null || results.size() == 0) { return false; } if(desc instanceof StepDescriptor) { return _isConnected(results, (StepDescriptor)desc); } else if(desc instanceof SplitDescriptor) { return _isConnected(results, (SplitDescriptor)desc); } else if(desc instanceof JoinDescriptor) { return _isConnected(results, (JoinDescriptor)desc); } return false; } private static boolean _isConnected(List results, StepDescriptor step) { if(results == null) { return false; } for(int i = 0; i < results.size(); i++) { ResultDescriptor result = (ResultDescriptor)results.get(i); if(result.getStep() == step.getId()) { // already connected return true; } } return false; } private static boolean _isConnected(List results, JoinDescriptor join) { if(results == null) { return false; } for(int i = 0; i < results.size(); i++) { ResultDescriptor result = (ResultDescriptor)results.get(i); if(result.getJoin() == join.getId()) { // already connected return true; } } return false; } private static boolean _isConnected(List results, SplitDescriptor split) { if(results == null) { return false; } for(int i = 0; i < results.size(); i++) { ResultDescriptor result = (ResultDescriptor)results.get(i); if(result.getSplit() == split.getId()) { // already connected return true; } } return false; } private static boolean isConnected(ResultDescriptor result, AbstractDescriptor desc) { if(result == null) { return false; } if(desc instanceof StepDescriptor) { return _isConnected(result, (StepDescriptor)desc); } else if(desc instanceof JoinDescriptor) { return _isConnected(result, (JoinDescriptor)desc); } else if(desc instanceof SplitDescriptor) { return _isConnected(result, (SplitDescriptor)desc); } return false; } private static boolean _isConnected(ResultDescriptor result, StepDescriptor step) { return result.getStep() == step.getId(); } private static boolean _isConnected(ResultDescriptor result, JoinDescriptor join) { return result.getJoin() == join.getId(); } private static boolean _isConnected(ResultDescriptor result, SplitDescriptor split) { return result.getSplit() == split.getId(); } private static int getConnectType(ActionDescriptor from, AbstractDescriptor to) { List results = from.getConditionalResults(); if(isConnected(results, to)) { return UNKNOWN; } ResultDescriptor result = from.getUnconditionalResult(); if(isConnected(result, to)) { return UNKNOWN; } int type; if(result != null) { type = CONDITIONAL; } else { // choose unconditional or conditional String conditional = ResourceManager.getString("result.conditional"); String unconditional = ResourceManager.getString("result.unconditional"); String cancel = ResourceManager.getString("cancel"); type = JOptionPane.showOptionDialog(null, ResourceManager.getString("result.select.long"), ResourceManager.getString("result.select"), JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{conditional, unconditional, cancel}, conditional); if(type != 0 && type != 1) { // cancel return UNKNOWN; } } return type; } private static boolean connectStepTo(StepCell source, WorkflowCell target, WorkflowGraphModel model) { ActionDescriptor sourceAction = DescriptorBuilder.createAction(source.getDescriptor(), source.getDescriptor().getName(), Utils.getNextId(model.getContext())); Utils.checkId(model.getContext(), sourceAction); AbstractDescriptor to; if(target instanceof StepCell) { to = ((StepCell)target).getDescriptor(); } else if(target instanceof SplitCell) { to = ((SplitCell)target).getSplitDescriptor(); } else if(target instanceof JoinCell) { to = ((JoinCell)target).getJoinDescriptor(); } else { return false; } ResultDescriptor result; int type = getConnectType(sourceAction, to); if(type == CONDITIONAL) { result = DescriptorBuilder.createConditionalResult(model, to); } else if(type == UNCONDITIONAL) { result = DescriptorBuilder.createResult(model, to); } else { return false; } result.setParent(sourceAction); if(type == CONDITIONAL) { sourceAction.getConditionalResults().add(result); } else { sourceAction.setUnconditionalResult(result); } model.recordResult(source, result, sourceAction); model.connectCells(source, sourceAction, target, result); return true; } private static boolean connectStartToStep(InitialActionCell source, StepCell target, WorkflowGraphModel model) { ActionDescriptor start = source.getActionDescriptor(); StepDescriptor step = target.getDescriptor(); ResultDescriptor result; int type = getConnectType(start, step); if(type == CONDITIONAL) { result = DescriptorBuilder.createConditionalResult(model, step); } else if(type == UNCONDITIONAL) { result = DescriptorBuilder.createResult(model, step); } else { return false; } result.setParent(start); if(type == CONDITIONAL) { start.getConditionalResults().add(result); } else { start.setUnconditionalResult(result); } // create new resultCell model.recordResult(source, result, start); model.connectCells(source, start, target, result); return true; } private static boolean connectSplitToStep(SplitCell source, StepCell target, WorkflowGraphModel model) { SplitDescriptor split = source.getSplitDescriptor(); StepDescriptor step = target.getDescriptor(); List results = split.getResults(); if(isConnected(results, step)) { return false; } // create new unconditional result ResultDescriptor result = DescriptorBuilder.createResult(model, step); result.setParent(split); // add to split's result list results.add(result); model.recordResult(source, result, null); // update the graph model.connectCells(source, null, target, result); return true; } private static boolean connectJoinToStep(JoinCell source, StepCell target, WorkflowGraphModel model) { JoinDescriptor join = source.getJoinDescriptor(); StepDescriptor step = target.getDescriptor(); ResultDescriptor result = join.getResult(); if(result != null) { return false; } // create new unconditional result result = DescriptorBuilder.createResult(model, step); result.setParent(join); join.setResult(result); model.recordResult(source, result, null); // update the graph model.connectCells(source, null, target, result); return true; } }
package helpers; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class StatsReporter { private static final long REPORT_INTERVAL_MILLIS = 10000l; private static final String REPORT_FILE_NAME = "report-stats.csv"; private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n"); // metrics not in use: "OpenFileDescriptorCount", "freeHeap", "FreeSwapSpaceSize", "maxHeap", // "MaxFileDescriptorCount", "TotalSwapSpaceSize", "heapSize", "ProcessCpuTime", , // "SystemCpuLoad", "CommittedVirtualMemorySize" private static final String[] keys = { "reportTime", "tasksCount", "latency", "ProcessCpuLoad", "heapSize"}; private final File reportFile; private final Lock latencyGetLock; private final Lock latencyUpdateLock; private final AtomicLong latencyTotal; private final AtomicInteger latencyReportsCounter; private int taskCounter; private long lastTimeReported; private volatile static StatsReporter instance = null; private StatsReporter() { this.reportFile = new File(REPORT_FILE_NAME); ReentrantReadWriteLock multiReportLock = new ReentrantReadWriteLock(); this.latencyGetLock = multiReportLock.writeLock(); this.latencyUpdateLock = multiReportLock.readLock(); this.latencyTotal = new AtomicLong(); this.latencyReportsCounter = new AtomicInteger(); this.taskCounter = 0; this.lastTimeReported = 0; writeHeaderToFile(); } public static StatsReporter get() { if (instance == null) { synchronized (StatsReporter.class) { if (instance == null) { instance = new StatsReporter(); } } } return instance; } public void incTasksCompleted() { taskCounter++; } public void reportLatency(long latencyMillis) { latencyUpdateLock.lock(); try { latencyTotal.addAndGet(latencyMillis); latencyReportsCounter.incrementAndGet(); } finally { latencyUpdateLock.unlock(); } } public void generateReport() { long now = System.currentTimeMillis(); if (lastTimeReported >= (now - REPORT_INTERVAL_MILLIS)) { return; } doGenerateReport(); lastTimeReported = System.currentTimeMillis(); } private void doGenerateReport() { Map<String, Object> statMap = new HashMap<String, Object>(); statMap.put("reportTime", System.currentTimeMillis()); statMap.put("tasksCount", taskCounter); taskCounter = 0; statMap.put("latency", doLatency()); addHeapStats(statMap); // doesn't work well with java9 // addMoreStats(statMap); // String jsonReport = toJson(statMap); String csvReport = toCsv(statMap); appendToFile(csvReport); } private long doLatency() { latencyGetLock.lock(); try { long totalLatency = latencyTotal.getAndSet(0); int count = latencyReportsCounter.getAndSet(0); if (count == 0) { return 0; } return totalLatency / count; } finally { latencyGetLock.unlock(); } } private static void addHeapStats(Map<String, Object> map) { Runtime runtime = Runtime.getRuntime(); map.put("heapSize", runtime.totalMemory()); map.put("maxHeap", runtime.maxMemory()); map.put("freeHeap", runtime.freeMemory()); } private void addMoreStats(Map<String, Object> map) { OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); String getPrefix = "get"; for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) { method.setAccessible(true); if (method.getName().startsWith(getPrefix) && Modifier.isPublic(method.getModifiers())) { Object value; try { value = method.invoke(operatingSystemMXBean); } catch (Exception e) { value = e; } String key = method.getName().substring(getPrefix.length()); map.put(key, value); } } } private String toCsv(Map<String, Object> statMap) { StringBuilder csv = new StringBuilder(""); for (String key : keys) { Object value = statMap.get(key); csv.append(value).append(", "); } csv.append(LINE_SEPARATOR); return csv.toString(); } private void writeHeaderToFile() { String header = Arrays.toString(keys); header = header.substring(1, header.length() -1) + "," + LINE_SEPARATOR; appendToFile(header, false); } private void appendToFile(String reportText) { appendToFile(reportText, true); } private void appendToFile(String reportText, boolean append) { FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(reportFile, append); bw = new BufferedWriter(fw); bw.write(reportText); bw.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (bw != null) { try { fw.close(); } catch (Exception e) { e.printStackTrace(); } } if (fw != null) { try { fw.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
package dr.app.beagle.tools.parsers; import java.util.logging.Logger; import dr.app.beagle.evomodel.sitemodel.BranchSubstitutionModel; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.sitemodel.HomogenousBranchSubstitutionModel; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.app.beagle.evomodel.substmodel.SubstitutionModel; import dr.app.beagle.tools.BeagleSequenceSimulator; import dr.evolution.alignment.Alignment; import dr.evolution.datatype.Codons; import dr.evolution.datatype.Nucleotides; import dr.evolution.sequence.Sequence; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.tree.TreeModel; import dr.xml.AbstractXMLObjectParser; import dr.xml.AttributeRule; import dr.xml.ElementRule; import dr.xml.XMLObject; import dr.xml.XMLParseException; import dr.xml.XMLSyntaxRule; import dr.xml.XORRule; /** * @author Filip Bielejec * @version $Id$ */ public class BeagleSequenceSimulatorParser extends AbstractXMLObjectParser { private static final String BEAGLE_SEQUENCE_SIMULATOR = "beagleSequenceSimulator"; private static final String REPLICATIONS = "replications"; // private static final String SITE_MODEL = "siteModel"; @Override public String getParserName() { return BEAGLE_SEQUENCE_SIMULATOR; } @Override public String getParserDescription() { return "Beagle sequence simulator"; } @Override public Class<Alignment> getReturnType() { return Alignment.class; } @Override public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[] { new ElementRule(TreeModel.class), new XORRule( new ElementRule(BranchSubstitutionModel.class), new ElementRule(SubstitutionModel.class), false), new ElementRule(GammaSiteRateModel.class), new ElementRule(BranchRateModel.class, true), new ElementRule(FrequencyModel.class), new ElementRule(Sequence.class, true), AttributeRule.newIntegerRule(REPLICATIONS) }; // return null; }//END: getSyntaxRules @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { String msg = ""; TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); GammaSiteRateModel siteModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); FrequencyModel freqModel = (FrequencyModel) xo.getChild(FrequencyModel.class); Sequence ancestralSequence = (Sequence) xo.getChild(Sequence.class); int replications = xo.getIntegerAttribute(REPLICATIONS); msg += "\n " + replications + ( (replications > 1) ? " replications " : " replication"); BranchRateModel rateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); if (rateModel == null) { rateModel = new DefaultBranchRateModel(); msg += "\n " + "default branch rate model with rate of 1.0"; } else { msg += "\n " + rateModel.getModelName() + " branch rate model"; } // TODO check this for cast errors BranchSubstitutionModel branchSubstitutionModel = (BranchSubstitutionModel) xo.getChild(BranchSubstitutionModel.class); if (branchSubstitutionModel == null) { SubstitutionModel substitutionModel = (SubstitutionModel) xo.getChild(SubstitutionModel.class); branchSubstitutionModel = new HomogenousBranchSubstitutionModel(substitutionModel, freqModel); // System.err.println("FUBAR"); } BeagleSequenceSimulator s = new BeagleSequenceSimulator( tree, branchSubstitutionModel, siteModel, rateModel, freqModel, replications ); if (ancestralSequence != null) { if (ancestralSequence.getLength() != 3 * replications && freqModel.getDataType() instanceof Codons) { throw new RuntimeException("Ancestral codon sequence has " + ancestralSequence.getLength() + " characters " + "expecting " + 3*replications + " characters"); } else if (ancestralSequence.getLength() != replications && freqModel.getDataType() instanceof Nucleotides) { throw new RuntimeException("Ancestral nuleotide sequence has " + ancestralSequence.getLength() + " characters " + "expecting " + replications + " characters"); } else { s.setAncestralSequence(ancestralSequence); }// END: dataType check }// END: ancestralSequence check if (msg.length() > 0) { Logger.getLogger("dr.evomodel").info("Using Beagle Sequence Simulator: " + msg); } return s.simulate(); }// END: parseXMLObject }// END: class
package edu.mit.streamjit.util.bytecode.methodhandles; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Convenience methods for {@link MethodHandles.Lookup} methods that infer * arguments when unambiguous and do not throw checked exceptions. * * Methods taking a Lookup and not a container class assume the container class * is the lookup class. Methods taking a container class and not a Lookup use * the public lookup. * * Methods not taking a type look reflectively at the class for a member with * the given name. If there is exactly one matching member, it will be looked * up as though no reflection was performed (i.e., not using Lookup.unreflect*). * @author Jeffrey Bosboom <jbosboom@csail.mit.edu> * @since 10/6/2014 (based on StreamJIT LookupUtils, @since 11/14/2013) */ public final class LookupUtils { private LookupUtils() {throw new AssertionError();} //<editor-fold defaultstate="collapsed" desc="findVirtual"> public static MethodHandle findVirtual(Lookup lookup, Class<?> container, String name, MethodType type) { try { return lookup.findVirtual(container, name, type); } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findVirtual(Lookup lookup, String name, MethodType type) { return findVirtual(lookup, lookup.lookupClass(), name, type); } public static MethodHandle findVirtual(Class<?> container, String name, MethodType type) { return findVirtual(MethodHandles.publicLookup(), container, name, type); } public static MethodHandle findVirtual(Lookup lookup, Class<?> container, String name, Predicate<MethodType> typeFilter) { List<Method> matching = Arrays.stream(container.getDeclaredMethods()) .filter(m -> !Modifier.isStatic(m.getModifiers())) .filter(m -> m.getName().equals(name)) .filter(m -> typeFilter.test(MethodType.methodType(m.getReturnType(), m.getParameterTypes()))) .collect(Collectors.toList()); if (matching.size() != 1) throw new RuntimeException(String.format("%s %s %s %s: %s", lookup, container, name, typeFilter, matching)); Method m = matching.get(0); return findVirtual(lookup, container, name, MethodType.methodType(m.getReturnType(), m.getParameterTypes())); } public static MethodHandle findVirtual(Lookup lookup, String name, Predicate<MethodType> typeFilter) { return findVirtual(lookup, lookup.lookupClass(), name, typeFilter); } public static MethodHandle findVirtual(Class<?> container, String name, Predicate<MethodType> typeFilter) { return findVirtual(MethodHandles.publicLookup(), container, name, typeFilter); } public static MethodHandle findVirtual(Lookup lookup, Class<?> container, String name) { return findVirtual(lookup, container, name, x -> true); } public static MethodHandle findVirtual(Lookup lookup, String name) { return findVirtual(lookup, lookup.lookupClass(), name); } public static MethodHandle findVirtual(Class<?> container, String name) { return findVirtual(MethodHandles.publicLookup(), container, name); } //</editor-fold> //TODO: findSpecial //<editor-fold defaultstate="collapsed" desc="findConstructor"> public static MethodHandle findConstructor(Lookup lookup, Class<?> container, MethodType type) { try { return lookup.findConstructor(container, type); } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findConstructor(Lookup lookup, MethodType type) { return findConstructor(lookup, lookup.lookupClass(), type); } public static MethodHandle findConstructor(Class<?> container, MethodType type) { return findConstructor(MethodHandles.publicLookup(), container, type); } public static MethodHandle findConstructor(Lookup lookup, Class<?> container, Predicate<MethodType> typeFilter) { List<Constructor<?>> matching = Arrays.stream(container.getDeclaredConstructors()) .filter(m -> typeFilter.test(MethodType.methodType(void.class, m.getParameterTypes()))) .collect(Collectors.toList()); if (matching.size() != 1) throw new RuntimeException(String.format("%s %s %s: %s", lookup, container, typeFilter, matching)); Constructor<?> m = matching.get(0); return findConstructor(lookup, container, MethodType.methodType(void.class, m.getParameterTypes())); } public static MethodHandle findConstructor(Lookup lookup, Predicate<MethodType> typeFilter) { return findConstructor(lookup, lookup.lookupClass(), typeFilter); } public static MethodHandle findConstructor(Class<?> container, Predicate<MethodType> typeFilter) { return findConstructor(MethodHandles.publicLookup(), container, typeFilter); } public static MethodHandle findConstructor(Lookup lookup, Class<?> container) { return findConstructor(lookup, container, x -> true); } public static MethodHandle findConstructor(Lookup lookup) { return findConstructor(lookup, lookup.lookupClass()); } public static MethodHandle findConstructor(Class<?> container) { return findConstructor(MethodHandles.publicLookup(), container); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="findStatic"> public static MethodHandle findStatic(Lookup lookup, Class<?> container, String name, MethodType type) { try { return lookup.findStatic(container, name, type); } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findStatic(Lookup lookup, String name, MethodType type) { return findStatic(lookup, lookup.lookupClass(), name, type); } public static MethodHandle findStatic(Class<?> container, String name, MethodType type) { return findStatic(MethodHandles.publicLookup(), container, name, type); } public static MethodHandle findStatic(Lookup lookup, Class<?> container, String name, Predicate<MethodType> typeFilter) { List<Method> matching = Arrays.stream(container.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers())) .filter(m -> m.getName().equals(name)) .filter(m -> typeFilter.test(MethodType.methodType(m.getReturnType(), m.getParameterTypes()))) .collect(Collectors.toList()); if (matching.size() != 1) throw new RuntimeException(String.format("%s %s %s %s: %s", lookup, container, name, typeFilter, matching)); Method m = matching.get(0); return findStatic(lookup, container, name, MethodType.methodType(m.getReturnType(), m.getParameterTypes())); } public static MethodHandle findStatic(Lookup lookup, String name, Predicate<MethodType> typeFilter) { return findStatic(lookup, lookup.lookupClass(), name, typeFilter); } public static MethodHandle findStatic(Class<?> container, String name, Predicate<MethodType> typeFilter) { return findStatic(MethodHandles.publicLookup(), container, name, typeFilter); } public static MethodHandle findStatic(Lookup lookup, Class<?> container, String name) { return findStatic(lookup, container, name, x -> true); } public static MethodHandle findStatic(Lookup lookup, String name) { return findStatic(lookup, lookup.lookupClass(), name); } public static MethodHandle findStatic(Class<?> container, String name) { return findStatic(MethodHandles.publicLookup(), container, name); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="findGetter"> public static MethodHandle findGetter(Lookup lookup, Class<?> container, String name, Class<?> type) { try { return lookup.findGetter(container, name, type); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findGetter(Class<?> container, String name, Class<?> type) { return findGetter(MethodHandles.publicLookup(), container, name, type); } public static MethodHandle findGetter(Lookup lookup, String name, Class<?> type) { return findGetter(lookup, lookup.lookupClass(), name, type); } public static MethodHandle findGetter(Lookup lookup, Class<?> container, String name) { try { return findGetter(lookup, container, name, container.getDeclaredField(name).getType()); } catch (NoSuchFieldException | SecurityException ex) { throw new RuntimeException(ex); } } public static MethodHandle findGetter(Class<?> container, String name) { return findGetter(MethodHandles.publicLookup(), container, name); } public static MethodHandle findGetter(Lookup lookup, String name) { return findGetter(lookup, lookup.lookupClass(), name); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="findSetter"> public static MethodHandle findSetter(Lookup lookup, Class<?> container, String name, Class<?> type) { try { return lookup.findSetter(container, name, type); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findSetter(Class<?> container, String name, Class<?> type) { return findSetter(MethodHandles.publicLookup(), container, name, type); } public static MethodHandle findSetter(Lookup lookup, String name, Class<?> type) { return findSetter(lookup, lookup.lookupClass(), name, type); } public static MethodHandle findSetter(Lookup lookup, Class<?> container, String name) { try { return findSetter(lookup, container, name, container.getDeclaredField(name).getType()); } catch (NoSuchFieldException | SecurityException ex) { throw new RuntimeException(ex); } } public static MethodHandle findSetter(Class<?> container, String name) { return findSetter(MethodHandles.publicLookup(), container, name); } public static MethodHandle findSetter(Lookup lookup, String name) { return findSetter(lookup, lookup.lookupClass(), name); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="findStaticGetter"> public static MethodHandle findStaticGetter(Lookup lookup, Class<?> container, String name, Class<?> type) { try { return lookup.findStaticGetter(container, name, type); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findStaticGetter(Class<?> container, String name, Class<?> type) { return findStaticGetter(MethodHandles.publicLookup(), container, name, type); } public static MethodHandle findStaticGetter(Lookup lookup, String name, Class<?> type) { return findStaticGetter(lookup, lookup.lookupClass(), name, type); } public static MethodHandle findStaticGetter(Lookup lookup, Class<?> container, String name) { try { return findStaticGetter(lookup, container, name, container.getDeclaredField(name).getType()); } catch (NoSuchFieldException | SecurityException ex) { throw new RuntimeException(ex); } } public static MethodHandle findStaticGetter(Class<?> container, String name) { return findStaticGetter(MethodHandles.publicLookup(), container, name); } public static MethodHandle findStaticGetter(Lookup lookup, String name) { return findStaticGetter(lookup, lookup.lookupClass(), name); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="findStaticSetter"> public static MethodHandle findStaticSetter(Lookup lookup, Class<?> container, String name, Class<?> type) { try { return lookup.findStaticSetter(container, name, type); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new RuntimeException(ex); } } public static MethodHandle findStaticSetter(Class<?> container, String name, Class<?> type) { return findStaticSetter(MethodHandles.publicLookup(), container, name, type); } public static MethodHandle findStaticSetter(Lookup lookup, String name, Class<?> type) { return findStaticSetter(lookup, lookup.lookupClass(), name, type); } public static MethodHandle findStaticSetter(Lookup lookup, Class<?> container, String name) { try { return findStaticSetter(lookup, container, name, container.getDeclaredField(name).getType()); } catch (NoSuchFieldException | SecurityException ex) { throw new RuntimeException(ex); } } public static MethodHandle findStaticSetter(Class<?> container, String name) { return findStaticSetter(MethodHandles.publicLookup(), container, name); } public static MethodHandle findStaticSetter(Lookup lookup, String name) { return findStaticSetter(lookup, lookup.lookupClass(), name); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="MethodType predicates"> public static Predicate<MethodType> params(int parameterCount) { return t -> t.parameterCount() == parameterCount; } public static Predicate<MethodType> param(int index, Class<?> type) { return t -> t.parameterCount() >= index && t.parameterType(index).equals(type); } public static Predicate<MethodType> noPrimParam() { return t -> !t.parameterList().stream().anyMatch(Class::isPrimitive); } public static Predicate<MethodType> noRefParam() { return t -> t.parameterList().stream().allMatch(Class::isPrimitive); } //</editor-fold> }
package fr.adrienbrault.idea.symfony2plugin.doctrine; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.psi.elements.*; import com.jetbrains.php.lang.psi.elements.impl.PhpNamedElementImpl; import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil; import fr.adrienbrault.idea.symfony2plugin.doctrine.component.DocumentNamespacesParser; import fr.adrienbrault.idea.symfony2plugin.doctrine.component.EntityNamesServiceParser; import fr.adrienbrault.idea.symfony2plugin.doctrine.dict.DoctrineModelField; import fr.adrienbrault.idea.symfony2plugin.doctrine.dict.DoctrineTypes; import fr.adrienbrault.idea.symfony2plugin.extension.DoctrineModelProvider; import fr.adrienbrault.idea.symfony2plugin.extension.DoctrineModelProviderParameter; import fr.adrienbrault.idea.symfony2plugin.util.*; import fr.adrienbrault.idea.symfony2plugin.util.dict.DoctrineModel; import fr.adrienbrault.idea.symfony2plugin.util.dict.SymfonyBundle; import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory; import fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper; import fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlKeyFinder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.yaml.psi.YAMLDocument; import org.jetbrains.yaml.psi.YAMLFile; import org.jetbrains.yaml.psi.YAMLKeyValue; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class EntityHelper { public static final ExtensionPointName<DoctrineModelProvider> MODEL_POINT_NAME = new ExtensionPointName<DoctrineModelProvider>("fr.adrienbrault.idea.symfony2plugin.extension.DoctrineModelProvider"); final public static String[] ANNOTATION_FIELDS = new String[] { "\\Doctrine\\ORM\\Mapping\\Column", "\\Doctrine\\ORM\\Mapping\\OneToOne", "\\Doctrine\\ORM\\Mapping\\ManyToOne", "\\Doctrine\\ORM\\Mapping\\OneToMany", "\\Doctrine\\ORM\\Mapping\\ManyToMany", }; final public static Set<String> RELATIONS = new HashSet<String>(Arrays.asList("manytoone", "manytomany", "onetoone", "onetomany")); /** * Resolve shortcut and namespaces classes for current phpclass and attached modelname */ public static PhpClass getAnnotationRepositoryClass(PhpClass phpClass, String modelName) { // \ns\Class fine we dont need to resolve classname we are in global context if(modelName.startsWith("\\")) { return PhpElementsUtil.getClassInterface(phpClass.getProject(), modelName); } // repositoryClass="Classname" pre-append namespace here PhpNamedElementImpl phpNamedElementImpl = PsiTreeUtil.getParentOfType(phpClass, PhpNamedElementImpl.class); if(phpNamedElementImpl != null) { String className = phpNamedElementImpl.getFQN() + "\\" + modelName; PhpClass namespaceClass = PhpElementsUtil.getClassInterface(phpClass.getProject(), className); if(namespaceClass != null) { return namespaceClass; } } // repositoryClass="Classname\Test" trailing backslash can be stripped return PhpElementsUtil.getClassInterface(phpClass.getProject(), modelName); } @Nullable public static PhpClass getEntityRepositoryClass(Project project, String shortcutName) { PhpClass phpClass = resolveShortcutName(project, shortcutName); if(phpClass == null) { return null; } // search on annotations PhpDocComment docAnnotation = phpClass.getDocComment(); if(docAnnotation != null) { // search for repositoryClass="Foo\Bar\RegisterRepository" // @MongoDB\Document; @ORM\Entity String docAnnotationText = docAnnotation.getText(); Matcher matcher = Pattern.compile("repositoryClass[\\s]*=[\\s]*[\"|'](.*)[\"|']").matcher(docAnnotationText); if (matcher.find()) { return getAnnotationRepositoryClass(phpClass, matcher.group(1)); } } SymfonyBundle symfonyBundle = new SymfonyBundleUtil(PhpIndex.getInstance(project)).getContainingBundle(phpClass); if(symfonyBundle != null) { String classFqnName = phpClass.getPresentableFQN(); if(classFqnName != null) { PhpClass repositoryClass = getEntityRepositoryClass(project, symfonyBundle, classFqnName); if(repositoryClass != null) { return repositoryClass; } } } // old __CLASS__ Repository type // @TODO remove this fallback when we implemented all cases return resolveShortcutName(project, shortcutName + "Repository"); } private static List<DoctrineModelField> getModelFieldsSet(YAMLKeyValue yamlKeyValue) { List<DoctrineModelField> fields = new ArrayList<DoctrineModelField>(); for(Map.Entry<String, YAMLKeyValue> entry: getYamlModelFieldKeyValues(yamlKeyValue).entrySet()) { List<DoctrineModelField> fieldSet = getYamlDoctrineFields(entry.getKey(), entry.getValue()); if(fieldSet != null) { fields.addAll(fieldSet); } } return fields; } @Nullable public static List<DoctrineModelField> getYamlDoctrineFields(String keyName, @Nullable YAMLKeyValue yamlKeyValue) { if(yamlKeyValue == null) { return null; } PsiElement yamlCompoundValue = yamlKeyValue.getValue(); if(yamlCompoundValue == null) { return null; } List<DoctrineModelField> modelFields = new ArrayList<DoctrineModelField>(); for(YAMLKeyValue yamlKey: PsiTreeUtil.getChildrenOfTypeAsList(yamlCompoundValue, YAMLKeyValue.class)) { String fieldName = YamlHelper.getYamlKeyName(yamlKey); if(fieldName != null) { DoctrineModelField modelField = new DoctrineModelField(fieldName); modelField.addTarget(yamlKey); attachYamlFieldTypeName(keyName, modelField, yamlKey); modelFields.add(modelField); } } return modelFields; } public static void attachYamlFieldTypeName(String keyName, DoctrineModelField doctrineModelField, YAMLKeyValue yamlKeyValue) { if("fields".equals(keyName) || "id".equals(keyName)) { YAMLKeyValue yamlType = YamlHelper.getYamlKeyValue(yamlKeyValue, "type"); if(yamlType != null && yamlType.getValueText() != null) { doctrineModelField.setTypeName(yamlType.getValueText()); } YAMLKeyValue yamlColumn = YamlHelper.getYamlKeyValue(yamlKeyValue, "column"); if(yamlColumn != null) { doctrineModelField.setColumn(yamlColumn.getValueText()); } return; } if(RELATIONS.contains(keyName.toLowerCase())) { YAMLKeyValue targetEntity = YamlHelper.getYamlKeyValue(yamlKeyValue, "targetEntity"); if(targetEntity != null) { doctrineModelField.setRelationType(keyName); String value = targetEntity.getValueText(); if(value != null) { doctrineModelField.setRelation(getYamlOrmClass(yamlKeyValue.getContainingFile(), value)); } } } } private static String getYamlOrmClass(PsiFile yamlFile, String className) { // force global namespace not need to search for class if(className.startsWith("\\")) { return className; } // espend\Doctrine\ModelBundle\Entity\Bike: // targetEntity: Foo YAMLDocument yamlDocument = PsiTreeUtil.getChildOfType(yamlFile, YAMLDocument.class); if(yamlDocument != null) { YAMLKeyValue entityKeyValue = PsiTreeUtil.getChildOfType(yamlDocument, YAMLKeyValue.class); if(entityKeyValue != null) { String entityName = entityKeyValue.getKeyText(); if(entityName != null) { // trim class name int lastBackSlash = entityName.lastIndexOf("\\"); if(lastBackSlash > 0) { String fqnClass = entityName.substring(0, lastBackSlash + 1) + className; if(PhpElementsUtil.getClass(yamlFile.getProject(), fqnClass) != null) { return fqnClass; } } } } } return className; } @NotNull public static Map<String, YAMLKeyValue> getYamlModelFieldKeyValues(YAMLKeyValue yamlKeyValue) { Map<String, YAMLKeyValue> keyValueCollection = new HashMap<String, YAMLKeyValue>(); for(String fieldMap: new String[] { "id", "fields", "manyToOne", "oneToOne", "manyToMany", "oneToMany"}) { YAMLKeyValue targetYamlKeyValue = YamlHelper.getYamlKeyValue(yamlKeyValue, fieldMap, true); if(targetYamlKeyValue != null) { keyValueCollection.put(fieldMap, targetYamlKeyValue); } } return keyValueCollection; } public static PsiElement[] getModelFieldTargets(PhpClass phpClass, String fieldName) { Collection<PsiElement> psiElements = new ArrayList<PsiElement>(); PsiFile psiFile = EntityHelper.getModelConfigFile(phpClass); if(psiFile instanceof YAMLFile) { PsiElement yamlDocument = psiFile.getFirstChild(); if(yamlDocument instanceof YAMLDocument) { PsiElement arrayKeyValue = yamlDocument.getFirstChild(); if(arrayKeyValue instanceof YAMLKeyValue) { for(YAMLKeyValue yamlKeyValue: EntityHelper.getYamlModelFieldKeyValues((YAMLKeyValue) arrayKeyValue).values()) { YAMLKeyValue target = YamlKeyFinder.findKey(yamlKeyValue, fieldName); if(target != null) { psiElements.add(target); } } } } } // provide fallback on annotations // @TODO: better detect annotation switch; yaml and annotation are valid; need deps on annotation plugin PhpDocComment docComment = phpClass.getDocComment(); if(docComment != null) { if(docComment.getText().contains("Entity") || docComment.getText().contains("@ORM") || docComment.getText().contains("repositoryClass")) { for(Field field: phpClass.getFields()) { if(!field.isConstant() && fieldName.equals(field.getName())) { psiElements.add(field); } } } } String methodName = "get" + StringUtils.camelize(fieldName.toLowerCase(), false); Method method = PhpElementsUtil.getClassMethod(phpClass, methodName); if(method != null) { psiElements.add(method); } return psiElements.toArray(new PsiElement[psiElements.size()]); } @Nullable public static PsiFile getModelConfigFile(PhpClass phpClass) { SymfonyBundle symfonyBundle = new SymfonyBundleUtil(phpClass.getProject()).getContainingBundle(phpClass); if(symfonyBundle != null) { for(String modelShortcut: new String[] {"orm", "mongodb"}) { String fqn = phpClass.getPresentableFQN(); String className = phpClass.getName(); if(fqn != null) { int n = fqn.indexOf("\\Entity\\"); if(n > 0) { className = fqn.substring(n + 8).replace("\\", "."); } } String entityFile = "Resources/config/doctrine/" + className + String.format(".%s.yml", modelShortcut); VirtualFile virtualFile = symfonyBundle.getRelative(entityFile); if(virtualFile != null) { PsiFile psiFile = PsiManager.getInstance(phpClass.getProject()).findFile(virtualFile); if(psiFile != null) { return psiFile; } } } } return null; } public static List<DoctrineModelField> getModelFields(PhpClass phpClass) { List<DoctrineModelField> modelFields = new ArrayList<DoctrineModelField>(); PsiFile psiFile = getModelConfigFile(phpClass); if(psiFile instanceof YAMLFile) { PsiElement yamlDocument = psiFile.getFirstChild(); if(yamlDocument instanceof YAMLDocument) { PsiElement arrayKeyValue = yamlDocument.getFirstChild(); if(arrayKeyValue instanceof YAMLKeyValue) { // first line is class name; check of we are right String className = YamlHelper.getYamlKeyName(((YAMLKeyValue) arrayKeyValue)); if(PhpElementsUtil.isEqualClassName(phpClass, className)) { modelFields.addAll(getModelFieldsSet((YAMLKeyValue) arrayKeyValue)); } } } return modelFields; } // provide fallback on annotations PhpDocComment docComment = phpClass.getDocComment(); if(docComment != null) { if(AnnotationBackportUtil.hasReference(docComment, "\\Doctrine\\ORM\\Mapping\\Entity")) { for(Field field: phpClass.getFields()) { if(!field.isConstant()) { if(AnnotationBackportUtil.hasReference(field.getDocComment(), ANNOTATION_FIELDS)) { DoctrineModelField modelField = new DoctrineModelField(field.getName()); attachAnnotationInformation(field, modelField.addTarget(field)); modelFields.add(modelField); } } } } } return modelFields; } @Nullable private static PhpClass getEntityRepositoryClass(Project project, SymfonyBundle symfonyBundle, String classFqnName) { // some default bundle search path // Bundle/Resources/config/doctrine/Product.orm.yml // Bundle/Resources/config/doctrine/Product.mongodb.yml List<String[]> managerConfigs = new ArrayList<String[]>(); managerConfigs.add(new String[] { "Entity", "orm"}); managerConfigs.add(new String[] { "Document", "mongodb"}); for(String[] managerConfig: managerConfigs) { String entityName = classFqnName.substring(symfonyBundle.getNamespaceName().length() - 1); if(entityName.startsWith(managerConfig[0] + "\\")) { entityName = entityName.substring((managerConfig[0] + "\\").length()); } // entities in sub folder: 'Foo\Bar' -> 'Foo.Bar.orm.yml' String entityFile = "Resources/config/doctrine/" + entityName.replace("\\", ".") + String.format(".%s.yml", managerConfig[1]); VirtualFile virtualFile = symfonyBundle.getRelative(entityFile); if(virtualFile != null) { PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if(psiFile != null) { // search for "repositoryClass: Foo\Bar\RegisterRepository" also provide quoted values Matcher matcher = Pattern.compile("[\\s]*repositoryClass:[\\s]*[\"|']*(.*)[\"|']*").matcher(psiFile.getText()); if (matcher.find()) { return PhpElementsUtil.getClass(PhpIndex.getInstance(project), matcher.group(1)); } // we found entity config so no other check needed return null; } } } return null; } @Nullable public static PhpClass resolveShortcutName(Project project, String shortcutName) { return resolveShortcutName(project, shortcutName, DoctrineTypes.Manager.ORM, DoctrineTypes.Manager.MONGO_DB); } /** * * @param project PHPStorm projects * @param shortcutName name as MyBundle\Entity\Model or MyBundle:Model * @return null|PhpClass */ @Nullable public static PhpClass resolveShortcutName(Project project, String shortcutName, DoctrineTypes.Manager... managers) { List<DoctrineTypes.Manager> managerList = Arrays.asList(managers); if(shortcutName == null) { return null; } String entity_name = shortcutName; // resolve: // MyBundle:Model -> MyBundle\Entity\Model // MyBundle:Folder\Model -> MyBundle\Entity\Folder\Model if (shortcutName.contains(":")) { Map<String, String> em = new HashMap<String, String>(); if(managerList.contains(DoctrineTypes.Manager.ORM)) { em.putAll(ServiceXmlParserFactory.getInstance(project, EntityNamesServiceParser.class).getEntityNameMap()); } if(managerList.contains(DoctrineTypes.Manager.MONGO_DB)) { em.putAll(ServiceXmlParserFactory.getInstance(project, DocumentNamespacesParser.class).getNamespaceMap()); } int firstDirectorySeparatorIndex = shortcutName.indexOf(":"); String bundlename = shortcutName.substring(0, firstDirectorySeparatorIndex); String entityName = shortcutName.substring(firstDirectorySeparatorIndex + 1); String namespace = em.get(bundlename); if(namespace == null) { return null; } entity_name = namespace + "\\" + entityName; } // only use them on entity namespace if(!entity_name.contains("\\")) { return null; } // dont we have any unique class getting method here? PhpIndex phpIndex = PhpIndex.getInstance(project); Collection<PhpClass> entity_classes = phpIndex.getClassesByFQN(entity_name); if(!entity_classes.isEmpty()){ return entity_classes.iterator().next(); } return null; } @Nullable public static DoctrineTypes.Manager getManager(MethodReference methodReference) { PhpPsiElement phpTypedElement = methodReference.getFirstPsiChild(); if(!(phpTypedElement instanceof PhpTypedElement)) { return null; } Symfony2InterfacesUtil symfony2InterfacesUtil = new Symfony2InterfacesUtil(); for(String typeString: PhpIndex.getInstance(methodReference.getProject()).completeType(methodReference.getProject(), ((PhpTypedElement) phpTypedElement).getType(), new HashSet<String>()).getTypes()) { for(Map.Entry<DoctrineTypes.Manager, String> entry: DoctrineTypes.getManagerInstanceMap().entrySet()) { if(symfony2InterfacesUtil.isInstanceOf(methodReference.getProject(), typeString, entry.getValue())) { return entry.getKey(); } } } return null; } public static PsiElement[] getModelPsiTargets(Project project, @NotNull String entityName) { List<PsiElement> results = new ArrayList<PsiElement>(); PhpClass phpClass = EntityHelper.getEntityRepositoryClass(project, entityName); if(phpClass != null) { results.add(phpClass); } // search any php model file PhpClass entity = EntityHelper.resolveShortcutName(project, entityName); if(entity != null) { results.add(entity); // find model config eg ClassName.orm.yml PsiFile psiFile = EntityHelper.getModelConfigFile(entity); if(psiFile != null) { results.add(psiFile); } } return results.toArray(new PsiElement[results.size()]); } public static void attachAnnotationInformation(Field field, DoctrineModelField doctrineModelField) { // we already have that without regular expression // @TODO: de.espend.idea.php.annotation.util.AnnotationUtil.getPhpDocCommentAnnotationContainer() // fully require plugin now? // get some more presentable completion information // dont resolve docblocks; just extract them from doc comment PhpDocComment docBlock = field.getDocComment(); if(docBlock == null) { return; } String text = docBlock.getText(); // column type Matcher matcher = Pattern.compile("type[\\s]*=[\\s]*[\"|']([\\w_\\\\]+)[\"|']").matcher(text); if (matcher.find()) { doctrineModelField.setTypeName(matcher.group(1)); } // targetEntity name matcher = Pattern.compile("targetEntity[\\s]*=[\\s]*[\"|']([\\w_\\\\]+)[\"|']").matcher(text); if (matcher.find()) { doctrineModelField.setRelation(matcher.group(1)); } // relation type matcher = Pattern.compile("((Many|One)To(Many|One))\\(").matcher(text); if (matcher.find()) { doctrineModelField.setRelationType(matcher.group(1)); } matcher = Pattern.compile("Column\\(").matcher(text); if (matcher.find()) { matcher = Pattern.compile("name\\s*=\\s*\"(\\w+)\"").matcher(text); if(matcher.find()) { doctrineModelField.setColumn(matcher.group(1)); } } } public static Collection<DoctrineModel> getModelClasses(final Project project) { Collection<DoctrineModel> doctrineModels = getModelClasses(project, new HashMap<String, String>() {{ putAll(ServiceXmlParserFactory.getInstance(project, EntityNamesServiceParser.class).getEntityNameMap()); putAll(ServiceXmlParserFactory.getInstance(project, DocumentNamespacesParser.class).getNamespaceMap()); }}); DoctrineModelProviderParameter containerLoaderExtensionParameter = new DoctrineModelProviderParameter(project, new ArrayList<DoctrineModelProviderParameter.DoctrineModel>()); for(DoctrineModelProvider provider : EntityHelper.MODEL_POINT_NAME.getExtensions()) { for(DoctrineModelProviderParameter.DoctrineModel doctrineModel: provider.collectModels(containerLoaderExtensionParameter)) { doctrineModels.add(new DoctrineModel(doctrineModel.getPhpClass(), doctrineModel.getName())); } } return doctrineModels; } public static Collection<DoctrineModel> getModelClasses(Project project, Map<String, String> shortcutNames) { Collection<DoctrineModel> models = new ArrayList<DoctrineModel>(); PhpClass repositoryInterface = PhpElementsUtil.getInterface(PhpIndex.getInstance(project), DoctrineTypes.REPOSITORY_INTERFACE); if(null == repositoryInterface) { return models; } for (Map.Entry<String, String> entry : shortcutNames.entrySet()) { Collection<PhpClass> phpClasses = PhpIndexUtil.getPhpClassInsideNamespace(repositoryInterface.getProject(), entry.getValue()); for(PhpClass phpClass: phpClasses) { if(isEntity(phpClass, repositoryInterface)) { models.add(new DoctrineModel(phpClass, entry.getKey(), entry.getValue())); } } } return models; } public static boolean isEntity(PhpClass entityClass, PhpClass repositoryClass) { if(entityClass.isAbstract()) { return false; } Symfony2InterfacesUtil symfony2Util = new Symfony2InterfacesUtil(); return !symfony2Util.isInstanceOf(entityClass, repositoryClass); } }