answer
stringlengths
17
10.2M
package org.codespartans.telegram.bot; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.fluent.Request; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.message.BasicNameValuePair; import org.codespartans.telegram.bot.models.*; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.*; /** * Implementation of Telegrams bot API. * * @author Ralph Broers */ public class TelegramBot { private static final ObjectMapper mapper = new ObjectMapper() .registerModule(new Jdk8Module()) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY); private static final String HOST = "api.telegram.org"; private static final String SCHEME = "https"; private final URI ApiUri; private TelegramBot(String token) throws URISyntaxException { this.ApiUri = new URIBuilder() .setScheme(SCHEME) .setHost(HOST) .setPath(String.format("/bot%s/", token)) .setCharset(StandardCharsets.UTF_8) .build(); } public static TelegramBot getInstance(String token) { token = Optional.ofNullable(token) .orElseThrow(() -> new NullPointerException("Token can't be null.")); try { return new TelegramBot(token); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public User getMe() throws IOException { return Request.Get(ApiUri.resolve("getMe")) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<User>>() { })); } public Message sendMessage(int chat_id, String text) throws IOException { return sendMessage(chat_id, text, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); } public Message sendMessage(int chat_id, String text, Optional<String> parse_mode, Optional<Boolean> disable_web_page_preview, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (text == null || disable_web_page_preview == null || reply_to_message_id == null || reply_markup == null) throw new NullPointerException("No null params allowed in sendMessage."); if (chat_id == 0) throw new IllegalArgumentException("Parameter chat_id shouldn't be zero."); final List<BasicNameValuePair> fields = new ArrayList<>(2); fields.add(new BasicNameValuePair("text", text)); parse_mode.map(parseMode -> fields.add(new BasicNameValuePair("parse_mode", parseMode))); disable_web_page_preview.map(preview -> fields.add(new BasicNameValuePair("disable_web_page_preview", preview.toString()))); return sendMessage("sendMessage", chat_id, fields, reply_to_message_id, reply_markup); } public List<Update> getUpdates(int offset, int limit, int timeout) throws IOException { if (limit == 0 || timeout == 0) throw new IllegalArgumentException("Parameters limit and timeout shouldn't be zero."); final List<NameValuePair> nvps = new ArrayList<>(3); nvps.add(new BasicNameValuePair("offset", String.valueOf(offset))); nvps.add(new BasicNameValuePair("limit", String.valueOf(limit))); nvps.add(new BasicNameValuePair("timeout", String.valueOf(timeout))); return getUpdates(nvps); } public List<Update> getUpdates(int offset, int limit) throws IOException { if (limit == 0) throw new IllegalArgumentException("Parameter limit shouldn't be zero."); final List<NameValuePair> nvps = new ArrayList<>(2); nvps.add(new BasicNameValuePair("offset", String.valueOf(offset))); nvps.add(new BasicNameValuePair("limit", String.valueOf(limit))); return getUpdates(nvps); } public List<Update> getUpdates(int timeout) throws IOException { if (timeout == 0) throw new IllegalArgumentException("Parameter timeout shouldn't be zero."); return getUpdates(Arrays.asList(new BasicNameValuePair("timeout", String.valueOf(timeout)))); } public List<Update> getUpdates() throws IOException { return getUpdates(Collections.emptyList()); } public void setWebHook(String url) throws IOException { url = Optional.ofNullable(url).orElseThrow(() -> new NullPointerException("Url can't be null.")); final StatusLine statusLine = Request.Post(ApiUri.resolve("setWebHook")) .bodyForm(Arrays.asList(new BasicNameValuePair("url", url)), StandardCharsets.UTF_8) .execute() .returnResponse() .getStatusLine(); if (statusLine.getStatusCode() != 200) throw new HttpResponseException(statusLine.hashCode(), statusLine.getReasonPhrase()); } public Message forwardMessage(int chat_id, int from_chat_id, int message_id) throws IOException { if (chat_id == 0 || from_chat_id == 0 || message_id == 0) throw new IllegalArgumentException("Parameters shouldn't be zero."); final List<NameValuePair> params = new ArrayList<>(3); params.add(new BasicNameValuePair("chat_id", String.valueOf(chat_id))); params.add(new BasicNameValuePair("from_chat_id", String.valueOf(from_chat_id))); params.add(new BasicNameValuePair("message_id", String.valueOf(message_id))); return Request.Post(ApiUri.resolve("forwardMessage")) .bodyForm(params, StandardCharsets.UTF_8) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<Message>>() { })); } public Message sendPhoto(int chat_id, File photo, Optional<String> caption, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (caption == null) throw new NullPointerException("Parameter caption cannot be null."); final List<BasicNameValuePair> extraFields = caption .map(cptn -> Arrays.asList(new BasicNameValuePair("caption", cptn))) .orElseGet(Collections::emptyList); return sendMedia("sendPhoto", chat_id, photo, reply_to_message_id, reply_markup, extraFields); } public Message sendPhoto(int chat_id, String photo, Optional<String> caption, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (caption == null) throw new NullPointerException("Parameter caption cannot be null."); final List<BasicNameValuePair> fields = new ArrayList<>(2); fields.add(new BasicNameValuePair("photo", photo)); caption.map(cptn -> fields.add(new BasicNameValuePair("caption", cptn))); return sendMessage("sendPhoto", chat_id, fields, reply_to_message_id, reply_markup); } public Message sendPhoto(int chat_id, File photo) throws IOException { return sendPhoto(chat_id, photo, Optional.empty(), Optional.empty(), Optional.empty()); } public Message sendPhoto(int chat_id, String photo) throws IOException { return sendPhoto(chat_id, photo, Optional.empty(), Optional.empty(), Optional.empty()); } public Message sendAudio(int chat_id, String audio, Optional<Integer> duration, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (duration == null) throw new NullPointerException("Parameter duration cannot be null."); final List<BasicNameValuePair> fields = new ArrayList<>(2); fields.add(new BasicNameValuePair("audio", audio)); duration.map(drtn -> fields.add(new BasicNameValuePair("duration", String.valueOf(drtn)))); return sendMessage("sendAudio", chat_id, fields, reply_to_message_id, reply_markup); } public Message sendAudio(int chat_id, String audio) throws IOException { return sendMessage("sendAudio", chat_id, Arrays.asList(new BasicNameValuePair("audio", audio))); } public Message sendAudio(int chat_id, File audio, Optional<Integer> duration, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (duration == null) throw new NullPointerException("Parameter duration cannot be null."); final List<BasicNameValuePair> extraFields = duration .map(drtn -> Arrays.asList(new BasicNameValuePair("duration", String.valueOf(drtn)))) .orElseGet(Collections::emptyList); return sendMedia("sendAudio", chat_id, audio, reply_to_message_id, reply_markup, extraFields); } public Message sendDocument(int chat_id, String document, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { return sendMessage("sendDocument", chat_id, Arrays.asList(new BasicNameValuePair("document", document)), reply_to_message_id, reply_markup); } public Message sendDocument(int chat_id, String document) throws IOException { return sendMessage("sendDocument", chat_id, Arrays.asList(new BasicNameValuePair("document", document))); } public Message sendDocument(int chat_id, File document, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { return sendMedia("sendDocument", chat_id, document, reply_to_message_id, reply_markup, Collections.emptyList()); } public Message sendDocument(int chat_id, File document) throws IOException { return sendMedia("sendDocument", chat_id, document); } public Message sendSticker(int chat_id, File sticker, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { return sendMedia("sendSticker", chat_id, sticker, reply_to_message_id, reply_markup, Collections.emptyList()); } public Message sendSticker(int chat_id, File sticker) throws IOException { return sendMedia("sendSticker", chat_id, sticker); } public Message sendSticker(int chat_id, String sticker, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { return sendMessage("sendSticker", chat_id, Arrays.asList(new BasicNameValuePair("sticker", sticker)), reply_to_message_id, reply_markup); } public Message sendSticker(int chat_id, String sticker) throws IOException { return sendMessage("sendSticker", chat_id, Arrays.asList(new BasicNameValuePair("sticker", sticker))); } public Message sendLocation(int chat_id, float latitude, float longitude, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (latitude == 0 || longitude == 0) throw new IllegalArgumentException("Latitude or longitude cannot be zero."); final List<BasicNameValuePair> fields = Arrays.asList( new BasicNameValuePair("latitude", String.valueOf(latitude)), new BasicNameValuePair("longitude", String.valueOf(longitude))); return sendMessage("sendLocation", chat_id, fields, reply_to_message_id, reply_markup); } public Message sendLocation(int chat_id, float latitude, float longitude) throws IOException { if (latitude == 0 || longitude == 0) throw new IllegalArgumentException("Latitude or longitude cannot be zero."); final List<BasicNameValuePair> fields = Arrays.asList( new BasicNameValuePair("latitude", String.valueOf(latitude)), new BasicNameValuePair("longitude", String.valueOf(longitude))); return sendMessage("sendLocation", chat_id, fields); } public void sendChatAction(int chat_id, Action action) throws IOException { if (chat_id == 0) throw new IllegalArgumentException("Parameter chat_id can't be zero."); final List<NameValuePair> params = Arrays.asList( new BasicNameValuePair("chat_id", String.valueOf(chat_id)), new BasicNameValuePair("action", action.toString().toLowerCase())); Request.Post(ApiUri.resolve("sendChatAction")) .bodyForm(params, StandardCharsets.UTF_8) .execute(); } public org.codespartans.telegram.bot.models.File getFile(String file_id) throws IOException { if (file_id == null) throw new IllegalArgumentException("Parameter file_id can't be null."); final List<NameValuePair> params = Arrays.asList(new BasicNameValuePair("file_id", file_id)); return Request.Post(ApiUri.resolve("getFile")) .bodyForm(params, StandardCharsets.UTF_8) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<org.codespartans.telegram.bot.models.File>>() { })); } public UserProfilePhotos getUserProfilePhotos(int user_id) throws IOException { return getUserProfilePhotos(user_id, Optional.empty(), Optional.empty()); } public UserProfilePhotos getUserProfilePhotos(int user_id, Optional<Integer> offset, Optional<Integer> limit) throws IOException { final URI uri; final List<NameValuePair> nvps = new ArrayList<>(3); nvps.add(new BasicNameValuePair("user_id", String.valueOf(user_id))); offset.ifPresent(off -> nvps.add(new BasicNameValuePair("offset", String.valueOf(off)))); limit.ifPresent(lim -> nvps.add(new BasicNameValuePair("limit", String.valueOf(lim)))); try { uri = new URIBuilder(ApiUri.resolve("getUserProfilePhotos")).addParameters(nvps).build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } return Request.Get(uri) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<UserProfilePhotos>>() { })); } private Message sendMedia(String method, int chat_id, File media) throws IOException { return sendMedia(method, chat_id, media, Optional.empty(), Optional.empty(), Collections.emptyList()); } private Message sendMedia(String method, int chat_id, File media, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup, List<BasicNameValuePair> extraFields) throws IOException { String mediaFieldName = method.toLowerCase().replace("send", ""); if (chat_id == 0) throw new IllegalArgumentException("Parameter chat_id can't be zero."); if (media == null || reply_to_message_id == null || reply_markup == null) throw new NullPointerException("Parameters of method " + method + " cannot be null."); if (!media.isFile() && media.exists()) throw new IllegalArgumentException("Parameter " + mediaFieldName + " must be an existing file."); final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setLaxMode() .setContentType(TelegramContentType.MULTIPART_FORM_DATA).setCharset(StandardCharsets.UTF_8) .addTextBody("chat_id", String.valueOf(chat_id), TelegramContentType.PAIN_TEXT) .addBinaryBody(mediaFieldName, media, TelegramContentType.MULTIPART_FORM_DATA, media.getName()); reply_to_message_id.ifPresent(id -> entityBuilder.addTextBody("reply_to_message_id", id.toString())); reply_markup.ifPresent(reply -> { try { entityBuilder.addTextBody("reply_markup", mapper.writeValueAsString(reply)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }); extraFields.stream().forEach(field -> entityBuilder.addTextBody(field.getName(), field.getValue())); return Request.Post(ApiUri.resolve(method)) .body(entityBuilder.build()) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<Message>>() { })); } private Message sendMessage(String method, int chat_id, List<BasicNameValuePair> fields) throws IOException { return sendMessage(method, chat_id, fields, Optional.empty(), Optional.empty()); } private Message sendMessage(String method, int chat_id, List<BasicNameValuePair> fields, Optional<Integer> reply_to_message_id, Optional<Reply> reply_markup) throws IOException { if (chat_id == 0) throw new IllegalArgumentException("Parameter chat_id can't be zero."); if (reply_to_message_id == null || reply_markup == null) throw new NullPointerException("Parameters of method " + method + " cannot be null."); final List<NameValuePair> params = new ArrayList<>(3 + fields.size()); params.add(new BasicNameValuePair("chat_id", String.valueOf(chat_id))); params.addAll(fields); reply_to_message_id.ifPresent(id -> params.add(new BasicNameValuePair("reply_to_message_id", id.toString()))); reply_markup.ifPresent(reply -> { try { params.add(new BasicNameValuePair("reply_markup", mapper.writeValueAsString(reply))); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }); return Request.Post(ApiUri.resolve(method)) .bodyForm(params, StandardCharsets.UTF_8) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<Message>>() { })); } private List<Update> getUpdates(List<NameValuePair> nvps) throws IOException { final URI uri; try { uri = new URIBuilder(ApiUri.resolve("getUpdates")).addParameters(nvps).build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } return Request.Get(uri) .execute() .handleResponse(getResponseHandler(new TypeReference<Response<List<Update>>>() { })); } private <T> ResponseHandler<T> getResponseHandler(TypeReference<Response<T>> reference) { return (HttpResponse response) -> { int code = response.getStatusLine().getStatusCode(); if (code == 404) throw new HttpResponseException(404, "Telegram bot API out of date."); if (code == 200) { Response<T> entityResponse = mapper.readValue(response.getEntity().getContent(), reference); if (entityResponse.isOk() && entityResponse.getResult() != null) return entityResponse.getResult(); throw new NullPointerException(); } throw new HttpResponseException(code, response.getStatusLine().getReasonPhrase()); }; } }
package org.xwiki.extension.xar.internal.handler.internal.repository; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.xwiki.extension.ExtensionId; import org.xwiki.extension.ResolveException; import org.xwiki.extension.repository.InstalledExtensionRepository; import org.xwiki.extension.test.MockitoRepositoryUtilsRule; import org.xwiki.extension.xar.internal.repository.XarInstalledExtensionRepository; import org.xwiki.test.annotation.AllComponents; import org.xwiki.test.mockito.MockitoComponentManagerRule; @AllComponents public class XarInstalledExtensionRepositoryTest { protected MockitoComponentManagerRule mocker = new MockitoComponentManagerRule(); @Rule public MockitoRepositoryUtilsRule repositoryUtil = new MockitoRepositoryUtilsRule(this.mocker); private XarInstalledExtensionRepository installedExtensionRepository; @Before public void setUp() throws Exception { this.installedExtensionRepository = this.mocker.getInstance(InstalledExtensionRepository.class, "xar"); } // Tests @Test public void testInit() throws ResolveException { Assert.assertTrue(this.installedExtensionRepository.countExtensions() == 1); Assert.assertNotNull(this.installedExtensionRepository.getInstalledExtension(new ExtensionId( "xarinstalledextension", "1.0"))); Assert .assertNotNull(this.installedExtensionRepository.resolve(new ExtensionId("xarinstalledextension", "1.0"))); } }
package org.jitsi.impl.neomedia; import org.jitsi.impl.neomedia.device.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; /** * Implementation of VolumeControl which uses system sound architecture (MacOsX * or Windows CoreAudio) to change input/output hardware volume. * * @author Vincent Lucas */ public class HardwareVolumeControl extends BasicVolumeControl { /** * The <tt>Logger</tt> used by the <tt>HarwareVolumeControl</tt> * class and its instances for logging output. */ private static final Logger logger = Logger.getLogger(HardwareVolumeControl.class); /** * The media service implementation. */ MediaServiceImpl mediaServiceImpl = null; /** * The maximal power level used for hardware amplification. Over this value * software amplification is used. */ private static final float MAX_HARDWARE_POWER = 1.0F; /** * Creates volume control instance and initializes initial level value * if stored in the configuration service. * * @param mediaServiceImpl The media service implementation. * @param volumeLevelConfigurationPropertyName the name of the configuration * property which specifies the value of the volume level of the new * instance */ public HardwareVolumeControl( MediaServiceImpl mediaServiceImpl, String volumeLevelConfigurationPropertyName) { super(volumeLevelConfigurationPropertyName); this.mediaServiceImpl = mediaServiceImpl; // Gets the device volume (an error use the default volume). this.volumeLevel = getDefaultVolumeLevel(); float volume = this.getVolume(); if(volume != -1) { this.volumeLevel = volume; } } /** * Returns the default volume level. * * @return The default volume level. */ protected static float getDefaultVolumeLevel() { // By default set the microphone at the middle of its hardware // sensibility range. return MAX_HARDWARE_POWER / 2; } /** * Returns the reference volume level for computing the gain. * * @return The reference volume level for computing the gain. */ protected static float getGainReferenceLevel() { // Starts to activate the gain (software amplification), only once the // microphone sensibility is sets to its maximum (hardware // amplification). return MAX_HARDWARE_POWER; } /** * Modifies the hardware microphone sensibility (hardware amplification). */ @Override protected void updateHardwareVolume() { // Gets the selected input dvice UID. String deviceUID = getCaptureDeviceUID(); // Computes the hardware volume. float jitsiHarwareVolumeFactor = MAX_VOLUME_LEVEL / MAX_HARDWARE_POWER; float hardwareVolumeLevel = this.volumeLevel * jitsiHarwareVolumeFactor; if(hardwareVolumeLevel > 1.0F) { hardwareVolumeLevel = 1.0F; } // Changes the input volume of the capture device. if(this.setInputDeviceVolume( deviceUID, hardwareVolumeLevel) != 0) { logger.debug("Could not change hardware input device level"); } } /** * Returns the selected input device UID. * * @return The selected input device UID. Or null if not found. */ protected String getCaptureDeviceUID() { AudioSystem audioSystem = mediaServiceImpl.getDeviceConfiguration().getAudioSystem(); CaptureDeviceInfo2 captureDevice = (audioSystem == null) ? null : audioSystem.getSelectedDevice(AudioSystem.DataFlow.CAPTURE); return (captureDevice == null) ? null : captureDevice.getUID(); } /** * Changes the device volume via the system API. * * @param deviceUID The device ID. * @param volume The volume requested. * * @return 0 if everything works fine. */ protected int setInputDeviceVolume(String deviceUID, float volume) { if(deviceUID == null) { return -1; } if(CoreAudioDevice.initDevices() == -1) { CoreAudioDevice.freeDevices(); logger.debug( "Could not initialize CoreAudio input devices"); return -1; } // Change the input volume of the capture device. if(CoreAudioDevice.setInputDeviceVolume(deviceUID, volume) != 0) { CoreAudioDevice.freeDevices(); logger.debug( "Could not change CoreAudio input device level"); return -1; } CoreAudioDevice.freeDevices(); return 0; } /** * Returns the device volume via the system API. * * @param deviceUID The device ID. * * @Return A scalar value between 0 and 1 if everything works fine. -1 if an * error occurred. */ protected float getInputDeviceVolume(String deviceUID) { float volume; if(deviceUID == null) { return -1; } if(CoreAudioDevice.initDevices() == -1) { CoreAudioDevice.freeDevices(); logger.debug( "Could not initialize CoreAudio input devices"); return -1; } // Get the input volume of the capture device. if((volume = CoreAudioDevice.getInputDeviceVolume(deviceUID)) == -1) { CoreAudioDevice.freeDevices(); logger.debug( "Could not get CoreAudio input device level"); return -1; } CoreAudioDevice.freeDevices(); return volume; } /** * Current volume value. * * @return the current volume level. * * @see org.jitsi.service.neomedia.VolumeControl */ @Override public float getVolume() { String deviceUID = getCaptureDeviceUID(); float volume = this.getInputDeviceVolume(deviceUID); // If the hardware voume for this device is not available, then switch // to the software volume. if(volume == -1) { volume = super.getVolume(); } return volume; } }
package org.joval.plugin.adapter.unix; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.xml.bind.JAXBElement; import oval.schemas.common.MessageType; import oval.schemas.common.MessageLevelEnumeration; import oval.schemas.common.OperationEnumeration; import oval.schemas.common.SimpleDatatypeEnumeration; import oval.schemas.definitions.core.EntityObjectStringType; import oval.schemas.definitions.core.ObjectType; import oval.schemas.definitions.unix.PasswordObject; import oval.schemas.systemcharacteristics.core.ItemType; import oval.schemas.systemcharacteristics.core.EntityItemIntType; import oval.schemas.systemcharacteristics.core.EntityItemStringType; import oval.schemas.systemcharacteristics.core.FlagEnumeration; import oval.schemas.systemcharacteristics.core.StatusEnumeration; import oval.schemas.systemcharacteristics.unix.PasswordItem; import oval.schemas.results.core.ResultEnumeration; import org.joval.intf.plugin.IAdapter; import org.joval.intf.plugin.IRequestContext; import org.joval.intf.unix.system.IUnixSession; import org.joval.oval.CollectException; import org.joval.oval.OvalException; import org.joval.oval.ResolveException; import org.joval.util.JOVALMsg; import org.joval.util.JOVALSystem; import org.joval.util.SafeCLI; import org.joval.util.StringTools; /** * Collects items for unix:password_objects. * * @author David A. Solin * @version %I% %G% */ public class PasswordAdapter implements IAdapter { private IUnixSession session; private Hashtable<String, PasswordItem> passwordMap; private String error; private boolean initialized; public PasswordAdapter(IUnixSession session) { this.session = session; passwordMap = new Hashtable<String, PasswordItem>(); error = null; initialized = false; } // Implement IAdapter private static Class[] objectClasses = {PasswordObject.class}; public Class[] getObjectClasses() { return objectClasses; } public Collection<JAXBElement<? extends ItemType>> getItems(IRequestContext rc) throws OvalException, CollectException { if (!initialized) { loadPasswords(); } if (error != null) { MessageType msg = JOVALSystem.factories.common.createMessageType(); msg.setLevel(MessageLevelEnumeration.ERROR); msg.setValue(error); rc.addMessage(msg); } Collection<JAXBElement<? extends ItemType>> items = new Vector<JAXBElement<? extends ItemType>>(); PasswordObject pObj = (PasswordObject)rc.getObject(); EntityObjectStringType usernameType = pObj.getUsername(); try { List<String> usernames = new Vector<String>(); if (usernameType.isSetVarRef()) { usernames.addAll(rc.resolve(usernameType.getVarRef())); } else { usernames.add((String)usernameType.getValue()); } for (String username : usernames) { OperationEnumeration op = usernameType.getOperation(); switch(op) { case EQUALS: if (passwordMap.containsKey(username)) { items.add(JOVALSystem.factories.sc.unix.createPasswordItem(passwordMap.get(username))); } break; case NOT_EQUAL: for (String s : passwordMap.keySet()) { if (!s.equals(username)) { items.add(JOVALSystem.factories.sc.unix.createPasswordItem(passwordMap.get(s))); } } break; case PATTERN_MATCH: { Pattern p = Pattern.compile(username); for (String s : passwordMap.keySet()) { if (p.matcher(s).find()) { items.add(JOVALSystem.factories.sc.unix.createPasswordItem(passwordMap.get(s))); } } break; } default: String msg = JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op); throw new CollectException(msg, FlagEnumeration.NOT_COLLECTED); } } } catch (ResolveException e) { throw new OvalException(e); } catch (PatternSyntaxException e) { MessageType msg = JOVALSystem.factories.common.createMessageType(); msg.setLevel(MessageLevelEnumeration.ERROR); msg.setValue(JOVALSystem.getMessage(JOVALMsg.ERROR_PATTERN, e.getMessage())); rc.addMessage(msg); session.getLogger().warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } return items; } // Internal private void loadPasswords() { try { for (String line : SafeCLI.multiLine("cat /etc/passwd", session, IUnixSession.Timeout.S)) { if (line.startsWith(" continue; } List<String> tokens = StringTools.toList(StringTools.tokenize(line, ":", false)); if (tokens.size() == 7) { int i=0; PasswordItem item = JOVALSystem.factories.sc.unix.createPasswordItem(); EntityItemStringType username = JOVALSystem.factories.sc.core.createEntityItemStringType(); String usernameString = tokens.get(i++); username.setValue(usernameString); item.setUsername(username); EntityItemStringType password = JOVALSystem.factories.sc.core.createEntityItemStringType(); i++; password.setStatus(StatusEnumeration.NOT_COLLECTED); item.setPassword(password); EntityItemIntType userId = JOVALSystem.factories.sc.core.createEntityItemIntType(); userId.setValue(tokens.get(i++)); userId.setDatatype(SimpleDatatypeEnumeration.INT.value()); item.setUserId(userId); EntityItemIntType groupId = JOVALSystem.factories.sc.core.createEntityItemIntType(); groupId.setValue(tokens.get(i++)); groupId.setDatatype(SimpleDatatypeEnumeration.INT.value()); item.setGroupId(groupId); EntityItemStringType gcos = JOVALSystem.factories.sc.core.createEntityItemStringType(); gcos.setValue(tokens.get(i++)); item.setGcos(gcos); EntityItemStringType homeDir = JOVALSystem.factories.sc.core.createEntityItemStringType(); homeDir.setValue(tokens.get(i++)); item.setHomeDir(homeDir); EntityItemStringType loginShell = JOVALSystem.factories.sc.core.createEntityItemStringType(); loginShell.setValue(tokens.get(i++)); item.setLoginShell(loginShell); EntityItemIntType lastLogin = JOVALSystem.factories.sc.core.createEntityItemIntType(); lastLogin.setStatus(StatusEnumeration.NOT_COLLECTED); lastLogin.setDatatype(SimpleDatatypeEnumeration.INT.value()); item.setLastLogin(lastLogin); passwordMap.put(usernameString, item); } else { session.getLogger().warn(JOVALMsg.ERROR_PASSWD_LINE, line); } } } catch (Exception e) { error = e.getMessage(); session.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } initialized = true; } }
package org.essencemc.essencesponge; import com.google.inject.Inject; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.*; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.service.config.DefaultConfig; import java.io.File; import static org.essencemc.essencesponge.PluginDescription.*; /** * The main class for Essence Sponge plugin */ @Plugin(id = ID, name = NAME, version = VERSION, dependencies = DEPENDENCIES) public class EssenceSponge { @Inject @DefaultConfig(sharedRoot = false) private File configDir; @Inject private Logger logger; @Inject private Game game; @Listener public void onPreInitialization(GamePreInitializationEvent event) { getLogger().info(ID + " is loading..."); if (!configDir.exists()) { configDir.mkdirs(); } //TODO add config loaders } @Listener public void onInitialization(GameInitializationEvent event) { // TODO register commands // TODO register events } @Listener public void onLoadComplete(GameLoadCompleteEvent event) { getLogger().info(ID + " has been loaded!"); } @Listener public void onStopping(GameStoppingEvent event) { getLogger().info(ID + " is unloading"); } @Listener public void onStopped(GameStoppedServerEvent event) { getLogger().info(ID + " has been unloaded!"); } public File getConfigDir() { return configDir; } public Logger getLogger() { return logger; } public Game getGame() { return game; } }
package beast.app.draw; import java.awt.Dimension; import java.util.List; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.border.EtchedBorder; import beast.app.beauti.BeautiDoc; import beast.app.beauti.BeautiSubTemplate; import beast.core.BEASTInterface; import beast.core.Input; import beast.util.AddOnManager; public class BEASTObjectInputEditor extends InputEditor.Base { private static final long serialVersionUID = 1L; JComboBox<Object> m_selectBEASTObjectBox; SmallButton m_editBEASTObjectButton; BEASTObjectInputEditor _this; public BEASTObjectInputEditor(BeautiDoc doc) { super(doc); _this = this; } @Override public Class<?> type() { return BEASTInterface.class; } /** * construct an editor consisting of * o a label * o a combo box for selecting another plug-in * o a button for editing the plug-in * o validation label -- optional, if input is not valid */ @Override public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) { //box.setAlignmentY(LEFT_ALIGNMENT); m_bAddButtons = addButtons; m_input = input; m_beastObject = beastObject; this.itemNr = itemNr; if (isExpandOption == ExpandOption.FALSE) { simpleInit(input, beastObject); } else { expandedInit(input, beastObject); } } // init /** * add combobox with available beastObjects * a button to edit that beastObject + * a validation icon * * */ void simpleInit(Input<?> input, BEASTInterface beastObject) { addInputLabel(); addComboBox(this, input, beastObject); if (m_bAddButtons) { if (BEASTObjectPanel.countInputs((BEASTInterface) m_input.get(), doc) > 0) { m_editBEASTObjectButton = new SmallButton("e", true); if (input.get() == null) { m_editBEASTObjectButton.setEnabled(false); } m_editBEASTObjectButton.setToolTipText("Edit " + m_inputLabel.getText()); m_editBEASTObjectButton.addActionListener(e -> { BEASTObjectDialog dlg = new BEASTObjectDialog((BEASTInterface) m_input.get(), m_input.getType(), doc); if (dlg.showDialog()) { try { dlg.accept((BEASTInterface) m_input.get(), doc); } catch (Exception ex) { ex.printStackTrace(); } } refresh(); validateInput(); refreshPanel(); }); add(m_editBEASTObjectButton); } } addValidationLabel(); } // init void refresh() { if (m_selectBEASTObjectBox != null) { String oldID = (String) m_selectBEASTObjectBox.getSelectedItem(); String id = ((BEASTInterface) m_input.get()).getID(); if (!id.equals(oldID)) { m_selectBEASTObjectBox.addItem(id); m_selectBEASTObjectBox.setSelectedItem(id); m_selectBEASTObjectBox.removeItem(oldID); } } super.refreshPanel(); // Component c = this; // while (((Component) c).getParent() != null) { // c = ((Component) c).getParent(); // if (c instanceof ListSelectionListener) { // ((ListSelectionListener) c).valueChanged(null); } void initSelectPluginBox() { List<String> availableBEASTObjects = doc.getInputEditorFactory().getAvailablePlugins(m_input, m_beastObject, null, doc); if (availableBEASTObjects.size() > 0) { availableBEASTObjects.add(NO_VALUE); for (int i = 0; i < availableBEASTObjects.size(); i++) { String beastObjectName = availableBEASTObjects.get(i); if (beastObjectName.startsWith("new ")) { beastObjectName = beastObjectName.substring(beastObjectName.lastIndexOf('.')); availableBEASTObjects.set(i, beastObjectName); } } m_selectBEASTObjectBox.removeAllItems(); for (String str : availableBEASTObjects.toArray(new String[0])) { m_selectBEASTObjectBox.addItem(str); } m_selectBEASTObjectBox.setSelectedItem(m_beastObject.getID()); } } Box m_expansionBox = null; void expandedInit(Input<?> input, BEASTInterface beastObject) { addInputLabel(); Box box = Box.createVerticalBox(); // add horizontal box with combobox of BEASTObjects to select from Box combobox = Box.createHorizontalBox(); addComboBox(combobox, input, beastObject); box.add(combobox); doc.getInputEditorFactory().addInputs(box, (BEASTInterface) input.get(), this, this, doc); box.setBorder(new EtchedBorder()); //box.setBorder(BorderFactory.createLineBorder(Color.BLUE)); add(box); m_expansionBox = box; } // expandedInit /** * add combobox with BEASTObjects to choose from * On choosing a new value, create beastObject (if is not already an object) * Furthermore, if expanded, update expanded inputs */ protected void addComboBox(JComponent box, Input<?> input, BEASTInterface beastObject0) { if (itemNr >= 0) { box.add(new JLabel(beastObject0.getID())); box.add(Box.createGlue()); return; } List<BeautiSubTemplate> availableTemplates = doc.getInputEditorFactory().getAvailableTemplates(m_input, m_beastObject, null, doc); if (availableTemplates.size() > 0) { // if (m_input.getRule() != Validate.REQUIRED || beastObject == null) { // availableBEASTObjects.add(NO_VALUE); // for (int i = 0; i < availableBEASTObjects.size(); i++) { // String beastObjectName = availableBEASTObjects.get(i); // if (beastObjectName.startsWith("new ")) { // beastObjectName = beastObjectName.substring(beastObjectName.lastIndexOf('.')); // availableBEASTObjects.set(i, beastObjectName); m_selectBEASTObjectBox = new JComboBox<>(availableTemplates.toArray()); m_selectBEASTObjectBox.setName(input.getName()); Object o = input.get(); if (itemNr >= 0) { o = ((List<?>)o).get(itemNr); } String id2; if (o == null) { id2 = beastObject0.getID(); } else { id2 = ((BEASTInterface) o).getID(); } if (id2.indexOf('.')>=0) { id2 = id2.substring(0, id2.indexOf('.')); } for (BeautiSubTemplate template : availableTemplates) { if (template.matchesName(id2)) { m_selectBEASTObjectBox.setSelectedItem(template); } } m_selectBEASTObjectBox.addActionListener(e -> { // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // get a handle of the selected beastObject BeautiSubTemplate selected = (BeautiSubTemplate) m_selectBEASTObjectBox.getSelectedItem(); BEASTInterface beastObject = (BEASTInterface) m_input.get(); String id = beastObject.getID(); String partition = id.substring(id.indexOf('.') + 1); if (partition.indexOf(':') >= 0) { partition = id.substring(id.indexOf(':') + 1); } //String newID = selected.getMainID().replaceAll("\\$\\(n\\)", partition); if (selected.equals(NO_VALUE)) { beastObject = null; // } else if (PluginPanel.g_plugins.containsKey(newID)) { // beastObject = PluginPanel.g_plugins.get(newID); } else { try { beastObject = selected.createSubNet(doc.getContextFor(beastObject), m_beastObject, m_input, true); //PluginPanel.addPluginToMap(beastObject); // tricky: try to connect up new inputs with old inputs of existing name // beastObject oldPlugin = (beastObject) m_input.get(); // for (Input<?> oldInput: oldPlugin.listInputs()) { // String name = oldInput.getName(); // try { // Input<?> newInput = beastObject.getInput(name); // if (newInput.get() instanceof List) { // List<?> values = (List<?>) oldInput.get(); // for (Object value: values) { // newInput.setValue(value, beastObject); // } else { // newInput.setValue(oldInput.get(), beastObject); // } catch (Exception ex) { // // ignore } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Could not select beastObject: " + ex.getClass().getName() + " " + ex.getMessage() ); } } try { if (beastObject == null) { m_selectBEASTObjectBox.setSelectedItem(NO_VALUE); // is this input expanded? if (m_expansionBox != null) { // remove items from Expansion Box, if any for (int i = 1; i < m_expansionBox.getComponentCount(); i++) { m_expansionBox.remove(i); } } else { // not expanded if (m_bAddButtons && m_editBEASTObjectButton != null) { m_editBEASTObjectButton.setEnabled(false); } } } else { if (!m_input.canSetValue(beastObject, m_beastObject)) { throw new IllegalArgumentException("Cannot set input to this value"); } // // get handle on ID of the beastObject, and add to combobox if necessary // String id = beastObject.getID(); // // TODO RRB: have to remove ID first, then add it // // The addition is necessary to make the items in the expansionBox scale and show up // // Is there another way? // m_selectPluginBox.removeItem(id); // m_selectPluginBox.addItem(id); // m_selectPluginBox.setSelectedItem(id); id = beastObject.getID(); id = id.substring(0, id.indexOf('.')); for (int i = 0; i < m_selectBEASTObjectBox.getItemCount(); i++) { BeautiSubTemplate template = (BeautiSubTemplate) m_selectBEASTObjectBox.getItemAt(i); if (template.getMainID().replaceAll(".\\$\\(n\\)", "").equals(id) || template.getMainID().replaceAll(".s:\\$\\(n\\)", "").equals(id) || template.getMainID().replaceAll(".c:\\$\\(n\\)", "").equals(id) || template.getMainID().replaceAll(".t:\\$\\(n\\)", "").equals(id)) { m_selectBEASTObjectBox.setSelectedItem(template); } } } setValue(beastObject); //m_input.setValue(beastObject, m_beastObject); if (m_expansionBox != null) { // remove items from Expansion Box for (int i = 1; i < m_expansionBox.getComponentCount(); ) { m_expansionBox.remove(i); } // add new items to Expansion Box if (beastObject != null) { doc.getInputEditorFactory().addInputs(m_expansionBox, beastObject, _this, _this, doc); } } else { // it is not expanded, enable the edit button if (m_bAddButtons && m_editBEASTObjectButton != null) { m_editBEASTObjectButton.setEnabled(true); } validateInput(); } sync(); refreshPanel(); } catch (Exception ex) { id = ((BEASTInterface) m_input.get()).getID(); m_selectBEASTObjectBox.setSelectedItem(id); ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Could not change beastObject: " + ex.getClass().getName() + " " + ex.getMessage() ); } }); m_selectBEASTObjectBox.setToolTipText(input.getHTMLTipText()); int fontsize = m_selectBEASTObjectBox.getFont().getSize(); m_selectBEASTObjectBox.setMaximumSize(new Dimension(1024, 200 * fontsize / 13)); box.add(m_selectBEASTObjectBox); } } // protected void addComboBox2(Box box, Input <?> input, BEASTObject beastObject) { // List<String> availableBEASTObjects = PluginPanel.getAvailablePlugins(m_input, m_beastObject, null); // if (availableBEASTObjects.size() > 0) { // if (m_input.getRule() != Validate.REQUIRED || beastObject == null) { // availableBEASTObjects.add(NO_VALUE); // for (int i = 0; i < availableBEASTObjects.size(); i++) { // String beastObjectName = availableBEASTObjects.get(i); // if (beastObjectName.startsWith("new ")) { // beastObjectName = beastObjectName.substring(beastObjectName.lastIndexOf('.')); // availableBEASTObjects.set(i, beastObjectName); // m_selectPluginBox = new JComboBox(availableBEASTObjects.toArray(new String[0])); // String selectString = NO_VALUE; // if (input.get() != null) { // selectString = ((BEASTObject) input.get()).getID(); // m_selectPluginBox.setSelectedItem(selectString); // m_selectPluginBox.addActionListener(new ActionListener() { // // implements ActionListener // public void actionPerformed(ActionEvent e) { // // get a handle of the selected beastObject // String selected = (String) m_selectPluginBox.getSelectedItem(); // BEASTObject beastObject = (BEASTObject) m_input.get(); // if (selected.equals(NO_VALUE)) { // beastObject = null; // } else if (!selected.startsWith(".")) { // beastObject = PluginPanel.g_plugins.get(selected); // } else { // List<String> availableBEASTObjects = PluginPanel.getAvailablePlugins(m_input, m_beastObject, null); // int i = 0; // while (!availableBEASTObjects.get(i).matches(".*\\"+selected+"$")) { // selected = availableBEASTObjects.get(i); // /* create new beastObject */ // try { // beastObject = (BEASTObject) Class.forName(selected.substring(4)).newInstance(); // PluginPanel.addPluginToMap(beastObject); // // tricky: try to connect up new inputs with old inputs of existing name // BEASTObject oldPlugin = (BEASTObject) m_input.get(); // for (Input<?> oldInput: oldPlugin.listInputs()) { // String name = oldInput.getName(); // try { // Input<?> newInput = beastObject.getInput(name); // if (newInput.get() instanceof List) { // List<?> values = (List<?>) oldInput.get(); // for (Object value: values) { // newInput.setValue(value, beastObject); // } else { // newInput.setValue(oldInput.get(), beastObject); // } catch (Exception ex) { // // ignore // } catch (Exception ex) { // JOptionPane.showMessageDialog(null, "Could not select beastObject: " + // ex.getClass().getName() + " " + // ex.getMessage() // try { // if (beastObject == null) { // m_selectPluginBox.setSelectedItem(NO_VALUE); // // is this input expanded? // if (m_expansionBox != null) { // // remove items from Expansion Box, if any // for (int i = 1; i < m_expansionBox.getComponentCount(); i++) { // m_expansionBox.remove(i); // } else { // not expanded // if (m_bAddButtons) { // m_editPluginButton.setEnabled(false); // } else { // if (!m_input.canSetValue(beastObject, m_beastObject)) { // throw new Exception("Cannot set input to this value"); // // get handle on ID of the beastObject, and add to combobox if necessary // String id = beastObject.getID(); // // TODO RRB: have to remove ID first, then add it // // The addition is necessary to make the items in the expansionBox scale and show up // // Is there another way? // m_selectPluginBox.removeItem(id); // m_selectPluginBox.addItem(id); // m_selectPluginBox.setSelectedItem(id); // m_input.setValue(beastObject, m_beastObject); // if (m_expansionBox != null) { // // remove items from Expansion Box // for (int i = 1; i < m_expansionBox.getComponentCount(); ) { // m_expansionBox.remove(i); // // add new items to Expansion Box // if (beastObject != null) { // PluginPanel.addInputs(m_expansionBox, beastObject, _this, _this); // } else { // // it is not expanded, enable the edit button // if (m_bAddButtons) { // m_editPluginButton.setEnabled(true); // checkValidation(); // } catch (Exception ex) { // String id = ((BEASTObject)m_input.get()).getID(); // m_selectPluginBox.setSelectedItem(id); // //ex.printStackTrace(); // JOptionPane.showMessageDialog(null, "Could not change beastObject: " + // ex.getClass().getName() + " " + // ex.getMessage() // m_selectPluginBox.setToolTipText(input.getTipText()); // m_selectPluginBox.setMaximumSize(new Dimension(1024, 20)); // box.add(m_selectPluginBox); String[] getAvailablePlugins() { List<String> beastObjectNames = AddOnManager.find(m_input.getType(), "beast"); return beastObjectNames.toArray(new String[0]); } // getAvailablePlugins } // class PluginInputEditor
package org.opencms.i18n.tools; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.ade.configuration.CmsResourceTypeConfig; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypeXmlContainerPage; import org.opencms.file.types.I_CmsResourceType; import org.opencms.i18n.CmsLocaleGroupService; import org.opencms.i18n.CmsLocaleGroupService.Status; import org.opencms.i18n.CmsLocaleManager; import org.opencms.loader.I_CmsFileNameGenerator; import org.opencms.lock.CmsLockActionRecord; import org.opencms.lock.CmsLockActionRecord.LockChange; import org.opencms.lock.CmsLockUtil; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.site.CmsSite; import org.opencms.ui.Messages; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsMacroResolver; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.CmsXmlException; import org.opencms.xml.containerpage.CmsContainerBean; import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.containerpage.CmsContainerPageBean; import org.opencms.xml.containerpage.CmsXmlContainerPage; import org.opencms.xml.containerpage.CmsXmlContainerPageFactory; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.commons.logging.Log; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * Helper class for copying container pages including some of their elements.<p> */ public class CmsContainerPageCopier { /** * Enum representing the element copy mode.<p> */ public enum CopyMode { /** Choose between reuse / copy automatically depending on source / target locale and the configuration .*/ automatic, /** Do not copy elements. */ reuse, /** Automatically determine when to copy elements. */ smartCopy, /** Like smartCopy, but also converts locales of copied elements. */ smartCopyAndChangeLocale; } /** * Exception indicating that no custom replacement element was found * for a type which requires replacement.<p> */ public static class NoCustomReplacementException extends Exception { /** Serial version id. */ private static final long serialVersionUID = 1L; /** The resource for which no exception was found. */ private CmsResource m_resource; /** * Creates a new instance.<p> * * @param resource the resource for which no replacement was found */ public NoCustomReplacementException(CmsResource resource) { super(); m_resource = resource; } /** * Gets the resource for which no replacement was found.<p> * * @return the resource */ public CmsResource getResource() { return m_resource; } } /** The log instance used for this class. */ private static final Log LOG = CmsLog.getLog(CmsContainerPageCopier.class); /** The CMS context used by this object. */ private CmsObject m_cms; /** The copied resource. */ private CmsResource m_copiedFolderOrPage; /** The copy mode. */ private CopyMode m_copyMode = CopyMode.smartCopyAndChangeLocale; /** List of created resources. */ private List<CmsResource> m_createdResources = Lists.newArrayList(); /** Map of custom replacements. */ private Map<CmsUUID, CmsUUID> m_customReplacements; /** Maps structure ids of original container elements to structure ids of their copies/replacements. */ private Map<CmsUUID, CmsUUID> m_elementReplacements = Maps.newHashMap(); /** The original page. */ private CmsResource m_originalPage; /** The target folder. */ private CmsResource m_targetFolder; /** Resource types which require custom replacements. */ private Set<String> m_typesWithRequiredReplacements; /** * Creates a new instance.<p> * * @param cms the CMS context to use */ public CmsContainerPageCopier(CmsObject cms) { m_cms = cms; } /** * Converts locales for the copied container element.<p> * * @param elementResource the copied container element * @throws CmsException if something goes wrong */ public void adjustLocalesForElement(CmsResource elementResource) throws CmsException { if (m_copyMode != CopyMode.smartCopyAndChangeLocale) { return; } CmsFile file = m_cms.readFile(elementResource); Locale oldLocale = OpenCms.getLocaleManager().getDefaultLocale(m_cms, m_originalPage); Locale newLocale = OpenCms.getLocaleManager().getDefaultLocale(m_cms, m_targetFolder); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file); try { content.moveLocale(oldLocale, newLocale); LOG.info("Replacing locale " + oldLocale + " -> " + newLocale + " for " + elementResource.getRootPath()); file.setContents(content.marshal()); m_cms.writeFile(file); } catch (CmsXmlException e) { LOG.info( "NOT replacing locale for " + elementResource.getRootPath() + ": old=" + oldLocale + ", new=" + newLocale + ", contentLocales=" + content.getLocales()); } } /** * Gets the copied folder or page.<p> * * @return the copied folder or page */ public CmsResource getCopiedFolderOrPage() { return m_copiedFolderOrPage; } /** * Returns the target folder.<p> * * @return the target folder */ public CmsResource getTargetFolder() { return m_targetFolder; } /** * Produces the replacement for a container page element to use in a copy of an existing container page.<p> * * @param targetPage the target container page * @param originalElement the original element * @return the replacement element for the copied page * * @throws CmsException if something goes wrong * @throws NoCustomReplacementException if a custom replacement is not found for a type which requires it */ public CmsContainerElementBean replaceContainerElement( CmsResource targetPage, CmsContainerElementBean originalElement) throws CmsException, NoCustomReplacementException { // if (m_elementReplacements.containsKey(originalElement.getId() CmsObject targetCms = OpenCms.initCmsObject(m_cms); CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(m_targetFolder.getRootPath()); if (site != null) { targetCms.getRequestContext().setSiteRoot(site.getSiteRoot()); } if ((originalElement.getFormatterId() == null) || (originalElement.getId() == null)) { String rootPath = m_originalPage != null ? m_originalPage.getRootPath() : "???"; LOG.warn("Skipping container element because of missing id in page: " + rootPath); return null; } if (m_elementReplacements.containsKey(originalElement.getId())) { return new CmsContainerElementBean( m_elementReplacements.get(originalElement.getId()), maybeReplaceFormatter(originalElement.getFormatterId()), maybeReplaceFormatterInSettings(originalElement.getIndividualSettings()), originalElement.isCreateNew()); } else { CmsResource originalResource = m_cms.readResource( originalElement.getId(), CmsResourceFilter.IGNORE_EXPIRATION); I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(originalResource); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(m_cms, targetPage.getRootPath()); CmsResourceTypeConfig typeConfig = config.getResourceType(type.getTypeName()); if ((m_copyMode != CopyMode.reuse) && (typeConfig != null) && (originalElement.isCreateNew() || typeConfig.isCopyInModels()) && !type.getTypeName().equals(CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME)) { CmsResource resourceCopy = typeConfig.createNewElement( targetCms, originalResource, targetPage.getRootPath()); CmsContainerElementBean copy = new CmsContainerElementBean( resourceCopy.getStructureId(), maybeReplaceFormatter(originalElement.getFormatterId()), maybeReplaceFormatterInSettings(originalElement.getIndividualSettings()), originalElement.isCreateNew()); m_elementReplacements.put(originalElement.getId(), resourceCopy.getStructureId()); LOG.info( "Copied container element " + originalResource.getRootPath() + " -> " + resourceCopy.getRootPath()); CmsLockActionRecord record = null; try { record = CmsLockUtil.ensureLock(m_cms, resourceCopy); adjustLocalesForElement(resourceCopy); } finally { if ((record != null) && (record.getChange() == LockChange.locked)) { m_cms.unlockResource(resourceCopy); } } return copy; } else if (m_customReplacements != null) { CmsUUID replacementId = m_customReplacements.get(originalElement.getId()); if (replacementId != null) { return new CmsContainerElementBean( replacementId, maybeReplaceFormatter(originalElement.getFormatterId()), maybeReplaceFormatterInSettings(originalElement.getIndividualSettings()), originalElement.isCreateNew()); } else { if ((m_typesWithRequiredReplacements != null) && m_typesWithRequiredReplacements.contains(type.getTypeName())) { throw new NoCustomReplacementException(originalResource); } else { return originalElement; } } } else { LOG.info("Reusing container element: " + originalResource.getRootPath()); return originalElement; } } } /** * Replaces the elements in the copied container page with copies, if appropriate based on the current copy mode.<p> * * @param containerPage the container page copy whose elements should be replaced with copies * * @throws CmsException if something goes wrong * @throws NoCustomReplacementException if a custom replacement element was not found for a type which requires it */ public void replaceElements(CmsResource containerPage) throws CmsException, NoCustomReplacementException { CmsObject rootCms = OpenCms.initCmsObject(m_cms); rootCms.getRequestContext().setSiteRoot(""); CmsObject targetCms = OpenCms.initCmsObject(m_cms); targetCms.getRequestContext().setSiteRoot(""); CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(m_targetFolder.getRootPath()); if (site != null) { targetCms.getRequestContext().setSiteRoot(site.getSiteRoot()); } else if (OpenCms.getSiteManager().startsWithShared(m_targetFolder.getRootPath())) { targetCms.getRequestContext().setSiteRoot(OpenCms.getSiteManager().getSharedFolder()); } CmsProperty elementReplacementProp = rootCms.readPropertyObject( m_targetFolder, CmsPropertyDefinition.PROPERTY_ELEMENT_REPLACEMENTS, true); if ((elementReplacementProp != null) && (elementReplacementProp.getValue() != null)) { try { CmsResource elementReplacementMap = targetCms.readResource( elementReplacementProp.getValue(), CmsResourceFilter.IGNORE_EXPIRATION); OpenCms.getLocaleManager(); String encoding = CmsLocaleManager.getResourceEncoding(targetCms, elementReplacementMap); CmsFile elementReplacementFile = targetCms.readFile(elementReplacementMap); Properties props = new Properties(); props.load( new InputStreamReader(new ByteArrayInputStream(elementReplacementFile.getContents()), encoding)); CmsMacroResolver resolver = new CmsMacroResolver(); resolver.addMacro("sourcesite", m_cms.getRequestContext().getSiteRoot().replaceAll("/+$", "")); resolver.addMacro("targetsite", targetCms.getRequestContext().getSiteRoot().replaceAll("/+$", "")); Map<CmsUUID, CmsUUID> customReplacements = Maps.newHashMap(); for (Map.Entry<Object, Object> entry : props.entrySet()) { if ((entry.getKey() instanceof String) && (entry.getValue() instanceof String)) { try { String key = (String)entry.getKey(); if ("required".equals(key)) { m_typesWithRequiredReplacements = Sets.newHashSet( ((String)entry.getValue()).split(" *, *")); continue; } key = resolver.resolveMacros(key); String value = (String)entry.getValue(); value = resolver.resolveMacros(value); CmsResource keyRes = rootCms.readResource(key, CmsResourceFilter.IGNORE_EXPIRATION); CmsResource valRes = rootCms.readResource(value, CmsResourceFilter.IGNORE_EXPIRATION); customReplacements.put(keyRes.getStructureId(), valRes.getStructureId()); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } m_customReplacements = customReplacements; } } } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.warn(e.getLocalizedMessage(), e); } } CmsXmlContainerPage pageXml = CmsXmlContainerPageFactory.unmarshal(m_cms, containerPage); CmsContainerPageBean page = pageXml.getContainerPage(m_cms); List<CmsContainerBean> newContainers = Lists.newArrayList(); for (CmsContainerBean container : page.getContainers().values()) { List<CmsContainerElementBean> newElements = Lists.newArrayList(); for (CmsContainerElementBean element : container.getElements()) { CmsContainerElementBean newBean = replaceContainerElement(containerPage, element); if (newBean != null) { newElements.add(newBean); } } CmsContainerBean newContainer = new CmsContainerBean( container.getName(), container.getType(), container.getParentInstanceId(), newElements); newContainers.add(newContainer); } CmsContainerPageBean newPageBean = new CmsContainerPageBean(newContainers); pageXml.save(rootCms, newPageBean); } /** * Starts the page copying process.<p> * * @param source the source (can be either a container page, or a folder whose default file is a container page) * @param target the target folder * * @throws CmsException if soemthing goes wrong * @throws NoCustomReplacementException if a custom replacement element was not found */ public void run(CmsResource source, CmsResource target) throws CmsException, NoCustomReplacementException { LOG.info( "Starting page copy process: page='" + source.getRootPath() + "', targetFolder='" + target.getRootPath() + "'"); CmsObject rootCms = OpenCms.initCmsObject(m_cms); rootCms.getRequestContext().setSiteRoot(""); if (m_copyMode == CopyMode.automatic) { Locale sourceLocale = OpenCms.getLocaleManager().getDefaultLocale(rootCms, source); Locale targetLocale = OpenCms.getLocaleManager().getDefaultLocale(rootCms, target); // if same locale, copy elements, otherwise use configured setting LOG.debug( "copy mode automatic: source=" + sourceLocale + " target=" + targetLocale + " reuseConfig=" + OpenCms.getLocaleManager().shouldReuseElements() + ""); if (sourceLocale.equals(targetLocale)) { m_copyMode = CopyMode.smartCopyAndChangeLocale; } else { if (OpenCms.getLocaleManager().shouldReuseElements()) { m_copyMode = CopyMode.reuse; } else { m_copyMode = CopyMode.smartCopyAndChangeLocale; } } } if (source.isFolder()) { if (source.equals(target)) { throw new CmsException(Messages.get().container(Messages.ERR_PAGECOPY_SOURCE_IS_TARGET_0)); } CmsResource page = m_cms.readDefaultFile(source, CmsResourceFilter.IGNORE_EXPIRATION); if ((page == null) || !CmsResourceTypeXmlContainerPage.isContainerPage(page)) { throw new CmsException(Messages.get().container(Messages.ERR_PAGECOPY_INVALID_PAGE_0)); } List<CmsProperty> properties = Lists.newArrayList(m_cms.readPropertyObjects(source, false)); Iterator<CmsProperty> iterator = properties.iterator(); while (iterator.hasNext()) { CmsProperty prop = iterator.next(); // copied folder may be root of a locale subtree, but since we may want to copy to a different locale, // we don't want the locale property in the copy if (prop.getName().equals(CmsPropertyDefinition.PROPERTY_LOCALE) || prop.getName().equals(CmsPropertyDefinition.PROPERTY_ELEMENT_REPLACEMENTS)) { iterator.remove(); } } I_CmsFileNameGenerator nameGen = OpenCms.getResourceManager().getNameGenerator(); String copyPath = CmsFileUtil.removeTrailingSeparator( CmsStringUtil.joinPaths(target.getRootPath(), source.getName())); copyPath = nameGen.getNewFileName(rootCms, copyPath + "%(number)", 4, true); Double maxNavPosObj = readMaxNavPos(target); double maxNavpos = maxNavPosObj == null ? 0 : maxNavPosObj.doubleValue(); boolean hasNavpos = maxNavPosObj != null; CmsResource copiedFolder = rootCms.createResource( copyPath, OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.RESOURCE_TYPE_NAME), null, properties); m_createdResources.add(copiedFolder); if (hasNavpos) { String newNavPosStr = "" + (maxNavpos + 10); rootCms.writePropertyObject( copiedFolder.getRootPath(), new CmsProperty(CmsPropertyDefinition.PROPERTY_NAVPOS, newNavPosStr, null)); } String pageCopyPath = CmsStringUtil.joinPaths(copiedFolder.getRootPath(), page.getName()); m_originalPage = page; m_targetFolder = target; m_copiedFolderOrPage = copiedFolder; rootCms.copyResource(page.getRootPath(), pageCopyPath); CmsResource copiedPage = rootCms.readResource(pageCopyPath, CmsResourceFilter.IGNORE_EXPIRATION); m_createdResources.add(copiedPage); replaceElements(copiedPage); CmsLocaleGroupService localeGroupService = rootCms.getLocaleGroupService(); if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) { try { localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } tryUnlock(copiedFolder); } else { CmsResource page = source; if (!CmsResourceTypeXmlContainerPage.isContainerPage(page)) { throw new CmsException(Messages.get().container(Messages.ERR_PAGECOPY_INVALID_PAGE_0)); } I_CmsFileNameGenerator nameGen = OpenCms.getResourceManager().getNameGenerator(); String copyPath = CmsFileUtil.removeTrailingSeparator( CmsStringUtil.joinPaths(target.getRootPath(), source.getName())); int lastDot = copyPath.lastIndexOf("."); int lastSlash = copyPath.lastIndexOf("/"); if (lastDot > lastSlash) { // path has an extension String macroPath = copyPath.substring(0, lastDot) + "%(number)" + copyPath.substring(lastDot); copyPath = nameGen.getNewFileName(rootCms, macroPath, 4, true); } else { copyPath = nameGen.getNewFileName(rootCms, copyPath + "%(number)", 4, true); } Double maxNavPosObj = readMaxNavPos(target); double maxNavpos = maxNavPosObj == null ? 0 : maxNavPosObj.doubleValue(); boolean hasNavpos = maxNavPosObj != null; rootCms.copyResource(page.getRootPath(), copyPath); if (hasNavpos) { String newNavPosStr = "" + (maxNavpos + 10); rootCms.writePropertyObject( copyPath, new CmsProperty(CmsPropertyDefinition.PROPERTY_NAVPOS, newNavPosStr, null)); } CmsResource copiedPage = rootCms.readResource(copyPath); m_createdResources.add(copiedPage); m_originalPage = page; m_targetFolder = target; m_copiedFolderOrPage = copiedPage; replaceElements(copiedPage); CmsLocaleGroupService localeGroupService = rootCms.getLocaleGroupService(); if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) { try { localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } tryUnlock(copiedPage); } } /** * Sets the copy mode.<p> * * @param copyMode the copy mode */ public void setCopyMode(CopyMode copyMode) { m_copyMode = copyMode; } /** * Reads the max nav position from the contents of a folder.<p> * * @param target a folder * @return the maximal NavPos from the contents of the folder, or null if no resources with a valid NavPos were found in the folder * * @throws CmsException if something goes wrong */ Double readMaxNavPos(CmsResource target) throws CmsException { List<CmsResource> existingResourcesInFolder = m_cms.readResources( target, CmsResourceFilter.IGNORE_EXPIRATION, false); double maxNavpos = 0.0; boolean hasNavpos = false; for (CmsResource existingResource : existingResourcesInFolder) { CmsProperty navpos = m_cms.readPropertyObject( existingResource, CmsPropertyDefinition.PROPERTY_NAVPOS, false); if (navpos.getValue() != null) { try { double navposNum = Double.parseDouble(navpos.getValue()); hasNavpos = true; maxNavpos = Math.max(navposNum, maxNavpos); } catch (NumberFormatException e) { // ignore } } } if (hasNavpos) { return Double.valueOf(maxNavpos); } else { return null; } } /** * Uses the custom translation table to translate formatter id.<p> * * @param formatterId the formatter id * @return the formatter replacement */ private CmsUUID maybeReplaceFormatter(CmsUUID formatterId) { if (m_customReplacements != null) { CmsUUID replacement = m_customReplacements.get(formatterId); if (replacement != null) { return replacement; } } return formatterId; } /** * Replaces formatter id in element settings.<p> * * @param individualSettings the settings in which to replace the formatter id * * @return the map with the possible replaced ids */ private Map<String, String> maybeReplaceFormatterInSettings(Map<String, String> individualSettings) { if (individualSettings == null) { return null; } else if (m_customReplacements == null) { return individualSettings; } else { LinkedHashMap<String, String> result = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> entry : individualSettings.entrySet()) { String value = entry.getValue(); if (CmsUUID.isValidUUID(value)) { CmsUUID valueId = new CmsUUID(value); if (m_customReplacements.containsKey(valueId)) { value = "" + m_customReplacements.get(valueId); } } result.put(entry.getKey(), value); } return result; } } /** * Tries to unlock the given resource.<p> * * @param resource the resource to unlock */ private void tryUnlock(CmsResource resource) { try { m_cms.unlockResource(resource); } catch (CmsException e) { // usually not a problem LOG.debug("failed to unlock " + resource.getRootPath(), e); } } }
package org.java_websocket.client; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.NotYetConnectedException; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketAdapter; import org.java_websocket.WebSocketImpl; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_17; import org.java_websocket.exceptions.InvalidHandshakeException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.handshake.HandshakeImpl1Client; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshake; /** * A subclass must implement at least <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be * useful. At runtime the user is expected to establish a connection via {@link #connect()}, then receive events like {@link #onMessage(String)} via the overloaded methods and to {@link #send(String)} data to the server. */ public abstract class WebSocketClient extends WebSocketAdapter implements Runnable, WebSocket { /** * The URI this channel is supposed to connect to. */ protected URI uri = null; private WebSocketImpl engine = null; private Socket socket = null; private InputStream istream; private OutputStream ostream; private Proxy proxy = Proxy.NO_PROXY; private Thread writeThread; private Draft draft; private Map<String,String> headers; private CountDownLatch connectLatch = new CountDownLatch( 1 ); private CountDownLatch closeLatch = new CountDownLatch( 1 ); private int connectTimeout = 0; /** This open a websocket connection as specified by rfc6455 */ public WebSocketClient( URI serverURI ) { this( serverURI, new Draft_17() ); } /** * Constructs a WebSocketClient instance and sets it to the connect to the * specified URI. The channel does not attampt to connect automatically. The connection * will be established once you call <var>connect</var>. */ public WebSocketClient( URI serverUri , Draft draft ) { this( serverUri, draft, null, 0 ); } public WebSocketClient( URI serverUri , Draft protocolDraft , Map<String,String> httpHeaders , int connectTimeout ) { if( serverUri == null ) { throw new IllegalArgumentException(); } else if( protocolDraft == null ) { throw new IllegalArgumentException( "null as draft is permitted for `WebSocketServer` only!" ); } this.uri = serverUri; this.draft = protocolDraft; this.headers = httpHeaders; this.connectTimeout = connectTimeout; this.engine = new WebSocketImpl( this, protocolDraft ); } /** * Returns the URI that this WebSocketClient is connected to. */ public URI getURI() { return uri; } public Draft getDraft() { return draft; } /** * Initiates the websocket connection. This method does not block. */ public void connect() { if( writeThread != null ) throw new IllegalStateException( "WebSocketClient objects are not reuseable" ); writeThread = new Thread( this ); writeThread.start(); } /** * Same as <code>connect</code> but blocks until the websocket connected or failed to do so.<br> * Returns whether it succeeded or not. **/ public boolean connectBlocking() throws InterruptedException { connect(); connectLatch.await(); return engine.isOpen(); } /** * Initiates the websocket close handshake. This method does not block<br> * In oder to make sure the connection is closed use <code>closeBlocking</code> */ public void close() { if( writeThread != null ) { engine.close( CloseFrame.NORMAL ); } } public void closeBlocking() throws InterruptedException { close(); closeLatch.await(); } /** * Sends <var>text</var> to the connected websocket server. * * @param text * The string which will be transmitted. */ public void send( String text ) throws NotYetConnectedException { engine.send( text ); } /** * Sends binary <var> data</var> to the connected webSocket server. * * @param data * The byte-Array of data to send to the WebSocket server. */ public void send( byte[] data ) throws NotYetConnectedException { engine.send( data ); } public void run() { try { if( socket == null ) { socket = new Socket( proxy ); } else if( socket.isClosed() ) { throw new IOException(); } if( !socket.isBound() ) socket.connect( new InetSocketAddress( uri.getHost(), getPort() ), connectTimeout ); istream = socket.getInputStream(); ostream = socket.getOutputStream(); sendHandshake(); } catch ( /*IOException | SecurityException | UnresolvedAddressException | InvalidHandshakeException | ClosedByInterruptException | SocketTimeoutException */Exception e ) { onWebsocketError( engine, e ); engine.closeConnection( CloseFrame.NEVER_CONNECTED, e.getMessage() ); return; } writeThread = new Thread( new WebsocketWriteThread() ); writeThread.start(); byte[] rawbuffer = new byte[ WebSocketImpl.RCVBUF ]; int readBytes; try { while ( ( readBytes = istream.read( rawbuffer ) ) != -1 ) { engine.decode( ByteBuffer.wrap( rawbuffer, 0, readBytes ) ); } engine.eot(); } catch ( IOException e ) { engine.eot(); } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); engine.closeConnection( CloseFrame.ABNORMAL_CLOSE, e.getMessage() ); } assert ( socket.isClosed() ); } private int getPort() { int port = uri.getPort(); if( port == -1 ) { String scheme = uri.getScheme(); if( scheme.equals( "wss" ) ) { return WebSocket.DEFAULT_WSS_PORT; } else if( scheme.equals( "ws" ) ) { return WebSocket.DEFAULT_PORT; } else { throw new RuntimeException( "unkonow scheme" + scheme ); } } return port; } private void sendHandshake() throws InvalidHandshakeException { String path; String part1 = uri.getPath(); String part2 = uri.getQuery(); if( part1 == null || part1.length() == 0 ) path = "/"; else path = part1; if( part2 != null ) path += "?" + part2; int port = getPort(); String host = uri.getHost() + ( port != WebSocket.DEFAULT_PORT ? ":" + port : "" ); HandshakeImpl1Client handshake = new HandshakeImpl1Client(); handshake.setResourceDescriptor( path ); handshake.put( "Host", host ); if( headers != null ) { for( Map.Entry<String,String> kv : headers.entrySet() ) { handshake.put( kv.getKey(), kv.getValue() ); } } engine.startHandshake( handshake ); } /** * This represents the state of the connection. */ public READYSTATE getReadyState() { return engine.getReadyState(); } /** * Calls subclass' implementation of <var>onMessage</var>. */ @Override public final void onWebsocketMessage( WebSocket conn, String message ) { onMessage( message ); } @Override public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) { onMessage( blob ); } @Override public void onWebsocketMessageFragment( WebSocket conn, Framedata frame ) { onFragment( frame ); } /** * Calls subclass' implementation of <var>onOpen</var>. */ @Override public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) { connectLatch.countDown(); onOpen( (ServerHandshake) handshake ); } /** * Calls subclass' implementation of <var>onClose</var>. */ @Override public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { connectLatch.countDown(); closeLatch.countDown(); if( writeThread != null ) writeThread.interrupt(); onClose( code, reason, remote ); } /** * Calls subclass' implementation of <var>onIOError</var>. */ @Override public final void onWebsocketError( WebSocket conn, Exception ex ) { onError( ex ); } @Override public final void onWriteDemand( WebSocket conn ) { // nothing to do } @Override public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) { onCloseInitiated( code, reason ); } @Override public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) { onClosing( code, reason, remote ); } public void onCloseInitiated( int code, String reason ) { } public void onClosing( int code, String reason, boolean remote ) { } public WebSocket getConnection() { return engine; } @Override public InetSocketAddress getLocalSocketAddress( WebSocket conn ) { if( socket != null ) return (InetSocketAddress) socket.getLocalSocketAddress(); return null; } @Override public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) { if( socket != null ) return (InetSocketAddress) socket.getLocalSocketAddress(); return null; } // ABTRACT METHODS ///////////////////////////////////////////////////////// public abstract void onOpen( ServerHandshake handshakedata ); public abstract void onMessage( String message ); public abstract void onClose( int code, String reason, boolean remote ); public abstract void onError( Exception ex ); public void onMessage( ByteBuffer bytes ) { } public void onFragment( Framedata frame ) { } private class WebsocketWriteThread implements Runnable { @Override public void run() { Thread.currentThread().setName( "WebsocketWriteThread" ); try { while ( !Thread.interrupted() ) { ByteBuffer buffer = engine.outQueue.take(); ostream.write( buffer.array(), 0, buffer.limit() ); ostream.flush(); } } catch ( IOException e ) { engine.eot(); } catch ( InterruptedException e ) { // this thread is regularly terminated via an interrupt } } } public void setProxy( Proxy proxy ) { if( proxy == null ) throw new IllegalArgumentException(); this.proxy = proxy; } /** * Accepts bound and unbound sockets.<br> * This method must be called before <code>connect</code>. * If the given socket is not yet bound it will be bound to the uri specified in the constructor. **/ public void setSocket( Socket socket ) { if( this.socket != null ) { throw new IllegalStateException( "socket has already been set" ); } this.socket = socket; } @Override public void sendFragmentedFrame( Opcode op, ByteBuffer buffer, boolean fin ) { engine.sendFragmentedFrame( op, buffer, fin ); } @Override public boolean isOpen() { return engine.isOpen(); } @Override public boolean isFlushAndClose() { return engine.isFlushAndClose(); } @Override public boolean isClosed() { return engine.isClosed(); } @Override public boolean isClosing() { return engine.isClosing(); } @Override public boolean isConnecting() { return engine.isConnecting(); } @Override public boolean hasBufferedData() { return engine.hasBufferedData(); } @Override public void close( int code ) { engine.close(); } @Override public void close( int code, String message ) { engine.close( code, message ); } @Override public void closeConnection( int code, String message ) { engine.closeConnection( code, message ); } @Override public void send( ByteBuffer bytes ) throws IllegalArgumentException , NotYetConnectedException { engine.send( bytes ); } @Override public void sendFrame( Framedata framedata ) { engine.sendFrame( framedata ); } @Override public InetSocketAddress getLocalSocketAddress() { return engine.getLocalSocketAddress(); } @Override public InetSocketAddress getRemoteSocketAddress() { return engine.getRemoteSocketAddress(); } }
package com.bitdubai.fermat_dmp_plugin.layer.network_service.wallet_resources.developer.bitdubai.version_1.event_handlers; import com.bitdubai.fermat_api.Service; import com.bitdubai.fermat_api.layer.dmp_network_service.CantCheckResourcesException; import com.bitdubai.fermat_api.layer.all_definition.enums.ServiceStatus; import com.bitdubai.fermat_api.layer.all_definition.event.PlatformEvent; import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventHandler; import com.bitdubai.fermat_api.layer.dmp_network_service.wallet_resources.WalletResourcesManager; public class BegunWalletInstallationEventHandler implements EventHandler { WalletResourcesManager walletResourcesManager; public void setWalletResourcesManager(WalletResourcesManager walletResourcesManager){ this.walletResourcesManager = walletResourcesManager; } @Override public void handleEvent(PlatformEvent platformEvent) throws Exception { if (((Service) this.walletResourcesManager).getStatus() == ServiceStatus.STARTED) { try { this.walletResourcesManager.checkResources(); } catch (CantCheckResourcesException cantCheckResourcesException) { /** * The main module could not handle this exception. Me neither. Will throw it again. */ throw cantCheckResourcesException; } } else { throw new CantCheckResourcesException("CAN'T CHECK WALLET RESOURCES:",null,"Error intalled wallet resources fields" , ""); } } }
package org.vitrivr.cineast.core.features; import gnu.trove.map.hash.TObjectDoubleHashMap; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.vitrivr.cineast.core.config.ReadableQueryConfig; import org.vitrivr.cineast.core.data.CorrespondenceFunction; import org.vitrivr.cineast.core.data.FloatVectorImpl; import org.vitrivr.cineast.core.data.Pair; import org.vitrivr.cineast.core.data.distance.DistanceElement; import org.vitrivr.cineast.core.data.score.ScoreElement; import org.vitrivr.cineast.core.data.score.SegmentScoreElement; import org.vitrivr.cineast.core.data.segments.SegmentContainer; import org.vitrivr.cineast.core.features.abstracts.StagedFeatureModule; import org.vitrivr.cineast.core.util.MathHelper; import org.vitrivr.cineast.core.util.audio.HPCP; import org.vitrivr.cineast.core.util.dsp.fft.FFTUtil; import org.vitrivr.cineast.core.util.dsp.fft.STFT; import org.vitrivr.cineast.core.util.dsp.fft.windows.HanningWindow; import java.util.ArrayList; import java.util.List; /** * @author rgasser * @version 1.0 * @created 25.04.17 */ public abstract class AverageHPCP extends StagedFeatureModule { /** Size of the window during STFT in samples. */ private final static float WINDOW_SIZE = 0.2f; /** Minimum resolution to consider in HPCP calculation. */ private final float min_frequency; /** Maximum resolution to consider in HPCP calculation. */ private final float max_frequency; /** HPCP resolution (12, 24, 36 bins). */ private final HPCP.Resolution resolution; /* The number of HPCP frames that should be averaged into a single vector. */ private final int average; /** * Default constructor. * * @param name Name of the entity (for persistence writer). * @param min_frequency Minimum frequency to consider for HPCP generation. * @param max_frequency Maximum frequency to consider for HPCP generation. * @param resolution Resolution of HPCP (i.e. number of HPCP bins). * @param average Number of frames to average. */ protected AverageHPCP(String name, float min_frequency, float max_frequency, HPCP.Resolution resolution, int average) { super(name, 2.0f); /* Assign variables. */ this.min_frequency = min_frequency; this.max_frequency = max_frequency; this.resolution = resolution; this.average = average; } /** * This method represents the first step that's executed when processing query. The associated SegmentContainer is * examined and feature-vectors are being generated. The generated vectors are returned by this method together with an * optional weight-vector. * <p> * <strong>Important: </strong> The weight-vector must have the same size as the feature-vectors returned by the method. * * @param sc SegmentContainer that was submitted to the feature module. * @param qc A QueryConfig object that contains query-related configuration parameters. Can still be edited. * @return List of feature vectors for lookup. */ @Override protected List<float[]> preprocessQuery(SegmentContainer sc, ReadableQueryConfig qc) { return this.getFeatures(sc); } /** * This method represents the last step that's executed when processing a query. A list of partial-results (DistanceElements) returned by * the lookup stage is processed based on some internal method and finally converted to a list of ScoreElements. The filtered list of * ScoreElements is returned by the feature module during retrieval. * * @param partialResults List of partial results returned by the lookup stage. * @param qc A ReadableQueryConfig object that contains query-related configuration parameters. * @return List of final results. Is supposed to be de-duplicated and the number of items should not exceed the number of items per module. */ @Override protected List<ScoreElement> postprocessQuery(List<DistanceElement> partialResults, ReadableQueryConfig qc) { /* Prepare helper data-structures. */ final List<ScoreElement> results = new ArrayList<>(); final TObjectDoubleHashMap<String> map = new TObjectDoubleHashMap<>(); /* Set QueryConfig and extract correspondence function. */ qc = this.setQueryConfig(qc); final CorrespondenceFunction correspondence = qc.getCorrespondenceFunction().orElse(this.linearCorrespondence); for (DistanceElement hit : partialResults) { if (map.containsKey(hit.getId())) { double current = map.get(hit.getId()); map.adjustValue(hit.getId(), (hit.getDistance()-current)/2.0f); } else { map.put(hit.getId(), hit.getDistance()); } } /* Prepare final result-set. */ map.forEachEntry((key, value) -> results.add(new SegmentScoreElement(key, correspondence.applyAsDouble(value)))); return ScoreElement.filterMaximumScores(results.stream()); } /** * Processes a SegmentContainer during extraction; calculates the HPCP for the container and * creates and persists a set shingle-vectors. * * @param segment SegmentContainer to process. */ public void processShot(SegmentContainer segment) { List<float[]> list = this.getFeatures(segment); list.forEach(f -> this.persist(segment.getId(), new FloatVectorImpl(f))); } /** * Returns a list of feature vectors given a SegmentContainer. * * @param segment SegmentContainer for which to calculate the feature vectors. * @return List of HPCP Shingle feature vectors. */ private List<float[]> getFeatures(SegmentContainer segment) { /* Create STFT. IF this fails, return empty list. */ Pair<Integer,Integer> parameters = FFTUtil.parametersForDuration(segment.getSamplingrate(), WINDOW_SIZE); STFT stft = segment.getSTFT(parameters.first, (parameters.first-2*parameters.second)/2,parameters.second, new HanningWindow()); if (stft == null) return new ArrayList<>(); HPCP hpcps = new HPCP(this.resolution, this.min_frequency, this.max_frequency); hpcps.addContribution(stft); /* Determine number of vectors that will result from the data. */ int vectors = hpcps.size()/this.average; List<float[]> features = new ArrayList<>(vectors); for (int i = 0; i < vectors; i++) { float[] feature = new float[2*this.resolution.bins]; SummaryStatistics[] statistics = new SummaryStatistics[this.resolution.bins]; for (int j = 0; j<this.average; j++) { for (int k=0; k<this.resolution.bins;k++) { if (statistics[k] == null) statistics[k] = new SummaryStatistics(); statistics[k].addValue(hpcps.getHpcp(i*this.average + j)[k]); } } for (int k=0; k<this.resolution.bins;k++) { feature[2*k] = (float)statistics[k].getMean(); feature[2*k+1] = (float)statistics[k].getStandardDeviation(); } features.add(MathHelper.normalizeL2(feature)); } return features; } }
package org.jtrfp.trcl.beh.ui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import org.jtrfp.trcl.AbstractSubmitter; import org.jtrfp.trcl.WeakPropertyChangeListener; import org.jtrfp.trcl.beh.Behavior; import org.jtrfp.trcl.beh.HasQuantifiableSupply; import org.jtrfp.trcl.beh.ProjectileFiringBehavior; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.ctl.ControllerInput; import org.jtrfp.trcl.ctl.ControllerInputsFactory.ControllerInputs; import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature; import org.jtrfp.trcl.file.Powerup; import org.jtrfp.trcl.miss.Mission; import org.jtrfp.trcl.miss.SatelliteViewFactory; import org.jtrfp.trcl.obj.Propelled; import org.jtrfp.trcl.obj.WorldObject; import org.jtrfp.trcl.snd.LoopingSoundEvent; import org.jtrfp.trcl.snd.SamplePlaybackEvent; import org.jtrfp.trcl.snd.SoundSystem; import org.jtrfp.trcl.snd.SoundTexture; public class AfterburnerBehavior extends Behavior implements HasQuantifiableSupply, PlayerControlBehavior { public static final String IGNITION_SOUND = "BLAST7.WAV"; public static final String EXTINGUISH_SOUND = "SHUT-DN7.WAV"; public static final String LOOP_SOUND = "ENGINE4.WAV"; private double fuelRemaining=0; private double formerMax,formerProp,newMax; private final ControllerInput afterburnerCtl; public static final String AFTERBURNER = "Afterburner"; private SoundTexture ignitionSound, extinguishSound, loopSound; private LoopingSoundEvent afterburnerLoop; private final RunStateListener runStateListener = new RunStateListener(); private final FiringVetoListener firingVetoListener = new FiringVetoListener(); private final ThrottleVetoListener throttleVetoListener = new ThrottleVetoListener(); // HARD REFERENCES; DO NOT REMOVE private PropertyChangeListener weakRunStateListener, weakAbControlListener, weakThrottleVetoListener; private boolean afterburning = false; private boolean installedVetoListeners = false; public AfterburnerBehavior(ControllerInputs inputs){ afterburnerCtl = inputs.getControllerInput(AFTERBURNER); //afterburnerCtl.addPropertyChangeListener(weakAbControlListener = new WeakPropertyChangeListener(abControlListener,afterburnerCtl)); }//end constructor private class FiringVetoListener implements VetoableChangeListener{ @Override public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { final Object newValue = evt.getNewValue(); if(isAfterburning() && newValue == Boolean.TRUE) throw new PropertyVetoException(null, evt); }//end vetoableChange(...) }//end FiringVetoListener private class ThrottleVetoListener implements VetoableChangeListener{ @Override public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { if(isAfterburning()) throw new PropertyVetoException(null, evt); }//end vetoableChange(...) }//end ThrottleVetoListener private class RunStateListener implements PropertyChangeListener{ @Override public void propertyChange(PropertyChangeEvent evt) { final Object newValue = evt.getNewValue(); //Ensure the afterburner sound isn't looping on completion of mission. if(!(newValue instanceof Mission.PlayerActivity)) ensureLoopDestroyed(); }//end propertyChange(...) }//end RunModeListener @Override public void setParent(WorldObject newParent){ super.setParent(newParent); final TR tr = newParent.getTr(); weakRunStateListener = new WeakPropertyChangeListener(runStateListener, tr); tr.addPropertyChangeListener(TRFactory.RUN_STATE, weakRunStateListener); }//end setParent(...) @Override public void tick(long tickTimeMillis){ if(!installedVetoListeners) installVetoListeners(); updateAfterburningState(); final WorldObject p = getParent(); if(isAfterburning()) fuelRemaining-=((double)p.getTr().getThreadManager().getElapsedTimeInMillisSinceLastGameTick()/ (double)Powerup.AFTERBURNER_TIME_PER_UNIT_MILLIS); }//end tick private void updateAfterburningState(){ final double state = afterburnerCtl.getState(); final Object runState = getParent().getTr().getRunState(); if(!isEnabled() || !(runState instanceof Mission.GameplayState) || runState instanceof SatelliteViewFactory.SatelliteViewState || runState instanceof Mission.SatelliteState ||//TODO: Supports old system, remove later runState instanceof Mission.Briefing) {setAfterburning(false);return;} setAfterburning(state >= .7); }//end updateAfterburningState() private void installVetoListeners(){ probeForBehaviors(new ProjectileFiringBehaviorSubmitter(), ProjectileFiringBehavior.class); probeForBehavior(UserInputThrottleControlBehavior.class).addVetoableChangeListener(UserInputThrottleControlBehavior.THROTTLE_CTL_STATE,throttleVetoListener); installedVetoListeners = true; }//end installVetoListeners() private class ProjectileFiringBehaviorSubmitter extends AbstractSubmitter<ProjectileFiringBehavior>{ @Override public void submit(ProjectileFiringBehavior item) { item.addVetoableChangeListener(ProjectileFiringBehavior.PENDING_FIRING,firingVetoListener); } }//end ProjectileFiringBehaviorSubmitter private void afterburnerOnTransient(WorldObject p){ //Save former max, former propulsion ignitionSFX(); startLoop(); Propelled prop = p.probeForBehavior(Propelled.class); formerMax=prop.getMaxPropulsion(); formerProp=prop.getPropulsion(); newMax=formerMax*3; p.probeForBehavior(Propelled.class). setMaxPropulsion(newMax). setPropulsion(newMax); }//end afterburnerOnTriansient(...) private void ignitionSFX(){ final SoundTexture ignitionSound = getIgnitionSound(); if(ignitionSound != null){ final WorldObject parent = getParent(); final TR tr = parent.getTr(); final SoundSystem soundSystem = Features.get(tr,SoundSystemFeature.class); final SamplePlaybackEvent playbackEvent = soundSystem.getPlaybackFactory(). create(ignitionSound, new double[]{ SoundSystem.DEFAULT_SFX_VOLUME, SoundSystem.DEFAULT_SFX_VOLUME}); soundSystem.enqueuePlaybackEvent(playbackEvent); }//end if(ignitionSound) }//end ignitionSFX() private void extinguishSFX(){ final SoundTexture extinguishSound = getExtinguishSound(); if(extinguishSound != null){ final WorldObject parent = getParent(); final TR tr = parent.getTr(); final SoundSystem soundSystem = Features.get(tr,SoundSystemFeature.class); final SamplePlaybackEvent playbackEvent = soundSystem.getPlaybackFactory(). create(extinguishSound, new double[]{ SoundSystem.DEFAULT_SFX_VOLUME, SoundSystem.DEFAULT_SFX_VOLUME}); soundSystem.enqueuePlaybackEvent(playbackEvent); }//end if(ignitionSound) }//end ignitionSFX() private void afterburnerOffTransient(WorldObject p){ stopLoop(); extinguishSFX(); Propelled prop = p.probeForBehavior(Propelled.class); prop.setMaxPropulsion(formerMax); prop.setPropulsion(formerProp); }//end afterburnerOffTransient(...) private void startLoop(){ if(loopSound == null) return; final WorldObject parent = getParent(); final TR tr = parent.getTr(); final SoundSystem soundSystem = Features.get(tr,SoundSystemFeature.class); if(afterburnerLoop != null) ensureLoopDestroyed(); afterburnerLoop = soundSystem.getLoopFactory(). create(loopSound, new double[]{ SoundSystem.DEFAULT_SFX_VOLUME, SoundSystem.DEFAULT_SFX_VOLUME}); soundSystem.enqueuePlaybackEvent(afterburnerLoop); }//end startLoop() private void ensureLoopDestroyed(){ if(afterburnerLoop == null) return; afterburnerLoop.destroy(); afterburnerLoop = null; } private void stopLoop(){ ensureLoopDestroyed(); } @Override public void addSupply(double amount) { fuelRemaining+=amount; }//end addSupply(...) @Override public double getSupply() { return fuelRemaining; }//end getSupply() public SoundTexture getIgnitionSound() { return ignitionSound; } public AfterburnerBehavior setIgnitionSound(SoundTexture ignitionSound) { this.ignitionSound = ignitionSound; return this; } public SoundTexture getExtinguishSound() { return extinguishSound; } public AfterburnerBehavior setExtinguishSound(SoundTexture extinguishSound) { this.extinguishSound = extinguishSound; return this; } public SoundTexture getLoopSound() { return loopSound; } public AfterburnerBehavior setLoopSound(SoundTexture loopSound) { this.loopSound = loopSound; return this; } public boolean isAfterburning() { return afterburning; } public void setAfterburning(boolean newValue) { final boolean oldValue = this.afterburning; if(newValue == oldValue) return; final WorldObject parent = getParent(); this.afterburning = newValue; if(newValue) afterburnerOnTransient(parent); else afterburnerOffTransient(parent); }//end setAfterburning(...) @Override public Behavior setEnable(boolean enable){ if(isAfterburning() && this.isEnabled() && !enable) setAfterburning(false); super.setEnable(enable); return this; } }//end AfterburnerBehavior
package railo.commons.date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import railo.commons.lang.StringUtil; import railo.runtime.exp.ExpressionException; import railo.runtime.type.List; public class TimeZoneUtil { private static final Map<String,TimeZone> IDS=new HashMap<String,TimeZone>(); static { String[] ids=TimeZone.getAvailableIDs(); for(int i=0;i<ids.length;i++){ IDS.put(ids[i].toLowerCase(), TimeZone.getTimeZone(ids[i])); } IDS.put("jvm", TimeZone.getDefault()); IDS.put("default", TimeZone.getDefault()); IDS.put("", TimeZone.getDefault()); // MS specific Timezone definions set("Dateline Standard Time",TimeZoneConstants.ETC_GMT_PLUS_12); // (GMT-12:00) International Date Line West set("Samoa Standard Time",TimeZoneConstants.PACIFIC_MIDWAY); // (GMT-11:00) Midway Island, Samoa set("Hawaiian Standard Time",TimeZoneConstants.HST); // (GMT-10:00) Hawaii set("Alaskan Standard Time",TimeZoneConstants.AST); // (GMT-09:00) Alaska set("Pacific Standard Time",TimeZoneConstants.PST); // (GMT-08:00) Pacific Time (US and Canada); Tijuana set("Mountain Standard Time",TimeZoneConstants.MST); // (GMT-07:00) Mountain Time (US and Canada) set("Mexico Standard Time",TimeZoneConstants.MEXICO_GENERAL); // (GMT-06:00) Guadalajara, Mexico City, Monterrey set("Mexico Standard Time 2",TimeZoneConstants.AMERICA_CHIHUAHUA); // (GMT-07:00) Chihuahua, La Paz, Mazatlan set("U.S. Mountain Standard Time",TimeZoneConstants.MST); // (GMT-07:00) Arizona set("Central Standard Time",TimeZoneConstants.CST); // (GMT-06:00) Central Time (US and Canada set("Canada Central Standard Time",TimeZoneConstants.CANADA_CENTRAL); // (GMT-06:00) Saskatchewan set("Central America Standard Time",TimeZoneConstants.CST); // (GMT-06:00) Central America set("Eastern Standard Time",TimeZoneConstants.EST); // (GMT-05:00) Eastern Time (US and Canada) set("U.S. Eastern Standard Time",TimeZoneConstants.EST); // (GMT-05:00) Indiana (East) set("S.A. Pacific Standard Time",TimeZoneConstants.AMERICA_BOGOTA); // (GMT-05:00) Bogota, Lima, Quito set("Atlantic Standard Time",TimeZoneConstants.CANADA_ATLANTIC); // (GMT-04:00) Atlantic Time (Canada) set("S.A. Western Standard Time",TimeZoneConstants.AMERICA_ANTIGUA); // (GMT-04:00) Caracas, La Paz set("Pacific S.A. Standard Time",TimeZoneConstants.AMERICA_SANTIAGO); // (GMT-04:00) Santiago set("Newfoundland and Labrador Standard Time",TimeZoneConstants.CNT); // (GMT-03:30) Newfoundland and Labrador set("E. South America Standard Time",TimeZoneConstants.BET); // (GMT-03:00) Brasilia set("S.A. Eastern Standard Time",TimeZoneConstants.AMERICA_ARGENTINA_BUENOS_AIRES); // (GMT-03:00) Buenos Aires, Georgetown set("Greenland Standard Time",TimeZoneConstants.AMERICA_GODTHAB); // (GMT-03:00) Greenland set("Mid-Atlantic Standard Time",TimeZoneConstants.AMERICA_NORONHA); // (GMT-02:00) Mid-Atlantic set("Azores Standard Time",TimeZoneConstants.ATLANTIC_AZORES); // (GMT-01:00) Azores set("Cape Verde Standard Time",TimeZoneConstants.ATLANTIC_CAPE_VERDE); // (GMT-01:00) Cape Verde Islands set("Central Europe Standard Time",TimeZoneConstants.CET); // (GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague set("Central European Standard Time",TimeZoneConstants.CET); // (GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb set("Romance Standard Time",TimeZoneConstants.EUROPE_BRUSSELS); // (GMT+01:00) Brussels, Copenhagen, Madrid, Paris set("W. Europe Standard Time",TimeZoneConstants.CET); // (GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna set("W. Central Africa Standard Time",null); // (GMT+01:00) West Central Africa set("E. Europe Standard Time",TimeZoneConstants.ART); // (GMT+02:00) Bucharest set("Egypt Standard Time",TimeZoneConstants.EGYPT); // (GMT+02:00) Cairo set("FLE Standard Time",TimeZoneConstants.EET); // (GMT+02:00) Helsinki, Kiev, Riga, Sofia, Tallinn, Vilnius set("GTB Standard Time",TimeZoneConstants.EUROPE_ATHENS); // (GMT+02:00) Athens, Istanbul, Minsk set("Israel Standard Time",TimeZoneConstants.ASIA_JERUSALEM); // (GMT+02:00) Jerusalem set("South Africa Standard Time",TimeZoneConstants.AFRICA_JOHANNESBURG); // (GMT+02:00) Harare, Pretoria set("Russian Standard Time",TimeZoneConstants.EUROPE_MOSCOW); // (GMT+03:00) Moscow, St. Petersburg, Volgograd set("Arab Standard Time",TimeZoneConstants.ASIA_KUWAIT); // (GMT+03:00) Kuwait, Riyadh set("E. Africa Standard Time",TimeZoneConstants.AFRICA_NAIROBI); // (GMT+03:00) Nairobi set("Arabic Standard Time",TimeZoneConstants.ASIA_BAGHDAD); // (GMT+03:00) Baghdad set("Iran Standard Time",TimeZoneConstants.ASIA_TEHRAN); // (GMT+03:30) Tehran set("Arabian Standard Time",TimeZoneConstants.ASIA_MUSCAT); // (GMT+04:00) Abu Dhabi, Muscat set("Caucasus Standard Time",TimeZoneConstants.ASIA_YEREVAN); // (GMT+04:00) Baku, Tbilisi, Yerevan set("Transitional Islamic State of Afghanistan Standard Time",TimeZoneConstants.ASIA_KABUL); // (GMT+04:30) Kabul set("Ekaterinburg Standard Time",TimeZoneConstants.ASIA_YEKATERINBURG); // (GMT+05:00) Ekaterinburg set("West Asia Standard Time",TimeZoneConstants.ASIA_KARACHI); // (GMT+05:00) Islamabad, Karachi, Tashkent set("India Standard Time",TimeZoneConstants.IST); // (GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi set("Nepal Standard Time",TimeZoneConstants.ASIA_KATMANDU); // (GMT+05:45) Kathmandu set("Central Asia Standard Time",TimeZoneConstants.ASIA_DHAKA); //(GMT+06:00) Astana, Dhaka set("Sri Lanka Standard Time",TimeZoneConstants.ASIA_COLOMBO); // (GMT+06:00) Sri Jayawardenepura set("N. Central Asia Standard Time",TimeZoneConstants.ASIA_ALMATY); // (GMT+06:00) Almaty, Novosibirsk set("Myanmar Standard Time",TimeZoneConstants.ASIA_RANGOON); // (GMT+06:30) Yangon Rangoon set("S.E. Asia Standard Time",TimeZoneConstants.ASIA_BANGKOK); // (GMT+07:00) Bangkok, Hanoi, Jakarta set("North Asia Standard Time",TimeZoneConstants.ASIA_KRASNOYARSK); // (GMT+07:00) Krasnoyarsk set("China Standard Time",TimeZoneConstants.CTT); // (GMT+08:00) Beijing, Chongqing, Hong Kong SAR, Urumqi set("Singapore Standard Time",TimeZoneConstants.ASIA_SINGAPORE); // (GMT+08:00) Kuala Lumpur, Singapore set("Taipei Standard Time",TimeZoneConstants.ASIA_TAIPEI); // (GMT+08:00) Taipei set("W. Australia Standard Time",TimeZoneConstants.AUSTRALIA_PERTH); // (GMT+08:00) Perth set("North Asia East Standard Time",TimeZoneConstants.ASIA_IRKUTSK); // (GMT+08:00) Irkutsk, Ulaanbaatar set("Korea Standard Time",TimeZoneConstants.ASIA_SEOUL); // (GMT+09:00) Seoul set("Tokyo Standard Time",TimeZoneConstants.ASIA_TOKYO); // (GMT+09:00) Osaka, Sapporo, Tokyo set("Yakutsk Standard Time",TimeZoneConstants.ASIA_YAKUTSK); // (GMT+09:00) Yakutsk set("A.U.S. Central Standard Time",TimeZoneConstants.ACT); // (GMT+09:30) Darwin set("Cen. Australia Standard Time",TimeZoneConstants.ACT); // (GMT+09:30) Adelaide set("A.U.S. Eastern Standard Time",TimeZoneConstants.AET); // (GMT+10:00) Canberra, Melbourne, Sydney set("E. Australia Standard Time",TimeZoneConstants.AET); // (GMT+10:00) Brisbane set("Tasmania Standard Time",TimeZoneConstants.AUSTRALIA_TASMANIA); // (GMT+10:00) Hobart set("Vladivostok Standard Time",TimeZoneConstants.ASIA_VLADIVOSTOK); // (GMT+10:00) Vladivostok set("West Pacific Standard Time",TimeZoneConstants.PACIFIC_GUAM); // (GMT+10:00) Guam, Port Moresby set("Central Pacific Standard Time",TimeZoneConstants.ASIA_MAGADAN); // (GMT+11:00) Magadan, Solomon Islands, New Caledonia set("Fiji Islands Standard Time",TimeZoneConstants.PACIFIC_FIJI); // (GMT+12:00) Fiji Islands, Kamchatka, Marshall Islands set("New Zealand Standard Time",TimeZoneConstants.NZ); // (GMT+12:00) Auckland, Wellington set("Tonga Standard Time",TimeZoneConstants.PACIFIC_TONGATAPU); // (GMT+13:00) Nuku'alofa } private static void set(String name, TimeZone tz) { if(tz==null) return; name=StringUtil.replace(name.trim().toLowerCase(), " ", "", false); IDS.put(name.toLowerCase(), tz); } /** * return the string format of the Timezone * @param timezone * @return */ public static String toString(TimeZone timezone){ return timezone.getID(); } private static String getSupportedTimeZonesAsString() { return List.arrayToList(TimeZone.getAvailableIDs(),", "); } /** * translate timezone string format to a timezone * @param strTimezone * @return */ public static TimeZone toTimeZone(String strTimezone,TimeZone defaultValue){ if(strTimezone==null) return defaultValue; strTimezone=StringUtil.replace(strTimezone.trim().toLowerCase(), " ", "", false); TimeZone tz = (TimeZone) IDS.get(strTimezone); if(tz!=null) return tz; return defaultValue; } public static TimeZone toTimeZone(String strTimezone) throws ExpressionException{ TimeZone tz = toTimeZone(strTimezone, null); if(tz!=null) return tz; throw new ExpressionException("can't cast value ("+strTimezone+") to a TimeZone","supported TimeZones are:"+getSupportedTimeZonesAsString()); } }
package org.lightmare.jpa.datasource; /** * Configuration of JDBC driver classes and database names * * @author levan * */ public abstract class DriverConfig { /** * Caches database driver names and classes * * @author levan * @since 0.0.81-SNAPSHOT */ public static enum Drivers { // Database name and driver class names ORACLE("oracle", "oracle.jdbc.OracleDriver"), // Oracle MYSQL("mysql", "com.mysql.jdbc.Driver"), // MYSQL POSTGRE("postgre", "org.postgresql.Driver"), // PostgreSQL MSSQL("mssql", "com.microsoft.sqlserver.jdbc.SQLServerDriver"), // MSSQL DB2("db2", "com.ibm.db2.jcc.DB2Driver"), // DB2 H2("h2", "org.h2.Driver"), DERBY("derby", "org.apache.derby.jdbc.EmbeddedDriver"); // DERBY // Database names public String name; // Driver class names public String driver; private Drivers(String name, String driver) { this.name = name; this.driver = driver; } } /** * Resolves appropriate JDBC driver class name by database name * * @param name * @return {@link String} */ public static String getDriverName(String name) { String driverName; if (Drivers.ORACLE.name.equals(name)) { driverName = Drivers.ORACLE.driver; } else if (Drivers.MYSQL.name.equals(name)) { driverName = Drivers.MYSQL.driver; } else if (Drivers.POSTGRE.name.equals(name)) { driverName = Drivers.POSTGRE.driver; } else if (Drivers.DB2.name.equals(name)) { driverName = Drivers.DB2.driver; } else if (Drivers.MSSQL.name.equals(name)) { driverName = Drivers.MSSQL.driver; } else if (Drivers.H2.name.equals(name)) { driverName = Drivers.H2.driver; } else if (Drivers.DERBY.name.equals(name)) { driverName = Drivers.DERBY.driver; } else { driverName = null; } return driverName; } public static boolean isOracle(String name) { return Drivers.ORACLE.driver.equals(name); } public static boolean isMySQL(String name) { return Drivers.MYSQL.driver.equals(name); } public static boolean isPostgre(String name) { return Drivers.POSTGRE.driver.equals(name); } public static boolean isDB2(String name) { return Drivers.DB2.driver.equals(name); } public static boolean isMsSQL(String name) { return Drivers.MSSQL.driver.equals(name); } public static boolean isH2(String name) { return Drivers.H2.driver.equals(name); } public static boolean isDerby(String name) { return Drivers.DERBY.driver.equals(name); } }
package org.lightmare.jpa.datasource; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Configuration of JDBC driver classes and database names * * @author levan * @since 0.0.15-SNAPSHOT */ public abstract class DriverConfig { /** * Caches database driver names and classes * * @author levan * @since 0.0.81-SNAPSHOT */ public static enum Drivers { // Database names and associated JDBC driver class names ORACLE("oracle", "oracle.jdbc.OracleDriver"), // Oracle MYSQL("mysql", "com.mysql.jdbc.Driver"), // MYSQL POSTGRE("postgre", "org.postgresql.Driver"), // PostgreSQL MSSQL("mssql", "com.microsoft.sqlserver.jdbc.SQLServerDriver"), // MSSQL DB2("db2", "com.ibm.db2.jcc.DB2Driver"), // DB2 H2("h2", "org.h2.Driver"), HYPERSONIC("hypersonic", "org.hsql.jdbcDriver"), // Hypersonic DERBY("derby", "org.apache.derby.jdbc.EmbeddedDriver"); // DERBY // Database names public String name; // Driver class names public String driver; private Drivers(String name, String driver) { this.name = name; this.driver = driver; } } /** * Resolves appropriate JDBC driver class name by database name * * @param name * @return {@link String} */ public static String getDriverName(String name) { String driverName; Drivers[] drivers = Drivers.values(); Drivers driver; int length = drivers.length; boolean match = Boolean.FALSE; for (int i = CollectionUtils.FIRST_INDEX; i < length && ObjectUtils.notTrue(match); i++) { driver = drivers[i]; match = driver.name.equals(name); if (match) { driverName = driver.driver; } } if (length == 0 || ObjectUtils.notTrue(match)) { driverName = null; } return driverName; } public static boolean isOracle(String name) { return Drivers.ORACLE.driver.equals(name); } public static boolean isMySQL(String name) { return Drivers.MYSQL.driver.equals(name); } public static boolean isPostgre(String name) { return Drivers.POSTGRE.driver.equals(name); } public static boolean isDB2(String name) { return Drivers.DB2.driver.equals(name); } public static boolean isMsSQL(String name) { return Drivers.MSSQL.driver.equals(name); } public static boolean isH2(String name) { return Drivers.H2.driver.equals(name); } public static boolean isDerby(String name) { return Drivers.DERBY.driver.equals(name); } }
package org.lightmare.rest.providers; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.MessageBodyReader; import org.glassfish.jersey.internal.util.collection.MultivaluedStringMap; import org.glassfish.jersey.message.MessageBodyWorkers; import org.glassfish.jersey.server.model.Parameter; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; import org.lightmare.utils.rest.RequestUtils; /** * Translates REST request parameters to java objects * * @author levan * @since 0.0.75-SNAPSHOT */ public class ParamBuilder { private MediaType mediaType; private List<Parameter> parameters; private MessageBodyWorkers workers; private ContainerRequestContext request; private MultivaluedMap<String, String> httpHeaders; private MultivaluedMap<String, String> uriParams; private MessageBodyReader<?> reader; private boolean check; private List<Object> paramsList; // Default length of parameters list (used for MultivaluedMap) private static final int PARAM_VALIES_LENGTH = 1; private ParamBuilder() { } public ParamBuilder(MediaType mediaType, List<Parameter> parameters, MessageBodyWorkers workers, ContainerRequestContext request) { this.mediaType = mediaType; this.parameters = parameters; this.workers = workers; this.request = request; } /** * Creates error message if one of the necessary fields in null * * @return String * @throws IOException */ private String errorOnBuild() throws IOException { String errorMessage; String errorPrefix = "Could not initialize "; String errorClass = this.getClass().getName(); String errorReasonPrefix = " caouse"; String errorReasonSuffix = "is null"; String errorMessageBody; if (mediaType == null) { errorMessageBody = "mediaType"; } else if (parameters == null) { errorMessageBody = "parameters"; } else if (workers == null) { errorMessageBody = "workers"; } else if (request == null) { errorMessageBody = "request"; } else { throw new IOException("Could not find null value"); } errorMessage = new StringBuilder().append(errorPrefix) .append(errorClass).append(errorReasonPrefix) .append(errorMessageBody).append(errorReasonSuffix).toString(); return errorMessage; } /** * Check if one of the necessary fields in null and if it is throws * {@link IOException} with generated error message * * @return <code>boolean</code> * @throws IOException */ private boolean checkOnBuild() throws IOException { boolean valid = ObjectUtils.notNullAll(mediaType, parameters, workers, request); if (ObjectUtils.notTrue(valid)) { String errorMessage = errorOnBuild(); throw new IOException(errorMessage); } return valid; } private boolean check() throws IOException { return ObjectUtils.notTrue(request.hasEntity()) && IOUtils.notAvailable(request.getEntityStream()); } private void copyAll(MultivaluedMap<String, String> from, MultivaluedMap<String, String> to) { for (Map.Entry<String, List<String>> entry : from.entrySet()) { to.addAll(entry.getKey(), entry.getValue()); } } private void addAll(MultivaluedMap<String, String> from, MultivaluedMap<String, String> to) { if (CollectionUtils.valid(from)) { copyAll(from, to); } } /** * Extracts all parameters from {@link ContainerRequestContext} object * * @param request * @return {@link MultivaluedMap}<String, String> */ private MultivaluedMap<String, String> extractParameters( ContainerRequestContext request) { MultivaluedMap<String, String> params = new MultivaluedStringMap(); MultivaluedMap<String, String> exts; boolean decode = Boolean.TRUE; UriInfo uriInfo = request.getUriInfo(); exts = request.getHeaders(); addAll(exts, params); exts = uriInfo.getPathParameters(decode); addAll(exts, params); exts = uriInfo.getQueryParameters(decode); addAll(exts, params); Map<String, Cookie> cookies = request.getCookies(); if (CollectionUtils.valid(cookies)) { for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { params.putSingle(entry.getKey(), entry.getValue().toString()); } } return params; } /** * Converts {@link Parameter} to {@link InputStream} or {@link List} of {@link InputStream} by {@link Parameter} nature * @param parameter * @return {@link Object} */ private Object getEntityStream(Parameter parameter) { Object stream; List<String> paramValues = uriParams.get(parameter.getSourceName()); String value; if (CollectionUtils.valid(paramValues)) { if (paramValues.size() == PARAM_VALIES_LENGTH) { value = CollectionUtils.getFirst(paramValues); stream = RequestUtils.textToStream(value); } else { stream = RequestUtils.textsToStreams(paramValues); } } else { stream = null; } return stream; } /** * Reads {@link InputStream} from passed {@link ContainerRequestContext} for * associated {@link Parameter} instance * * @param request * @param parameter * @return {@link Object} */ private Object getEntityStream(ContainerRequestContext request, Parameter parameter) { Object entityStream; if (check) { entityStream = getEntityStream(parameter); } else { entityStream = request.getEntityStream(); } return entityStream; } private boolean available(InputStream entityStream, Parameter parameter) { return ObjectUtils.notNullAll(reader, entityStream) && reader.isReadable(parameter.getRawType(), parameter.getType(), parameter.getAnnotations(), mediaType); } private void close(InputStream entityStream) throws IOException { if (check) { IOUtils.close(entityStream); } } /** * Extracts parameter from passed {@link InputStream} (writes appropriate * value to {@link Object} instance) * * @param parameter * @param entityStream * @return {@link Object} * @throws IOException */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Object extractParam(Parameter parameter, InputStream entityStream) throws IOException { Object param; try { param = reader.readFrom((Class) parameter.getRawType(), parameter.getType(), parameter.getAnnotations(), mediaType, httpHeaders, entityStream); } finally { close(entityStream); } return param; } private void addParam(Object param) { if (ObjectUtils.notNull(param)) { paramsList.add(param); } } /** * Initializes and adds null parameter to {@link List} of parameters * * @param parameter */ private void addNullParam(Parameter parameter) { Class<?> paramType = parameter.getRawType(); Object nullParam; if (paramType.isPrimitive()) { nullParam = MetaUtils.getDefault(paramType); } else { nullParam = null; } paramsList.add(nullParam); } /** * Reads from {@link InputStream} to java {@link Object} instance * * @param entityStream * @param parameter * @throws IOException */ private void readFromStream(InputStream entityStream, Parameter parameter) throws IOException { boolean valid = available(entityStream, parameter); if (valid) { Object param = extractParam(parameter, entityStream); addParam(param); } } /** * Reads from {@link InputStream} or {@link List} of {@link InputStream} in * case that parameters are multi valued * * @param stream * @param parameter * @throws IOException */ private void fillParamList(Object stream, Parameter parameter) throws IOException { InputStream entityStream; if (stream instanceof InputStream) { entityStream = (InputStream) stream; readFromStream(entityStream, parameter); } else if (stream instanceof List) { List<InputStream> streamsList = ObjectUtils.cast(stream); Iterator<InputStream> streams = streamsList.iterator(); while (streams.hasNext()) { entityStream = streams.next(); readFromStream(entityStream, parameter); } } } /** * Extracts parameters from {@link ContainerRequestContext} instance * * @return {@link List}<Object> * @throws IOException */ public List<Object> extractParams() throws IOException { paramsList = new ArrayList<Object>(); check = check(); httpHeaders = request.getHeaders(); uriParams = extractParameters(request); Object stream; for (Parameter parameter : parameters) { reader = RequestUtils.getReader(workers, parameter, mediaType); stream = getEntityStream(request, parameter); if (ObjectUtils.notNull(stream)) { fillParamList(stream, parameter); } else { addNullParam(parameter); } } return paramsList; } /** * Builder class to configure and initialize {@link ParamBuilder} instance * * @author Levan * */ public static final class Builder { private ParamBuilder target; public Builder() { target = new ParamBuilder(); } /** * Adds {@link MediaType} necessary parameter * * @param mediaType * @return {@link Builder} */ public ParamBuilder.Builder setMediaType(MediaType mediaType) { target.mediaType = mediaType; return this; } /** * Adds {@link List}<Parameter> necessary parameter * * @param parameters * @return {@link Builder} */ public ParamBuilder.Builder setParameters(List<Parameter> parameters) { target.parameters = parameters; return this; } /** * Adds {@link MessageBodyWorkers} necessary parameter * * @param workers * @return {@link Builder} */ public ParamBuilder.Builder setWorkers(MessageBodyWorkers workers) { target.workers = workers; return this; } /** * Adds {@link ContainerRequestContext} necessary parameter * * @param request * @return {@link Builder} */ public ParamBuilder.Builder setRequest(ContainerRequestContext request) { target.request = request; return this; } public ParamBuilder build() throws IOException { // TODO Check if there is a another way to create ParamBuilder // instance or // checks all parameters not to be null target.checkOnBuild(); return target; } } }
package br.edu.ladoss.form; import javax.ws.rs.FormParam; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.annotations.providers.multipart.PartType; public class FileUploadForm { @FormParam("uploadedFile") @PartType(MediaType.APPLICATION_OCTET_STREAM) private byte[] data; @FormParam("fileName") @PartType(MediaType.TEXT_PLAIN +";charset=UTF-8") private String fileName; @FormParam("idPessoa") @PartType(MediaType.TEXT_PLAIN) private int idPessoa; public FileUploadForm() {} public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public int getIdPessoa() { return idPessoa; } public void setIdPessoa(int idPessoa) { this.idPessoa = idPessoa; } }
package com.greenaddress.abcore; import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Packages { final static String GLIBC_MAJOR = "2.25"; final static String CORE_V = "0.15.1"; private final static String GLIBC_MINOR = "4"; private final static String CORE_URL = "https://bitcoin.org/bin/%s"; private final static String KNOTS_CORE_URL = "https://bitcoinknots.org/files/0.15.x/%s"; final static List<PkgH> ARCH_PACKAGES = new ArrayList<>( Arrays.asList( new PkgH(String.format("glibc/glibc-%s-%s", GLIBC_MAJOR, GLIBC_MINOR), Arrays.asList( "armhf8c1e542e0fac554c29a57301c0daf2fde68b0425ddd9b96b029f766dc440833c", "arm642d08aa49b527817528b6e75043da5ae264448b541043ccc2af9ca52086aabafd", "amd64efd42f69a712a4202a2cfd1dd7763bb21eee669242ea4038cc971af147f0c33a", "i386e00bb8779db964581e17dcc93de9158607e2ca7a4397b36e59ba84c673d67258" )), new PkgH("gcc-libs/gcc-libs-7.1.1-2", Arrays.asList( "armhf16c07c6b81cc9b07e42356f680cdf42b3fb6cc3ffdf4ab47cfdd163e077f1882", "arm64c81f122d275171fc1c77dd8871f6fa03ad193fd314d802fc64e7265c874cb1ed", "amd64f9d11c0b924638a0ac4100c006997f4f0ca102750c0b4c222f19ab00942a579a", "i386fe4832dab14c7ebdb13e49e1568538a8f3bdb2d7530e7d41265bdde2d29ce845" )) )); final static PkgH CORE_PACKAGE = new PkgH(String.format("bitcoin-core-%s/bitcoin-%s-", CORE_V, CORE_V), Arrays.asList( "armhfceba092c9a390082ff184c8d82a24bc34d7f9b421dc5c1e6847fcf769541f305", "arm64d64d2e27cad78bbd2a0268bdaa9efa3f1eca670a4fab462b5e851699c780e3a0", "amd64387c2e12c67250892b0814f26a5a38f837ca8ab68c86af517f975a2a2710225b", "i386231e4c9f5cf4ba977dbaf118bf38b0fde4d50ab7b9efd65bee6647fb14035a2c" )); final static PkgH KNOTS_CORE_PACKAGE = new PkgH(String.format("%s.knots20171111/bitcoin-%s.knots20171111-", CORE_V, CORE_V), Arrays.asList( "armhfa69398ec03b6c1ca8fca6ab8140759bc52175c6d0efed825c5f7b807f16eb672", "arm6469ca02bcdfd1cb005069d5cd9586d032e308d304134235d7c4dd450ff830b12c", "amd641f12e32e18974bdd6f820f01596c0b2789278f53425f3cbc8d7508b0617c76ca", "i3863aff13e30b00bf4ae6aa24c88c3b7dbd56c918d7b7b3b260d2e4ce9f50973e21" )); private static String getRepo(final String arch) { if (arch.equals("amd64") || arch.equals("i386")) return "https://archive.archlinux.org/packages"; else return "http://tardis.tiny-vps.com/aarm/packages"; } static String getPackageUrl(final Packages.PkgH pkg, final String arch) { final boolean isArmArchitecture = !arch.equals("amd64") && !arch.equals("i386"); final String osArch = Utils.getArchLinuxArchitecture(arch); final String fileArch = arch.equals("armhf") ? "armv7h" : osArch; final String template = "%s/%s/%s-" + (isArmArchitecture ? fileArch : osArch) + ".pkg.tar.xz"; final String repo = getRepo(arch); return String.format(template, repo, pkg.pkg.charAt(0), pkg.pkg); } static String getCorePackageUrl(final Packages.PkgH pkg, final String arch) { final String packageName = arch == null ? Utils.getCorePkgsName(): Utils.getCorePkgsArch(arch); final String path = String.format("%s%s.tar.gz", pkg.pkg, packageName); if (pkg.pkg.contains("bitcoin-core")) return String.format(Packages.CORE_URL, path); else if (pkg.pkg.contains("knots")) return String.format(Packages.KNOTS_CORE_URL, path); throw new RuntimeException("Package not found"); } static class PkgH { final String pkg; final List<String> archHash; PkgH(final String pkg, final List<String> archHash) { this.pkg = pkg; this.archHash = archHash; } } }
package org.encuestame.web.beans.admon; import java.io.Serializable; import java.util.Collection; import java.util.Date; import org.encuestame.web.beans.MasterBean; /** * Unit Use rBean. * @author Picado, Juan juan@encuestame.org * @since 27/04/2009 * @version $Id$ */ public class UnitUserBean extends MasterBean implements Serializable { private static final long serialVersionUID = -6690522000664394521L; private Integer id; private String email; private String name; private String username; private Boolean status; private String password; private String inviteCode; private Date dateNew; private Long primaryUserId; private Boolean publisher; private Collection<UnitGroupBean> listGroups; private Collection<UnitPermission> listPermission; /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the status */ public Boolean getStatus() { return status; } /** * @param status the status to set */ public void setStatus(Boolean status) { this.status = status; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the inviteCode */ public String getInviteCode() { return inviteCode; } /** * @param inviteCode the inviteCode to set */ public void setInviteCode(String inviteCode) { this.inviteCode = inviteCode; } /** * @return the dateNew */ public Date getDateNew() { return dateNew; } /** * @param dateNew the dateNew to set */ public void setDateNew(Date dateNew) { this.dateNew = dateNew; } /** * @return the publisher */ public Boolean getPublisher() { return publisher; } /** * @param publisher the publisher to set */ public void setPublisher(Boolean publisher) { this.publisher = publisher; } /** * @return the listGroups */ public Collection<UnitGroupBean> getListGroups() { return listGroups; } /** * @param listGroups the listGroups to set */ public void setListGroups(Collection<UnitGroupBean> listGroups) { this.listGroups = listGroups; } public Collection<UnitPermission> getListPermission() { return listPermission; } public void setListPermission(Collection<UnitPermission> listPermission) { this.listPermission = listPermission; } /** * @return the primaryUserId */ public Long getPrimaryUserId() { return primaryUserId; } /** * @param primaryUserId the primaryUserId to set */ public void setPrimaryUserId(Long primaryUserId) { this.primaryUserId = primaryUserId; } }
package com.pr0gramm.app.ui; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.view.menu.ActionMenuItem; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.Window; import com.akodiakson.sdk.simple.Sdk; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.pr0gramm.app.ActivityComponent; import com.pr0gramm.app.BuildConfig; import com.pr0gramm.app.R; import com.pr0gramm.app.Settings; import com.pr0gramm.app.feed.FeedFilter; import com.pr0gramm.app.feed.FeedType; import com.pr0gramm.app.services.BookmarkService; import com.pr0gramm.app.services.SingleShotService; import com.pr0gramm.app.services.Track; import com.pr0gramm.app.services.UserService; import com.pr0gramm.app.sync.SyncBroadcastReceiver; import com.pr0gramm.app.ui.base.BaseAppCompatActivity; import com.pr0gramm.app.ui.dialogs.UpdateDialogFragment; import com.pr0gramm.app.ui.fragments.DrawerFragment; import com.pr0gramm.app.ui.fragments.FavoritesFragment; import com.pr0gramm.app.ui.fragments.FeedFragment; import com.pr0gramm.app.ui.fragments.ItemWithComment; import com.pr0gramm.app.ui.fragments.PostPagerNavigation; import com.trello.rxlifecycle.RxLifecycle; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.inject.Inject; import butterknife.Bind; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Actions; import static com.google.common.base.MoreObjects.firstNonNull; import static com.pr0gramm.app.services.ThemeHelper.theme; import static com.pr0gramm.app.ui.dialogs.ErrorDialogFragment.defaultOnError; import static com.pr0gramm.app.ui.fragments.BusyDialogFragment.busyDialog; import static com.pr0gramm.app.util.Noop.noop; /** * This is the main class of our pr0gramm app. */ public class MainActivity extends BaseAppCompatActivity implements DrawerFragment.OnFeedFilterSelected, FragmentManager.OnBackStackChangedListener, ScrollHideToolbarListener.ToolbarActivity, MainActionHandler, PermissionHelperActivity { // we use this to propagate a fake-home event to the fragments. public static final int ID_FAKE_HOME = android.R.id.list; private final Handler handler = new Handler(Looper.getMainLooper()); @Bind(R.id.drawer_layout) DrawerLayout drawerLayout; @Bind(R.id.toolbar) Toolbar toolbar; @Nullable @Bind(R.id.toolbar_container) View toolbarContainer; @Bind(R.id.content) View contentContainer; @Inject UserService userService; @Inject BookmarkService bookmarkService; @Inject Settings settings; @Inject SharedPreferences shared; @Inject SingleShotService singleShotService; @Inject PermissionHelper permissionHelper; private ActionBarDrawerToggle drawerToggle; private ScrollHideToolbarListener scrollHideToolbarListener; private boolean startedWithIntent; @Override public void onCreate(Bundle savedInstanceState) { if (Sdk.isAtLeastLollipop()) { // enable transition on lollipop and above supportRequestWindowFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); } setTheme(theme().translucentStatus); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // use toolbar as action bar setSupportActionBar(toolbar); // and hide it away on scrolling scrollHideToolbarListener = new ScrollHideToolbarListener( firstNonNull(toolbarContainer, toolbar)); // prepare drawer layout drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name); drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); drawerLayout.setDrawerListener(new ForwardDrawerListener(drawerToggle) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); // i am not quite sure if everyone knows that there is a drawer to open. Track.drawerOpened(); } }); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); drawerToggle.syncState(); // listen to fragment changes getSupportFragmentManager().addOnBackStackChangedListener(this); if (savedInstanceState == null) { createDrawerFragment(); Intent intent = getIntent(); if (intent == null || Intent.ACTION_MAIN.equals(intent.getAction())) { // load feed-fragment into view gotoFeedFragment(defaultFeedFilter(), true); } else { startedWithIntent = true; onNewIntent(intent); } } if (singleShotService.firstTimeInVersion("changelog")) { ChangeLogDialog dialog = new ChangeLogDialog(); dialog.show(getSupportFragmentManager(), null); } else if (shouldShowFeedbackReminder()) { //noinspection ResourceType Snackbar.make(contentContainer, R.string.feedback_reminder, 10000) .setAction(R.string.okay, noop) .show(); } else { // start the update check again UpdateDialogFragment.checkForUpdates(this, false); } addOriginalContentBookmarkOnce(); } private boolean shouldShowFeedbackReminder() { // By design it is | and not ||. We want both conditions to // be evaluated for the sideeffects return settings.useBetaChannel() && (singleShotService.firstTimeInVersion("hint_feedback_reminder") | singleShotService.firstTimeToday("hint_feedback_reminder")); } @Override protected void injectComponent(ActivityComponent appComponent) { appComponent.inject(this); } /** * Adds a bookmark if there currently are no bookmarks. */ private void addOriginalContentBookmarkOnce() { if (!singleShotService.isFirstTime("add_original_content_bookmarks")) return; bookmarkService.get().first().subscribe(bookmarks -> { if (bookmarks.isEmpty()) { bookmarkService.create(new FeedFilter() .withFeedType(FeedType.PROMOTED) .withTags("original content")); } }, Actions.empty()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (!Intent.ACTION_VIEW.equals(intent.getAction())) return; handleUri(intent.getData()); } @Override protected void onDestroy() { getSupportFragmentManager().removeOnBackStackChangedListener(this); try { super.onDestroy(); } catch (RuntimeException ignored) { } } @Override public void onBackStackChanged() { updateToolbarBackButton(); updateActionbarTitle(); DrawerFragment drawer = getDrawerFragment(); if (drawer != null) { FeedFilter currentFilter = getCurrentFeedFilter(); // show the current item in the drawer drawer.updateCurrentFilters(currentFilter); } if (BuildConfig.DEBUG) { printFragmentStack(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Settings.VolumeNavigationType navigationType = settings.volumeNavigation(); Fragment fragment = getCurrentFragment(); if (fragment instanceof PostPagerNavigation && navigationType != Settings.VolumeNavigationType.DISABLED) { PostPagerNavigation pager = (PostPagerNavigation) fragment; if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { if (navigationType == Settings.VolumeNavigationType.UP) { pager.moveToNext(); } else { pager.moveToPrev(); } return true; } if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { if (navigationType == Settings.VolumeNavigationType.UP) { pager.moveToPrev(); } else { pager.moveToNext(); } return true; } } return super.onKeyDown(keyCode, event); } /** * Prints the current fragmetn stack. This should only be invoked in debug builds. */ private void printFragmentStack() { List<String> names = new ArrayList<>(); names.add("root"); for (int idx = 0; idx < getSupportFragmentManager().getBackStackEntryCount(); idx++) { FragmentManager.BackStackEntry entry = getSupportFragmentManager().getBackStackEntryAt(idx); names.add(entry.getName()); } logger.info("stack: {}", Joiner.on(" -> ").join(names)); } private void updateActionbarTitle() { ActionBar bar = getSupportActionBar(); if (bar != null) { FeedFilter filter = getCurrentFeedFilter(); if (filter == null) { bar.setTitle(R.string.pr0gramm); bar.setSubtitle(null); } else { FeedFilterFormatter.FeedTitle feed = FeedFilterFormatter.format(this, filter); bar.setTitle(feed.title); bar.setSubtitle(feed.subtitle); } } } /** * Returns the current feed filter. Might be null, if no filter could be detected. */ @Nullable private FeedFilter getCurrentFeedFilter() { // get the filter of the visible fragment. FeedFilter currentFilter = null; Fragment fragment = getCurrentFragment(); if (fragment instanceof FilterFragment) { currentFilter = ((FilterFragment) fragment).getCurrentFilter(); } return currentFilter; } private Fragment getCurrentFragment() { return getSupportFragmentManager().findFragmentById(R.id.content); } private boolean shouldClearOnIntent() { return !(getCurrentFragment() instanceof FavoritesFragment) && getSupportFragmentManager().getBackStackEntryCount() == 0; } private void updateToolbarBackButton() { drawerToggle.setDrawerIndicatorEnabled(shouldClearOnIntent()); drawerToggle.syncState(); } private void createDrawerFragment() { DrawerFragment fragment = new DrawerFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.left_drawer, fragment) .commit(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!drawerToggle.isDrawerIndicatorEnabled()) { if (item.getItemId() == android.R.id.home) { if (!dispatchFakeHomeEvent(item)) onBackPressed(); return true; } } return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } private boolean dispatchFakeHomeEvent(MenuItem item) { return onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, new ActionMenuItem( this, item.getGroupId(), ID_FAKE_HOME, 0, item.getOrder(), item.getTitle())); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawers(); return; } // at the end, go back to the "top" page before stopping everything. if (getSupportFragmentManager().getBackStackEntryCount() == 0 && !startedWithIntent) { FeedFilter filter = getCurrentFeedFilter(); if (filter != null && !isDefaultFilter(filter)) { gotoFeedFragment(defaultFeedFilter(), true); return; } } super.onBackPressed(); } private boolean isDefaultFilter(FeedFilter filter) { return defaultFeedFilter().equals(filter); } @Override protected void onResume() { super.onResume(); onBackStackChanged(); } @Override protected void onStart() { super.onStart(); // schedule a sync operation every minute Observable.interval(0, 1, TimeUnit.MINUTES, AndroidSchedulers.mainThread()) .compose(RxLifecycle.bindActivity(lifecycle())) .subscribe(event -> SyncBroadcastReceiver.syncNow(MainActivity.this)); } @Override public void onLogoutClicked() { drawerLayout.closeDrawers(); Track.logout(); userService.logout() .compose(bindToLifecycle()) .lift(busyDialog(this)) .doOnCompleted(() -> { // show a short information. Snackbar.make(drawerLayout, R.string.logout_successful_hint, Snackbar.LENGTH_SHORT) .setAction(R.string.okay, noop) .show(); // reset everything! gotoFeedFragment(defaultFeedFilter(), true); }) .subscribe(Actions.empty(), defaultOnError()); } private FeedFilter defaultFeedFilter() { FeedType type = settings.feedStartAtNew() ? FeedType.NEW : FeedType.PROMOTED; return new FeedFilter().withFeedType(type); } @Override public void onFeedFilterSelectedInNavigation(FeedFilter filter) { gotoFeedFragment(filter, true); drawerLayout.closeDrawers(); } @Override public void onOtherNavigationItemClicked() { drawerLayout.closeDrawers(); } @Override public void onNavigateToFavorites(String username) { // move to new fragment FavoritesFragment fragment = FavoritesFragment.newInstance(username); moveToFragment(fragment, true); drawerLayout.closeDrawers(); } @Override public void onUsernameClicked() { Optional<String> name = userService.getName(); if (name.isPresent()) { FeedFilter filter = new FeedFilter() .withFeedType(FeedType.NEW) .withUser(name.get()); gotoFeedFragment(filter, false); } drawerLayout.closeDrawers(); } @Override public void onFeedFilterSelected(FeedFilter filter) { gotoFeedFragment(filter, false); } @Override public void pinFeedFilter(FeedFilter filter, String title) { bookmarkService.create(filter, title).subscribe(Actions.empty(), defaultOnError()); drawerLayout.openDrawer(GravityCompat.START); } private void gotoFeedFragment(FeedFilter newFilter, boolean clear) { gotoFeedFragment(newFilter, clear, Optional.absent()); } private void gotoFeedFragment(FeedFilter newFilter, boolean clear, Optional<ItemWithComment> start) { moveToFragment(FeedFragment.newInstance(newFilter, start), clear); } private void moveToFragment(Fragment fragment, boolean clear) { if (isFinishing()) return; if (clear) { clearBackStack(); } // and show the fragment @SuppressLint("CommitTransaction") FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction() .replace(R.id.content, fragment); if (!clear) { logger.info("Adding fragment {} to backstrack", fragment.getClass().getName()); transaction.addToBackStack("Feed" + fragment); } try { transaction.commit(); } catch (IllegalStateException ignored) { } // trigger a back-stack changed after adding the fragment. handler.post(this::onBackStackChanged); } private DrawerFragment getDrawerFragment() { return (DrawerFragment) getSupportFragmentManager() .findFragmentById(R.id.left_drawer); } private void clearBackStack() { try { getSupportFragmentManager().popBackStackImmediate( null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } catch (Exception ignored) { } } @Override public ScrollHideToolbarListener getScrollHideToolbarListener() { return scrollHideToolbarListener; } /** * Handles a uri to something on pr0gramm * * @param uri The uri to handle */ private void handleUri(Uri uri) { Optional<FeedFilterWithStart> result = FeedFilterWithStart.fromUri(uri); if (result.isPresent()) { FeedFilter filter = result.get().getFilter(); Optional<ItemWithComment> start = result.get().getStart(); boolean clear = shouldClearOnIntent(); gotoFeedFragment(filter, clear, start); } else { gotoFeedFragment(defaultFeedFilter(), true); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public Observable<Void> requirePermission(String permission) { return permissionHelper.requirePermission(permission); } public static void open(Context context) { Intent intent = new Intent(context, MainActivity.class); context.startActivity(intent); } }
package org.ndexbio.rest.services; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import org.ndexbio.common.access.NetworkAOrientDBDAO; import org.ndexbio.common.exceptions.NdexException; import org.ndexbio.model.object.network.BaseTerm; import org.ndexbio.model.object.network.Network; import org.ndexbio.model.object.network.NetworkSummary; import org.ndexbio.common.models.object.NetworkQueryParameters; import org.ndexbio.rest.annotations.ApiDoc; @Path("/network") public class NetworkAService extends NdexService { private NetworkAOrientDBDAO dao = NetworkAOrientDBDAO.getInstance(); public NetworkAService(@Context HttpServletRequest httpRequest) { super(httpRequest); } @GET @Path("/{networkId}/term/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Returns a block of terms from the network specified by networkId as a list. " + "'blockSize' specifies the maximum number of terms to retrieve in the block, " + "'skipBlocks' specifies the number of blocks to skip.") public List<BaseTerm> getTerms( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { return dao.getTerms(this.getLoggedInUser(), networkId, skipBlocks, blockSize); } @GET @Path("/{networkId}/edge/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Returns a network based on a set of edges selected from the network " + "specified by networkId. The returned network is fully poplulated and " + "'self-sufficient', including all nodes, terms, supports, citations, " + "and namespaces. The query selects a number of edges specified by the " + "'blockSize' parameter, starting at an offset specified by the 'skipBlocks' parameter.") public Network getEdges( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { return dao.getEdges(this.getLoggedInUser(), networkId, skipBlocks, blockSize); } @POST @Path("/{networkId}/query/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Returns a network based on a block of edges retrieved by the POSTed queryParameters " + "from the network specified by networkId. The returned network is fully poplulated and " + "'self-sufficient', including all nodes, terms, supports, citations, and namespaces.") public Network queryNetwork( @PathParam("networkId") final String networkId, final NetworkQueryParameters queryParameters, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { return dao.queryForSubnetwork(this.getLoggedInUser(), networkId, queryParameters, skipBlocks, blockSize); } @POST @Path("/search/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Returns a list of NetworkDescriptors based on POSTed NetworkQuery. The allowed NetworkQuery subtypes "+ "for v1.0 will be NetworkSimpleQuery and NetworkMembershipQuery. 'blockSize' specifies the number of " + "NetworkDescriptors to retrieve in each block, 'skipBlocks' specifies the number of blocks to skip.") public List<NetworkSummary> searchNetwork( final NetworkQueryParameters queryParameters, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { return null ; } }
package org.dcache.xdr; import org.dcache.utils.net.InetSocketAddresses; import org.dcache.xdr.gss.GssProtocolFilter; import org.dcache.xdr.gss.GssSessionManager; import org.dcache.xdr.portmap.GenericPortmapClient; import org.dcache.xdr.portmap.OncPortmapClient; import org.dcache.xdr.portmap.OncRpcPortmap; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.GrizzlyFuture; import org.glassfish.grizzly.PortRange; import org.glassfish.grizzly.SocketBinder; import org.glassfish.grizzly.Transport; import org.glassfish.grizzly.filterchain.FilterChain; import org.glassfish.grizzly.filterchain.FilterChainBuilder; import org.glassfish.grizzly.filterchain.TransportFilter; import org.glassfish.grizzly.jmxbase.GrizzlyJmxManager; import org.glassfish.grizzly.nio.transport.TCPNIOTransport; import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; import org.glassfish.grizzly.nio.transport.UDPNIOTransport; import org.glassfish.grizzly.nio.transport.UDPNIOTransportBuilder; import org.glassfish.grizzly.strategies.SameThreadIOStrategy; import org.glassfish.grizzly.threadpool.ThreadPoolConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static org.dcache.xdr.GrizzlyUtils.getSelectorPoolCfg; import static org.dcache.xdr.GrizzlyUtils.rpcMessageReceiverFor; import static org.dcache.xdr.GrizzlyUtils.transportFor; public class OncRpcSvc { private final static Logger _log = LoggerFactory.getLogger(OncRpcSvc.class); private final int _backlog; private final boolean _publish; private final PortRange _portRange; private final String _bindAddress; private final List<Transport> _transports = new ArrayList<Transport>(); private final Set<Connection<InetSocketAddress>> _boundConnections = new HashSet<Connection<InetSocketAddress>>(); private final ExecutorService _requestExecutor; public enum IoStrategy { SAME_THREAD, WORKER_THREAD } private final ReplyQueue<Integer, RpcReply> _replyQueue = new ReplyQueue<Integer, RpcReply>(); /** * Handle RPCSEC_GSS */ private final GssSessionManager _gssSessionManager; /** * mapping of registered programs. */ private final Map<OncRpcProgram, RpcDispatchable> _programs = new ConcurrentHashMap<OncRpcProgram, RpcDispatchable>(); /** * Create new RPC service with defined configuration. * @param builder to build this service */ OncRpcSvc(OncRpcSvcBuilder builder) { _publish = builder.isAutoPublish(); final int protocol = builder.getProtocol(); if ((protocol & (IpProtocolType.TCP | IpProtocolType.UDP)) == 0) { throw new IllegalArgumentException("TCP or UDP protocol have to be defined"); } IoStrategy ioStrategy = builder.getIoStrategy(); ThreadPoolConfig selectorPoolConfig = getSelectorPoolCfg(ioStrategy); if ((protocol & IpProtocolType.TCP) != 0) { final TCPNIOTransport tcpTransport = TCPNIOTransportBuilder .newInstance() .setReuseAddress(true) .setIOStrategy(SameThreadIOStrategy.getInstance()) .setSelectorThreadPoolConfig(selectorPoolConfig) .build(); _transports.add(tcpTransport); } if ((protocol & IpProtocolType.UDP) != 0) { final UDPNIOTransport udpTransport = UDPNIOTransportBuilder .newInstance() .setReuseAddress(true) .setIOStrategy(SameThreadIOStrategy.getInstance()) .setSelectorThreadPoolConfig(selectorPoolConfig) .build(); _transports.add(udpTransport); } _portRange = new PortRange(builder.getMinPort(), builder.getMaxPort()); _backlog = builder.getBacklog(); _bindAddress = builder.getBindAddress(); if (builder.isWithJMX()) { final GrizzlyJmxManager jmxManager = GrizzlyJmxManager.instance(); for (Transport t : _transports) { jmxManager.registerAtRoot(t.getMonitoringConfig().createManagementObject(), t.getName() + "-" + _portRange); } } _requestExecutor = builder.getWorkerThreadExecutorService(); _gssSessionManager = builder.getGssSessionManager(); } /** * Register a new PRC service. Existing registration will be overwritten. * * @param prog program number * @param handler RPC requests handler. */ public void register(OncRpcProgram prog, RpcDispatchable handler) { _log.info("Registering new program {} : {}", prog, handler); _programs.put(prog, handler); } /** * Unregister program. * * @param prog */ public void unregister(OncRpcProgram prog) { _log.info("Unregistering program {}", prog); _programs.remove(prog); } /** * Add programs to existing services. * @param services */ public void setPrograms(Map<OncRpcProgram, RpcDispatchable> services) { _programs.putAll(services); } /** * Register services in portmap. * * @throws IOException * @throws UnknownHostException */ private void publishToPortmap(Connection<InetSocketAddress> connection, Set<OncRpcProgram> programs) throws IOException { OncRpcClient rpcClient = new OncRpcClient(InetAddress.getByName(null), IpProtocolType.UDP, OncRpcPortmap.PORTMAP_PORT); XdrTransport transport = rpcClient.connect(); try { OncPortmapClient portmapClient = new GenericPortmapClient(transport); String username = System.getProperty("user.name"); Transport t = connection.getTransport(); String uaddr = InetSocketAddresses.uaddrOf(connection.getLocalAddress()); for (OncRpcProgram program : programs) { try { if (t instanceof TCPNIOTransport) { portmapClient.setPort(program.getNumber(), program.getVersion(), "tcp", uaddr, username); } if (t instanceof UDPNIOTransport) { portmapClient.setPort(program.getNumber(), program.getVersion(), "udp", uaddr, username); } } catch (OncRpcException ex) { _log.error("Failed to register program", ex); } } } catch (RpcProgUnavailable e) { _log.warn("Failed to register at portmap: ", e.getMessage()); } finally { rpcClient.close(); } } /** * UnRegister services in portmap. * * @throws IOException * @throws UnknownHostException */ private void clearPortmap(Set<OncRpcProgram> programs) throws IOException { OncRpcClient rpcClient = new OncRpcClient(InetAddress.getByName(null), IpProtocolType.UDP, OncRpcPortmap.PORTMAP_PORT); XdrTransport transport = rpcClient.connect(); try { OncPortmapClient portmapClient = new GenericPortmapClient(transport); String username = System.getProperty("user.name"); for (OncRpcProgram program : programs) { try { portmapClient.unsetPort(program.getNumber(), program.getVersion(), username); } catch (OncRpcException ex) { _log.info("Failed to unregister program {}", ex.getMessage()); } } } catch (RpcProgUnavailable e) { _log.info("portmap service not available"); } finally { rpcClient.close(); } } public void start() throws IOException { if(_publish) { clearPortmap(_programs.keySet()); } for (Transport t : _transports) { FilterChainBuilder filterChain = FilterChainBuilder.stateless(); filterChain.add(new TransportFilter()); filterChain.add(rpcMessageReceiverFor(t)); filterChain.add(new RpcProtocolFilter(_replyQueue)); // use GSS if configures if (_gssSessionManager != null) { filterChain.add(new GssProtocolFilter(_gssSessionManager)); } filterChain.add(new RpcDispatcher(_requestExecutor, _programs)); final FilterChain filters = filterChain.build(); t.setProcessor(filters); Connection<InetSocketAddress> connection = ((SocketBinder) t).bind(_bindAddress, _portRange, _backlog); t.start(); _boundConnections.add(connection); if (_publish) { publishToPortmap(connection, _programs.keySet()); } } } public void stop() throws IOException { if (_publish) { clearPortmap(_programs.keySet()); } for (Transport t : _transports) { t.shutdownNow(); } _requestExecutor.shutdown(); } public void stop(long gracePeriod, TimeUnit timeUnit) throws IOException { if (_publish) { clearPortmap(_programs.keySet()); } List<GrizzlyFuture<Transport>> transportsShuttingDown = new ArrayList<GrizzlyFuture<Transport>>(); for (Transport t : _transports) { transportsShuttingDown.add(t.shutdown(gracePeriod, timeUnit)); } for (GrizzlyFuture<Transport> transportShuttingDown : transportsShuttingDown) { try { transportShuttingDown.get(); } catch (Exception e) { _log.warn("Exception while waiting for transport to shut down gracefully",e); } } _requestExecutor.shutdown(); } /** * Returns the address of the endpoint this service is bound to, * or <code>null</code> if it is not bound yet. * @param protocol * @return a {@link InetSocketAddress} representing the local endpoint of * this service, or <code>null</code> if it is not bound yet. */ public InetSocketAddress getInetSocketAddress(int protocol) { Class< ? extends Transport> transportClass = transportFor(protocol); for (Connection<InetSocketAddress> connection: _boundConnections) { if(connection.getTransport().getClass() == transportClass) return connection.getLocalAddress(); } return null; } }
package net.fortuna.ical4j.model; /** * Provides access to the configured <code>TimeZoneRegistry</code> instance. * Alternative factory implementations may be specified via the following * system property: * <pre>net.fortuna.ical4j.timezone.registry=&lt;factory_class_name&gt;</pre> * @author Ben Fortuna */ public abstract class TimeZoneRegistryFactory { /** * The system property used to specify an alternate * <code>TimeZoneRegistryFactory</code> implementation. */ public static final String KEY_FACTORY_CLASS = "net.fortuna.ical4j.timezone.registry"; private static TimeZoneRegistryFactory instance; static { try { Class factoryClass = Class.forName(System.getProperty(KEY_FACTORY_CLASS)); instance = (TimeZoneRegistryFactory) factoryClass.newInstance(); } catch (Exception e) { instance = new DefaultTimeZoneRegistryFactory(); } } /** * @return */ public static TimeZoneRegistryFactory getInstance() { return instance; } /** * Returns a new instance of the configured <code>TimeZoneRegistry</code>. * @return a timezone registry instance */ public abstract TimeZoneRegistry createRegistry(); }
package com.t28.rxweather.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.t28.rxweather.request.ForecastRequest; import com.t28.rxweather.util.CollectionUtils; import com.t28.rxweather.volley.RxSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import rx.Observable; @JsonDeserialize(builder = Forecast.Builder.class) public class Forecast implements Model { private final City mCity; private final List<Weather> mWeathers; private Forecast(Builder builder) { mCity = builder.mCity; if (CollectionUtils.isEmpty(builder.mWeathers)) { mWeathers = Collections.emptyList(); } else { mWeathers = new ArrayList<>(builder.mWeathers); } } @Override public boolean isValid() { return true; } public City getCity() { return mCity; } public List<Weather> getWeathers() { return new ArrayList<>(mWeathers); } public static Observable<Forecast> findByName(RxSupport support, String name) { final ForecastRequest request = new ForecastRequest.Builder("") .setCityName(name) .build(); return support.createObservableRequest(request); } public static Observable<Forecast> findByCoordinate(RxSupport support, Coordinate coordinate) { final ForecastRequest request = new ForecastRequest.Builder("") .setLat(coordinate.getLat()) .setLon(coordinate.getLon()) .build(); return support.createObservableRequest(request); } @JsonPOJOBuilder(withPrefix = "set") @JsonIgnoreProperties(ignoreUnknown = true) public static class Builder { private City mCity; private List<Weather> mWeathers; public Builder() { } public Builder setCity(City city) { mCity = city; return this; } @JsonProperty("list") public Builder setWeathers(List<Weather> weathers) { mWeathers = weathers; return this; } public Forecast build() { return new Forecast(this); } } }
package org.neo4j.shell.impl; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.neo4j.helpers.Service; import org.neo4j.kernel.KernelExtension; import org.neo4j.shell.StartClient; import org.neo4j.shell.kernel.GraphDatabaseShellServer; @Service.Implementation( KernelExtension.class ) public final class ShellServerExtension extends KernelExtension { public ShellServerExtension() { super( "shell" ); } @Override protected void load( KernelData kernel ) { String shellConfig = (String) kernel.getParam( "enable_remote_shell" ); if ( shellConfig != null ) { if ( shellConfig.contains( "=" ) ) { enableRemoteShell( kernel, parseShellConfigParameter( shellConfig ) ); } else if ( Boolean.parseBoolean( shellConfig ) ) { enableRemoteShell( kernel, null ); } } } @Override protected void unload( KernelData kernel ) { GraphDatabaseShellServer server = getServer( kernel ); if ( server != null ) { server.shutdown(); } } @SuppressWarnings( "boxing" ) public void enableRemoteShell( KernelData kernel, Map<String, Serializable> config ) { GraphDatabaseShellServer server = getServer( kernel ); if ( server != null ) { throw new IllegalStateException( "Shell already enabled" ); } if ( config == null ) config = Collections.<String, Serializable>emptyMap(); try { server = new GraphDatabaseShellServer( kernel.graphDatabase(), (Boolean) getConfig( config, StartClient.ARG_READONLY, Boolean.FALSE ) ); int port = (Integer) getConfig( config, StartClient.ARG_PORT, AbstractServer.DEFAULT_PORT ); String name = (String) getConfig( config, StartClient.ARG_NAME, AbstractServer.DEFAULT_NAME ); server.makeRemotelyAvailable( port, name ); } catch ( Exception ex ) { if ( server != null ) server.shutdown(); throw new IllegalStateException( "Can't start remote Neo4j shell", ex ); } setServer( kernel, server ); } private void setServer( KernelData kernel, final GraphDatabaseShellServer server ) { kernel.setState( this, server ); } private GraphDatabaseShellServer getServer( KernelData kernel ) { return (GraphDatabaseShellServer) kernel.getState( this ); } @SuppressWarnings( "boxing" ) private static Map<String, Serializable> parseShellConfigParameter( String shellConfig ) { Map<String, Serializable> map = new HashMap<String, Serializable>(); for ( String keyValue : shellConfig.split( "," ) ) { String[] splitted = keyValue.split( "=" ); if ( splitted.length != 2 ) { throw new RuntimeException( "Invalid shell configuration '" + shellConfig + "' should be '<key1>=<value1>,<key2>=<value2>...' where key can" + " be any of [" + StartClient.ARG_PORT + ", " + StartClient.ARG_NAME + ", " + StartClient.ARG_READONLY + "]" ); } String key = splitted[0].trim(); Serializable value = splitted[1]; if ( key.equals( StartClient.ARG_PORT ) ) { value = Integer.parseInt( splitted[1] ); } else if ( key.equals( StartClient.ARG_READONLY ) ) { value = Boolean.parseBoolean( splitted[1] ); } map.put( key, value ); } return map; } private Serializable getConfig( Map<String, Serializable> config, String key, Serializable defaultValue ) { Serializable result = config.get( key ); return result != null ? result : defaultValue; } }
package com.facebook.react; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.devsupport.JSCHeapCapture; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.model.ReactModuleInfo; import com.facebook.react.module.model.ReactModuleInfoProvider; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.HashMap; import java.util.Map; /** * Package defining core framework modules (e.g. UIManager). It should be used for modules that * require special integration with other framework parts (e.g. with the list of packages to load * view managers from). */ @ReactModuleList( nativeModules = { JSCHeapCapture.class, }) public class DebugCorePackage extends TurboReactPackage { public DebugCorePackage() {} @Override public NativeModule getModule(String name, ReactApplicationContext reactContext) { switch (name) { case JSCHeapCapture.TAG: return new JSCHeapCapture(reactContext); default: throw new IllegalArgumentException( "In CoreModulesPackage, could not find Native module for " + name); } } @Override public ReactModuleInfoProvider getReactModuleInfoProvider() { try { Class<?> reactModuleInfoProviderClass = Class.forName("com.facebook.react.DebugCorePackage$$ReactModuleInfoProvider"); return (ReactModuleInfoProvider) reactModuleInfoProviderClass.newInstance(); } catch (ClassNotFoundException e) { // In OSS case, the annotation processor does not run. We fall back on creating this by hand Class<? extends NativeModule>[] moduleList = new Class[] {JSCHeapCapture.class}; final Map<String, ReactModuleInfo> reactModuleInfoMap = new HashMap<>(); for (Class<? extends NativeModule> moduleClass : moduleList) { ReactModule reactModule = moduleClass.getAnnotation(ReactModule.class); reactModuleInfoMap.put( reactModule.name(), new ReactModuleInfo( reactModule.name(), moduleClass.getName(), reactModule.canOverrideExistingModule(), reactModule.needsEagerInit(), reactModule.hasConstants(), reactModule.isCxxModule(), TurboModule.class.isAssignableFrom(moduleClass))); } return new ReactModuleInfoProvider() { @Override public Map<String, ReactModuleInfo> getReactModuleInfos() { return reactModuleInfoMap; } }; } catch (InstantiationException e) { throw new RuntimeException( "No ReactModuleInfoProvider for DebugCorePackage$$ReactModuleInfoProvider", e); } catch (IllegalAccessException e) { throw new RuntimeException( "No ReactModuleInfoProvider for DebugCorePackage$$ReactModuleInfoProvider", e); } } }
package chameleon.core.context; import chameleon.core.MetamodelException; import chameleon.core.declaration.Declaration; import chameleon.core.declaration.DeclarationSelector; import chameleon.core.element.Element; /** * @author Marko van Dooren */ public class LexicalContext extends Context { //public abstract Context getParentContext() throws MetamodelException; public LexicalContext(Context local, Element element) { setLocalContext(local); setElement(element); } public void setElement(Element element) { _element=element; } public Element element() { return _element; } private Element _element; public void setLocalContext(Context local) { _localContext = local; } public Context localContext() { return _localContext; } private Context _localContext; /** * Return the parent context of this context. * @throws MetamodelException */ public Context parentContext() throws MetamodelException { Element parent = element().parent(); if(parent != null) { return parent.lexicalContext(element()); } else { throw new MetamodelException("Lookup wants to go to the parent element of a "+element().getClass() +" but it is null."); } } public <T extends Declaration> T lookUp(DeclarationSelector<T> selector) throws MetamodelException { T tmp = localContext().lookUp(selector); if(tmp != null) { return tmp; } else { return parentContext().lookUp(selector); } } }
package com.wsy.plan.main; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import com.wsy.plan.R; import com.wsy.plan.databinding.ActivityUpdateBinding; import com.wsy.plan.main.model.AccountModel; import com.wsy.plan.main.model.TypeArrays; import com.wsy.plan.main.presenter.IAccountModelPresenter; import com.wsy.plan.main.presenter.LocalPresenter; import com.wsy.plan.rxbus.RxBus; public class UpdateActivity extends AppCompatActivity { private Spinner spinnerMethod, spinnerFirst, spinnerSecond; private String[][] typeArrays; private int position; private AccountModel model = new AccountModel(); private IAccountModelPresenter presenter = new LocalPresenter(); private boolean isStart = true; public static void startAction(Context context, int position, AccountModel model) { Intent intent = new Intent(context, UpdateActivity.class); intent.putExtra("position", position); intent.putExtra("model", model); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityUpdateBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_update); binding.setModel(model); binding.setHandler(this); setFinishOnTouchOutside(false); if (getIntent() != null) { position = getIntent().getIntExtra("position", -1); AccountModel am = (AccountModel) getIntent().getSerializableExtra("model"); model.id.set(am.id.get()); model.account_date.set(am.account_date.get()); model.account_method.set(am.account_method.get()); model.account_first.set(am.account_first.get()); model.account_second.set(am.account_second.get()); model.account_money.set(am.account_money.get()); model.account_comment.set(am.account_comment.get()); model.account_flag.set(am.account_flag.get()); } initSpinners(); } private void initSpinners() { spinnerMethod = (Spinner) findViewById(R.id.spinner_account_method); spinnerFirst = (Spinner) findViewById(R.id.spinner_account_first); spinnerSecond = (Spinner) findViewById(R.id.spinner_add_second); typeArrays = TypeArrays.get(this); for (int i = 0; i < TypeArrays.getMethod(this).length; i++) { if (TypeArrays.getMethod(this)[i].equals(model.account_method.get())) { spinnerMethod.setSelection(i); } } for (int j = 0; j < TypeArrays.getFirst(this).length; j++) { if (TypeArrays.getFirst(this)[j].equals(model.account_first.get())) { spinnerFirst.setSelection(j); } } spinnerFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spinnerSecond.setAdapter(new ArrayAdapter<>(UpdateActivity.this, android.R.layout.simple_spinner_dropdown_item, typeArrays[i])); if (isStart) { for (int k = 0; k < spinnerSecond.getCount(); k++) { if (spinnerSecond.getItemAtPosition(k).equals(model.account_second.get())) { spinnerSecond.setSelection(k); } } isStart = false; } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } public void onSaveClick() { model.account_flag.set(getString(R.string.income).equals(spinnerFirst.getSelectedItem()) ? 1 : 0); model.account_method.set((String) spinnerMethod.getSelectedItem()); model.account_first.set((String) spinnerFirst.getSelectedItem()); model.account_second.set((String) spinnerSecond.getSelectedItem()); if (presenter.updateModel(model.id.get(), model)) { Toast.makeText(this, R.string.main_update_successfully, Toast.LENGTH_SHORT).show(); RxBus.getInstance().post(new Object[]{position, model}); onBackPressed(); } else { Toast.makeText(this, R.string.main_update_failed, Toast.LENGTH_SHORT).show(); } } public void onCancelClick() { onBackPressed(); } }
package us.kbase.workspace.database.mongo; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.jongo.Jongo; import us.kbase.workspace.database.AllUsers; import us.kbase.workspace.database.Permission; import us.kbase.workspace.database.ResolvedWorkspaceID; import us.kbase.workspace.database.User; import us.kbase.workspace.database.WorkspaceIdentifier; import us.kbase.workspace.database.WorkspaceUser; import us.kbase.workspace.database.exceptions.CorruptWorkspaceDBException; import us.kbase.workspace.database.exceptions.NoSuchObjectException; import us.kbase.workspace.database.exceptions.NoSuchWorkspaceException; import us.kbase.workspace.database.exceptions.WorkspaceCommunicationException; import com.mongodb.AggregationOutput; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoException; public class QueryMethods { private final DB wsmongo; private final Jongo wsjongo; private final AllUsers allUsers; private final String workspaceCollection; private final String pointerCollection; private final String versionCollection; private final String workspaceACLCollection; QueryMethods(final DB wsmongo, final AllUsers allUsers, final String workspaceCollection, final String pointerCollection, final String versionCollection, final String workspaceACLCollection) { this.wsmongo = wsmongo; wsjongo = new Jongo(wsmongo); this.allUsers = allUsers; this.workspaceCollection = workspaceCollection; this.pointerCollection = pointerCollection; this.versionCollection = versionCollection; this.workspaceACLCollection = workspaceACLCollection; } Map<String, Object> queryWorkspace(final ResolvedMongoWSID rwsi, final Set<String> fields) throws WorkspaceCommunicationException, CorruptWorkspaceDBException { Set<ResolvedMongoWSID> rwsiset = new HashSet<ResolvedMongoWSID>(); rwsiset.add(rwsi); return queryWorkspacesByResolvedID(rwsiset, fields).get(rwsi); } Map<ResolvedMongoWSID, Map<String, Object>> queryWorkspacesByResolvedID(final Set<ResolvedMongoWSID> rwsiset, final Set<String> fields) throws WorkspaceCommunicationException, CorruptWorkspaceDBException { final Map<Long, ResolvedMongoWSID> ids = new HashMap<Long, ResolvedMongoWSID>(); for (ResolvedMongoWSID r: rwsiset) { ids.put(r.getID(), r); } final Map<Long, Map<String, Object>> idres; try { idres = queryWorkspacesByID(ids.keySet(), fields); } catch (NoSuchWorkspaceException nswe) { throw new CorruptWorkspaceDBException( "Workspace deleted from database: " + nswe.getLocalizedMessage()); } final Map<ResolvedMongoWSID, Map<String, Object>> ret = new HashMap<ResolvedMongoWSID, Map<String,Object>>(); for (final Long id: idres.keySet()) { ret.put(ids.get(id), idres.get(id)); } return ret; } Map<String, Object> queryWorkspace(final WorkspaceIdentifier wsi, final Set<String> fields) throws NoSuchWorkspaceException, WorkspaceCommunicationException { Set<WorkspaceIdentifier> wsiset = new HashSet<WorkspaceIdentifier>(); wsiset.add(wsi); return queryWorkspacesByIdentifier(wsiset, fields).get(wsi); } Map<WorkspaceIdentifier, Map<String, Object>> queryWorkspacesByIdentifier(final Set<WorkspaceIdentifier> wsiset, final Set<String> fields) throws NoSuchWorkspaceException, WorkspaceCommunicationException { final Map<Long, WorkspaceIdentifier> ids = new HashMap<Long, WorkspaceIdentifier>(); final Map<String, WorkspaceIdentifier> names = new HashMap<String, WorkspaceIdentifier>(); for (WorkspaceIdentifier wsi: wsiset) { if (wsi.getId() != null) { ids.put(wsi.getId(), wsi); } else { names.put(wsi.getName(), wsi); } } //could do an or here but hardly seems worth it final Map<WorkspaceIdentifier, Map<String, Object>> ret = new HashMap<WorkspaceIdentifier, Map<String,Object>>(); final Map<Long, Map<String, Object>> idres = queryWorkspacesByID( ids.keySet(), fields); for (final Long id: idres.keySet()) { ret.put(ids.get(id), idres.get(id)); } final Map<String, Map<String, Object>> nameres = queryWorkspacesByName( names.keySet(), fields); for (String name: nameres.keySet()) { ret.put(names.get(name), nameres.get(name)); } return ret; } Map<String, Object> queryWorkspace(final String name, final Set<String> fields) throws NoSuchWorkspaceException, WorkspaceCommunicationException { Set<String> nameset = new HashSet<String>(); nameset.add(name); return queryWorkspacesByName(nameset, fields).get(name); } Map<String, Map<String, Object>> queryWorkspacesByName( final Set<String> wsnames, final Set<String> fields) throws NoSuchWorkspaceException, WorkspaceCommunicationException { if (wsnames.isEmpty()) { return new HashMap<String, Map<String, Object>>(); } fields.add(Fields.WS_NAME); final List<Map<String, Object>> queryres = queryCollection(workspaceCollection, String.format("{%s: {$in: [\"%s\"]}}", Fields.WS_NAME, StringUtils.join(wsnames, "\", \"")), fields); final Map<String, Map<String, Object>> result = new HashMap<String, Map<String, Object>>(); for (Map<String, Object> m: queryres) { result.put((String) m.get(Fields.WS_NAME), m); } for (String name: wsnames) { if (!result.containsKey(name)) { throw new NoSuchWorkspaceException(String.format( "No workspace with name %s exists", name)); } } return result; } Map<String, Object> queryWorkspace(final long id, final Set<String> fields) throws NoSuchWorkspaceException, WorkspaceCommunicationException { Set<Long> idset = new HashSet<Long>(); idset.add(id); return queryWorkspacesByID(idset, fields).get(id); } Map<Long, Map<String, Object>> queryWorkspacesByID( final Set<Long> wsids, final Set<String> fields) throws NoSuchWorkspaceException, WorkspaceCommunicationException { if (wsids.isEmpty()) { return new HashMap<Long, Map<String, Object>>(); } fields.add(Fields.WS_ID); final List<Map<String, Object>> queryres = queryCollection(workspaceCollection, String.format( "{%s: {$in: [%s]}}", Fields.WS_ID, StringUtils.join(wsids, ", ")), fields); final Map<Long, Map<String, Object>> result = new HashMap<Long, Map<String, Object>>(); for (Map<String, Object> m: queryres) { result.put((Long) m.get(Fields.WS_ID), m); } for (final Long id: wsids) { if (!result.containsKey(id)) { throw new NoSuchWorkspaceException(String.format( "No workspace with id %s exists", id)); } } return result; } Map<ObjectIDResolvedWSNoVer, Map<String, Object>> queryObjects( final Set<ObjectIDResolvedWSNoVer> objectIDs, final Set<String> fields) throws NoSuchObjectException, WorkspaceCommunicationException { return queryObjects(objectIDs, fields, true); } Map<ObjectIDResolvedWSNoVer, Map<String, Object>> queryObjects( final Set<ObjectIDResolvedWSNoVer> objectIDs, final Set<String> fields, final boolean exceptOnMissing) throws NoSuchObjectException, WorkspaceCommunicationException { final Map<ResolvedMongoWSID, Map<Long, ObjectIDResolvedWSNoVer>> ids = new HashMap<ResolvedMongoWSID, Map<Long, ObjectIDResolvedWSNoVer>>(); final Map<ResolvedMongoWSID, Set<Long>> idsquery = new HashMap<ResolvedMongoWSID, Set<Long>>(); final Map<ResolvedMongoWSID, Map<String, ObjectIDResolvedWSNoVer>> names = new HashMap<ResolvedMongoWSID, Map<String, ObjectIDResolvedWSNoVer>>(); final Map<ResolvedMongoWSID, Set<String>> namesquery = new HashMap<ResolvedMongoWSID, Set<String>>(); for (final ObjectIDResolvedWSNoVer o: objectIDs) { final ResolvedMongoWSID rwsi = convertResolvedID(o.getWorkspaceIdentifier()); if (o.getId() == null) { if (names.get(rwsi) == null) { names.put(rwsi, new HashMap<String, ObjectIDResolvedWSNoVer>()); namesquery.put(rwsi, new HashSet<String>()); } names.get(rwsi).put(o.getName(), o); namesquery.get(rwsi).add(o.getName()); } else { if (ids.get(rwsi) == null) { ids.put(rwsi, new HashMap<Long, ObjectIDResolvedWSNoVer>()); idsquery.put(rwsi, new HashSet<Long>()); } ids.get(rwsi).put(o.getId(), o); idsquery.get(rwsi).add(o.getId()); } } final Map<ObjectIDResolvedWSNoVer, Map<String, Object>> ret = new HashMap<ObjectIDResolvedWSNoVer, Map<String, Object>>(); final Map<ResolvedMongoWSID, Map<String, Map<String, Object>>> nameres = queryObjectsByName(namesquery, fields, exceptOnMissing); final Map<ResolvedMongoWSID, Map<Long, Map<String, Object>>> idres = queryObjectsByID(idsquery, fields, exceptOnMissing); for (final ResolvedMongoWSID rwsi: ids.keySet()) { if (!idres.containsKey(rwsi)) { continue; //exceptOnMissing was false and one was missing } for (final Long id: idres.get(rwsi).keySet()) { ret.put(ids.get(rwsi).get(id), idres.get(rwsi).get(id)); } } for (final ResolvedMongoWSID rwsi: names.keySet()) { if (!nameres.containsKey(rwsi)) { continue; //exceptOnMissing was false and one was missing } for (final String name: nameres.get(rwsi).keySet()) { ret.put(names.get(rwsi).get(name), nameres.get(rwsi).get(name)); } } return ret; } Map<ResolvedMongoWSID, Map<String, Map<String, Object>>> queryObjectsByName( final Map<ResolvedMongoWSID, Set<String>> names, final Set<String> fields, final boolean exceptOnMissing) throws NoSuchObjectException, WorkspaceCommunicationException { if (names.isEmpty()) { return new HashMap<ResolvedMongoWSID, Map<String,Map<String,Object>>>(); } final List<DBObject> orquery = new LinkedList<DBObject>(); for (final ResolvedMongoWSID rwsi: names.keySet()) { final DBObject query = new BasicDBObject(Fields.PTR_WS_ID, rwsi.getID()); query.put(Fields.PTR_NAME, new BasicDBObject("$in", names.get(rwsi))); orquery.add(query); } fields.add(Fields.PTR_NAME); fields.add(Fields.PTR_WS_ID); final List<Map<String, Object>> queryres = queryCollection( pointerCollection, new BasicDBObject("$or", orquery), fields); final Map<ResolvedMongoWSID, Map<String, Map<String, Object>>> result = new HashMap<ResolvedMongoWSID, Map<String, Map<String, Object>>>(); for (Map<String, Object> m: queryres) { final ResolvedMongoWSID rwsi = new ResolvedMongoWSID((Long) m.get(Fields.PTR_WS_ID)); if (!result.containsKey(rwsi)) { result.put(rwsi, new HashMap<String, Map<String, Object>>()); } result.get(rwsi).put((String) m.get(Fields.PTR_NAME), m); } if (exceptOnMissing) { for (final ResolvedMongoWSID rwsi: names.keySet()) { for (String name: names.get(rwsi)) { if (!result.containsKey(rwsi) || !result.get(rwsi).containsKey(name)) { throw new NoSuchObjectException(String.format( "No object with name %s exists in workspace %s", name, rwsi.getID())); } } } } return result; } Map<ResolvedMongoWSID, Map<Long, Map<String, Object>>> queryObjectsByID( final Map<ResolvedMongoWSID, Set<Long>> ids, final Set<String> fields, final boolean exceptOnMissing) throws NoSuchObjectException, WorkspaceCommunicationException { if (ids.isEmpty()) { return new HashMap<ResolvedMongoWSID, Map<Long,Map<String,Object>>>(); } final List<DBObject> orquery = new LinkedList<DBObject>(); for (final ResolvedMongoWSID rwsi: ids.keySet()) { final DBObject query = new BasicDBObject(Fields.PTR_WS_ID, rwsi.getID()); query.put(Fields.PTR_ID, new BasicDBObject("$in", ids.get(rwsi))); orquery.add(query); } fields.add(Fields.PTR_ID); fields.add(Fields.PTR_WS_ID); final List<Map<String, Object>> queryres = queryCollection( pointerCollection, new BasicDBObject("$or", orquery), fields); final Map<ResolvedMongoWSID, Map<Long, Map<String, Object>>> result = new HashMap<ResolvedMongoWSID, Map<Long, Map<String, Object>>>(); for (Map<String, Object> m: queryres) { final ResolvedMongoWSID rwsi = new ResolvedMongoWSID((Long) m.get(Fields.PTR_WS_ID)); if (!result.containsKey(rwsi)) { result.put(rwsi, new HashMap<Long, Map<String, Object>>()); } result.get(rwsi).put((Long) m.get(Fields.PTR_ID), m); } if (exceptOnMissing) { for (final ResolvedMongoWSID rwsi: ids.keySet()) { for (Long id: ids.get(rwsi)) { if (!result.containsKey(rwsi) || !result.get(rwsi).containsKey(id)) { throw new NoSuchObjectException(String.format( "No object with id %s exists in workspace %s", id, rwsi.getID())); } } } } return result; } Map<ResolvedMongoObjectID, Map<String, Object>> queryVersions( final Set<ResolvedMongoObjectID> objectIDs, final Set<String> fields) throws WorkspaceCommunicationException, NoSuchObjectException { final Map<ResolvedMongoWSID, Map<Long, List<Integer>>> ids = new HashMap<ResolvedMongoWSID, Map<Long, List<Integer>>>(); final Map<ResolvedMongoWSID, List<Long>> idsNoVer = new HashMap<ResolvedMongoWSID, List<Long>>(); for (final ResolvedMongoObjectID o: objectIDs) { final ResolvedMongoWSID rwsi = convertResolvedID(o.getWorkspaceIdentifier()); if (o.getVersion() == null) { if (idsNoVer.get(rwsi) == null) { idsNoVer.put(rwsi, new LinkedList<Long>()); } idsNoVer.get(rwsi).add(o.getId()); } else { if (ids.get(rwsi) == null) { ids.put(rwsi, new HashMap<Long, List<Integer>>()); } if (ids.get(rwsi).get(o.getId()) == null) { ids.get(rwsi).put(o.getId(), new LinkedList<Integer>()); } ids.get(rwsi).get(o.getId()).add(o.getVersion()); } } final Map<ResolvedMongoWSID, Map<Long, Integer>> latestIds = getLatestVersions(idsNoVer); for (final ResolvedMongoWSID rwsi: idsNoVer.keySet()) { if (ids.get(rwsi) == null) { ids.put(rwsi, new HashMap<Long, List<Integer>>()); } for (final Long oid: latestIds.get(rwsi).keySet()) { if (ids.get(rwsi).get(oid) == null) { ids.get(rwsi).put(oid, new LinkedList<Integer>()); } ids.get(rwsi).get(oid).add(latestIds.get(rwsi).get(oid)); } } // ws id, obj id, obj version, version data map final Map<ResolvedMongoWSID, Map<Long, Map<Integer, Map<String, Object>>>> data = //this is getting ridiculous queryVersions(ids, fields); final Map<ResolvedMongoObjectID, Map<String, Object>> ret = new HashMap<ResolvedMongoObjectID, Map<String,Object>>(); for (final ResolvedMongoObjectID roi: objectIDs) { if (roi.getVersion() == null) { // this id is resolved so at least one version must exist int latest = latestIds.get(roi.getWorkspaceIdentifier()) .get(roi.getId()); ret.put(roi, data.get(roi.getWorkspaceIdentifier()) .get(roi.getId()).get(latest)); } else { final Map<String, Object> d = data.get( roi.getWorkspaceIdentifier()).get(roi.getId()) .get(roi.getVersion()); if (d == null) { throw new NoSuchObjectException(String.format( "No object with id %s (name %s) and version %s exists in" + " workspace %s", roi.getId(), roi.getName(), roi.getVersion(), roi.getWorkspaceIdentifier().getID())); } ret.put(roi, d); } } return ret; } private Map<ResolvedMongoWSID, Map<Long, Map<Integer, Map<String, Object>>>> queryVersions(final Map<ResolvedMongoWSID, Map<Long, List<Integer>>> ids, final Set<String> fields) throws WorkspaceCommunicationException { fields.add(Fields.VER_ID); fields.add(Fields.VER_VER); //disgusting. need to do better. //nested or queries are slow per the mongo docs so just query one //workspace at a time. If profiling shows this is slow investigate //further final Map<ResolvedMongoWSID, Map<Long, Map<Integer, Map<String, Object>>>> ret = new HashMap<ResolvedMongoWSID, Map<Long,Map<Integer,Map<String,Object>>>>(); for (final ResolvedMongoWSID rwsi: ids.keySet()) { ret.put(rwsi, new HashMap<Long, Map<Integer, Map<String,Object>>>()); final List<DBObject> orquery = new LinkedList<DBObject>(); for (final Long objectID: ids.get(rwsi).keySet()) { ret.get(rwsi).put(objectID, new HashMap<Integer, Map<String, Object>>()); final DBObject q = new BasicDBObject(Fields.VER_VER, new BasicDBObject("$in", ids.get(rwsi).get(objectID))); q.put(Fields.VER_ID, objectID); orquery.add(q); } final DBObject query = new BasicDBObject("$or", orquery); query.put(Fields.VER_WS_ID, rwsi.getID()); final List<Map<String, Object>> res = queryCollection( versionCollection, query, fields); for (final Map<String, Object> r: res) { final Long id = (Long) r.get(Fields.VER_ID); final Integer ver = (Integer) r.get(Fields.VER_VER); ret.get(rwsi).get(id).put(ver, r); } } return ret; } private Map<ResolvedMongoWSID, Map<Long, Integer>> getLatestVersions( final Map<ResolvedMongoWSID, List<Long>> ids) throws WorkspaceCommunicationException { final Map<ResolvedMongoWSID, Map<Long, Integer>> ret = new HashMap<ResolvedMongoWSID, Map<Long, Integer>>(); if (ids.isEmpty()) { return ret; } final List<DBObject> orquery = new LinkedList<DBObject>(); for (final ResolvedMongoWSID wsid: ids.keySet()) { final DBObject query = new BasicDBObject( Fields.VER_ID, new BasicDBObject("$in", ids.get(wsid))); query.put(Fields.VER_WS_ID, wsid.getID()); orquery.add(query); } final DBObject query = new BasicDBObject("$or", orquery); final DBObject groupid = new BasicDBObject( Fields.VER_WS_ID, "$" + Fields.VER_WS_ID); groupid.put(Fields.VER_ID, "$" + Fields.VER_ID); final DBObject group = new BasicDBObject(Fields.MONGO_ID, groupid); group.put(Fields.VER_VER, new BasicDBObject("$max", "$" + Fields.VER_VER)); final AggregationOutput mret; try { mret = wsmongo.getCollection(versionCollection).aggregate( new BasicDBObject("$match", query), new BasicDBObject("$group", group)); } catch (MongoException me) { throw new WorkspaceCommunicationException( "There was a problem communicating with the database", me); } for (DBObject o: mret.results()) { final DBObject id = (DBObject) o.get(Fields.MONGO_ID); final ResolvedMongoWSID rwsi = new ResolvedMongoWSID( (Long) id.get(Fields.VER_WS_ID)); if (!ret.containsKey(rwsi)) { ret.put(rwsi, new HashMap<Long, Integer>()); } ret.get(rwsi).put((Long) id.get(Fields.VER_ID), (Integer) o.get(Fields.VER_VER)); } return ret; } List<Map<String, Object>> queryCollection(final String collection, final String query, final Set<String> fields) throws WorkspaceCommunicationException { final DBObject projection = new BasicDBObject(); for (final String field: fields) { projection.put(field, 1); } @SuppressWarnings("rawtypes") final Iterable<Map> im; try { @SuppressWarnings({ "rawtypes" }) final Iterable<Map> res = wsjongo.getCollection(collection) .find(query).projection(projection.toString()) .as(Map.class); im = res; } catch (MongoException me) { throw new WorkspaceCommunicationException( "There was a problem communicating with the database", me); } final List<Map<String, Object>> result = new ArrayList<Map<String,Object>>(); for (@SuppressWarnings("rawtypes") Map m: im) { @SuppressWarnings("unchecked") final Map<String, Object> castmap = (Map<String, Object>) m; result.add(castmap); } return result; } List<Map<String, Object>> queryCollection(final String collection, final DBObject query, final Set<String> fields) throws WorkspaceCommunicationException { final DBObject projection = new BasicDBObject(); for (final String field: fields) { projection.put(field, 1); } final DBCursor im; try { im = wsmongo.getCollection(collection).find(query, projection); } catch (MongoException me) { throw new WorkspaceCommunicationException( "There was a problem communicating with the database", me); } final List<Map<String, Object>> result = new ArrayList<Map<String,Object>>(); for (final DBObject o: im) { result.add(dbObjectToMap(o)); } return result; } //since LazyBsonObject.toMap() is not supported private Map<String, Object> dbObjectToMap(final DBObject o) { final Map<String, Object> m = new HashMap<String, Object>(); for (final String name: o.keySet()) { m.put(name, o.get(name)); } return m; } Map<User, Permission> queryPermissions( final ResolvedMongoWSID rwsi) throws WorkspaceCommunicationException, CorruptWorkspaceDBException { return queryPermissions(rwsi, null); } Map<User, Permission> queryPermissions( final ResolvedMongoWSID rwsi, final Set<User> users) throws WorkspaceCommunicationException, CorruptWorkspaceDBException { final Set<ResolvedMongoWSID> wsis = new HashSet<ResolvedMongoWSID>(); wsis.add(rwsi); return queryPermissions(wsis, users).get(rwsi); } Map<ResolvedMongoWSID, Map<User, Permission>> queryPermissions( final Set<ResolvedMongoWSID> rwsis, final Set<User> users) throws WorkspaceCommunicationException, CorruptWorkspaceDBException { final DBObject query = new BasicDBObject(); final DBObject iddb = new BasicDBObject(); final Set<Long> wsids = new HashSet<Long>(); for (final ResolvedMongoWSID r: rwsis) { wsids.add(r.getID()); } iddb.put("$in", wsids); query.put(Fields.ACL_WSID, iddb); if (users != null && users.size() > 0) { final List<String> u = new ArrayList<String>(); for (User user: users) { u.add(user.getUser()); } final DBObject usersdb = new BasicDBObject(); usersdb.put("$in", u); query.put(Fields.ACL_USER, usersdb); } final DBObject proj = new BasicDBObject(); proj.put(Fields.MONGO_ID, 0); proj.put(Fields.ACL_USER, 1); proj.put(Fields.ACL_PERM, 1); proj.put(Fields.ACL_WSID, 1); final DBCursor res; try { res = wsmongo.getCollection(workspaceACLCollection) .find(query, proj); } catch (MongoException me) { throw new WorkspaceCommunicationException( "There was a problem communicating with the database", me); } final Map<Long, Map<User, Permission>> wsidToPerms = new HashMap<Long, Map<User, Permission>>(); for (final DBObject m: res) { final long wsid = (Long) m.get(Fields.ACL_WSID); if (!wsidToPerms.containsKey(wsid)) { wsidToPerms.put(wsid, new HashMap<User, Permission>()); } wsidToPerms.get(wsid).put(getUser((String) m.get(Fields.ACL_USER)), Permission.fromInt((Integer) m.get(Fields.ACL_PERM))); } final Map<ResolvedMongoWSID, Map<User, Permission>> ret = new HashMap<ResolvedMongoWSID, Map<User, Permission>>(); for (ResolvedMongoWSID rwsi: rwsis) { final Map<User, Permission> p = wsidToPerms.get(rwsi.getID()); ret.put(rwsi, p == null ? new HashMap<User, Permission>() : p); } return ret; } private User getUser(final String user) throws CorruptWorkspaceDBException { try { return new WorkspaceUser(user); } catch (IllegalArgumentException iae) { if (user.length() != 1) { throw new CorruptWorkspaceDBException(String.format( "Illegal user %s found in database", user)); } try { final AllUsers u = new AllUsers(user.charAt(0)); if (!allUsers.equals(u)) { throw new IllegalArgumentException(); } return u; } catch (IllegalArgumentException i) { throw new CorruptWorkspaceDBException(String.format( "Illegal user %s found in database", user)); } } } ResolvedMongoWSID convertResolvedID(ResolvedWorkspaceID rwsi) { if (!(rwsi instanceof ResolvedMongoWSID)) { throw new RuntimeException( "Passed incorrect implementation of ResolvedWorkspaceID:" + (rwsi == null ? null : rwsi.getClass())); } return (ResolvedMongoWSID) rwsi; } }
package edu.ucsd.cse.eulexia; import com.google.android.glass.app.Card; import com.google.android.glass.content.Intents; import com.google.android.glass.media.Sounds; import com.google.android.glass.widget.CardBuilder; import com.google.android.glass.widget.CardScrollAdapter; import com.google.android.glass.widget.CardScrollView; import com.google.android.glass.touchpad.*; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.MotionEvent; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.TextView; import android.graphics.Typeface; import android.view.KeyEvent; import android.util.Log; import android.provider.MediaStore; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Pattern; import java.util.regex.Matcher; import android.content.Intent; import android.net.Uri; import android.os.FileObserver; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONArray; public class OCRActivity extends Activity { /** * {@link CardScrollView} to use as the main content view. */ private CardScrollView mCardScroller; private ProgressDialog mProgressDialog; /** * "Hello World!" {@link View} generated by {@link #buildView()}. */ private View mView; private GestureDetector mGestureDetector; private CameraView mCameraView; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA) { // Stop the preview and release the camera. // Execute your logic as quickly as possible // so the capture happens quickly. return false; } else { return super.onKeyDown(keyCode, event); } } @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mView = buildView(); mGestureDetector = createGestureDetector(this); mProgressDialog = new ProgressDialog(this); mProgressDialog.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle("Loading..."); mProgressDialog.setCancelable(false); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mCardScroller = new CardScrollView(this); mCardScroller.setAdapter(new CardScrollAdapter() { @Override public int getCount() { return 1; } @Override public Object getItem(int position) { return mView; } @Override public View getView(int position, View convertView, ViewGroup parent) { return mView; } @Override public int getPosition(Object item) { if (mView.equals(item)) { return 0; } return AdapterView.INVALID_POSITION; } }); // Handle the TAP event. mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Plays disallowed sound to indicate that TAP actions are not supported. AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); am.playSoundEffect(Sounds.DISALLOWED); } }); setContentView(mCardScroller); } @Override protected void onResume() { super.onResume(); mCardScroller.activate(); } @Override protected void onPause() { mCardScroller.deactivate(); super.onPause(); } /** * Builds a Glass styled "Hello World!" view using the {@link CardBuilder} class. */ private View buildView() { Drawable mtitle = getResources().getDrawable(R.drawable.titlemoon); View view = new CardBuilder(getApplicationContext(), CardBuilder.Layout.CAPTION) .addImage(mtitle) //.setIcon(R.drawable.ic_spellcheck) //.setText(R.string.title_activity_ocr) .setFootnote(R.string.ocr_menu_description) .getView(); return view; /*View view = new CardBuilder(this, CardBuilder.Layout.EMBED_INSIDE) .setEmbeddedLayout(R.layout.main_view) .getView(); TextView textView1 = (TextView) view.findViewById(R.id.textView); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Calibri.ttf"); textView1.setTypeface(tf); textView1.setText("Swipe forward to take a picture"); return view;*/ } ////////////////////// GESTURES /////////////////////////////// @Override public boolean onGenericMotionEvent(MotionEvent event) { if (mGestureDetector != null) { return mGestureDetector.onMotionEvent(event); } return false; } ////////////////////// PICTURE PROCESSING /////////////////////////////// private static final int TAKE_PICTURE_REQUEST = 1; private void takePicture() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, TAKE_PICTURE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) { stopCameraPreview(); String thumbnailPath = data.getStringExtra(Intents.EXTRA_THUMBNAIL_FILE_PATH); String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH); Log.d("OCR", "the picture will be saved to: " + picturePath); mProgressDialog.setMessage("Saving Image..."); //Set the current progress to zero mProgressDialog.setProgress(50); //Display the progress dialog mProgressDialog.show(); processPictureWhenReady(picturePath); // TODO: Show the thumbnail to the user while the full picture is being // processed. } super.onActivityResult(requestCode, resultCode, data); } private void processPictureWhenReady(final String picturePath) { final File pictureFile = new File(picturePath); if (pictureFile.exists()) { // The picture is ready; process it. // SEBTEST: DO OCR HERE mProgressDialog.hide(); Log.d("OCR", "Picture ready"); OCRRequest request = new OCRRequest(this, getApplicationContext()); request.execute(picturePath); } else { // The file does not exist yet. Before starting the file observer, you // can update your UI to let the user know that the application is // waiting for the picture (for example, by displaying the thumbnail // image and a progress indicator). final File parentDirectory = pictureFile.getParentFile(); FileObserver observer = new FileObserver(parentDirectory.getPath(), FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) { // Protect against additional pending events after CLOSE_WRITE // or MOVED_TO is handled. private boolean isFileWritten; @Override public void onEvent(int event, String path) { if (!isFileWritten) { // For safety, make sure that the file that was created in // the directory is actually the one that we're expecting. File affectedFile = new File(parentDirectory, path); isFileWritten = affectedFile.equals(pictureFile); if (isFileWritten) { stopWatching(); // Now that the file is ready, recursively call // processPictureWhenReady again (on the UI thread). runOnUiThread(new Runnable() { @Override public void run() { processPictureWhenReady(picturePath); } }); } } } }; observer.startWatching(); } } private GestureDetector createGestureDetector(Context context) { GestureDetector gestureDetector = new GestureDetector(context); //Create a base listener for generic gestures gestureDetector.setBaseListener(new GestureDetector.BaseListener() { @Override public boolean onGesture(Gesture gesture) { Log.e("tag", gesture.name()); if (gesture == Gesture.LONG_PRESS) { // do something on tap toggleCamera(); } else if (gesture == Gesture.TWO_TAP) { // take picture and do OCR return true; } else if (gesture == Gesture.SWIPE_RIGHT) { // do something on right (forward) swipe // stopCameraPreview(); takePicture(); return true; } else if (gesture == Gesture.SWIPE_LEFT) { // do something on left (backwards) swipe return true; } return false; } }); return gestureDetector; } public void toggleCamera(){ if(mCameraView == null){ Log.d(getLocalClassName(), "Starting camera preview"); mCameraView = new CameraView(this); setContentView(mCameraView); }else{ // Stop camera and return back to main layout stopCameraPreview(); } } public void stopCameraPreview(){ Log.d(getLocalClassName(), "Stopping camera preview"); if(mCameraView != null) { mCameraView.releaseCamera(); mCameraView = null; setContentView(mCardScroller); } } public void transitionToSpellcheck(List results, Intent intent) { Bundle params = new Bundle(); ArrayList<String> ocrResults = new ArrayList<String>(); ocrResults.addAll(results); params.putStringArrayList("ocrResults", ocrResults); intent.putExtras(params); startActivity(intent); } } class OCRRequest extends AsyncTask<String /*params*/, String /*progress*/, String/*result*/> { private String url="https://ocr.a9t9.com/api/Parse/Image"; private ProgressDialog mProgressDialog; private Intent intent; private OCRActivity ocrActivity; public OCRRequest(OCRActivity activity, Context context) { mProgressDialog = new ProgressDialog(activity); mProgressDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle("Loading..."); mProgressDialog.setCancelable(false); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); ocrActivity = activity; intent = new Intent(context, SpellcheckActivity.class); } @Override protected void onPreExecute() { Log.d("OCR","onpreExecute"); mProgressDialog.setMessage("Starting OCR Request..."); mProgressDialog.setCancelable(false); mProgressDialog.setProgress(33); mProgressDialog.show(); //Display the progress dialog } @Override protected String doInBackground(String... uri) { Log.d("OCR", "performing http POST with picture " + uri[0]); // uri[0] will contain the picture path HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse response; String responseString = null; MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apiKey", "helloworld", ContentType.TEXT_PLAIN); builder.addBinaryBody("file", new File(uri[0]), ContentType.APPLICATION_OCTET_STREAM, uri[0].substring(uri[0].lastIndexOf("/") + 1)); builder.addTextBody("language", "eng", ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); mProgressDialog.show(); mProgressDialog.setMessage("Receiving OCR Response..."); mProgressDialog.setProgress(66); try { response = httpclient.execute(httpPost); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpStatus.SC_OK){ ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseString = out.toString(); Log.d("OCR", "response: " + out); out.close(); } else{ //Closes the connection. Log.d("OCR", "BAD response: " + statusLine.getReasonPhrase()); response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { //TODO Handle problems.. Log.d("OCR", e.getMessage()); } catch (IOException e) { //TODO Handle problems.. Log.d("OCR", e.getMessage()); } Log.d("OCR","ocr result is " + responseString); return responseString; } @Override protected void onPostExecute(String result) { mProgressDialog.hide(); super.onPostExecute(result); //Do anything with response.. Log.d("OCR", "Implement a transition here?"); try { JSONObject resObj = new JSONObject(result); JSONArray parsedRes = new JSONArray(resObj.getString("ParsedResults")); JSONObject parsedResults = parsedRes.getJSONObject(0); if(resObj.getBoolean("IsErroredOnProcessing")) { // error occured in parsing - handle it return; } String res = parsedResults.getString("ParsedText"); res = res.replaceAll("[\n\r]", ""); // Get rid of escape characters List<String> results = Arrays.asList(res.split(" ")); ocrActivity.transitionToSpellcheck(results, intent); } catch (JSONException e) { e.printStackTrace(); } } }
package org.openremote.security; import java.net.URI; import java.security.KeyStore; import java.security.KeyPair; import java.security.PrivateKey; import java.security.Provider; import java.security.cert.Certificate; import org.openremote.security.provider.BouncyCastleKeySigner; /** * This is a convenience implementation based on standard Java security architecture and its * management of asymmetric key pairs. It provides some helper methods for generating asymmetric * key pairs (for example, elliptic curves, RSA) and associated public key X.509 certificates * for public key infrastructure. It also provides convenience methods for persistent and * in-memory private key stores. * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public class PrivateKeyManager extends KeyManager { /** * The default key algorithm used when generating self-signed key pairs : {@value} */ public static final AsymmetricKeyAlgorithm DEFAULT_SELF_SIGNED_KEY_ALGORITHM = AsymmetricKeyAlgorithm.EC; public static final String DEFAULT_SELF_SIGNED_KEY_ISSUER = "OpenRemote Inc."; private static final KeySigner keySigner = new BouncyCastleKeySigner(); /** * Creates a new private key manager. * * @return key manager instance * * @throws ConfigurationException if creating private key manager fails, e.g. the requested * keystore algorithm is not found with the installed security providers. */ public static PrivateKeyManager create() throws ConfigurationException { return create(DEFAULT_KEYSTORE_STORAGE); } /** * Creates a new private key manager with a given storage format. * * @param storage * the desired key storage format * * @return key manager instance * * @throws ConfigurationException if creating private key manager fails, e.g. the requested * keystore algorithm is not found with the installed security providers. */ public static PrivateKeyManager create(Storage storage) throws ConfigurationException { try { return new PrivateKeyManager(storage, storage.getSecurityProvider()); } catch (KeyManagerException exception) { throw new ConfigurationException( "Could not create private key manager : {0}", exception, exception.getMessage() ); } } public static PrivateKeyManager create(Storage storage, SecurityProvider provider) throws ConfigurationException { try { return new PrivateKeyManager(storage, provider.getProviderInstance()); } catch (KeyManagerException exception) { throw new ConfigurationException( "Could not create private key manager : {0}", exception, exception.getMessage() ); } } public static PrivateKeyManager create(URI keyStoreLocation, char[] masterPassword) throws ConfigurationException { return create(keyStoreLocation, masterPassword, DEFAULT_KEYSTORE_STORAGE); } public static PrivateKeyManager create(URI keyStoreLocation, char[] masterPassword, Storage storage) throws ConfigurationException { try { return new PrivateKeyManager(keyStoreLocation, masterPassword, storage); } catch (KeyManagerException exception) { throw new ConfigurationException( "Could not create private key manager : {0}", exception, exception.getMessage() ); } } /** * Location of the keystore, if persisted. */ private URI keystoreLocation = null; private PrivateKeyManager(Storage storage, SecurityProvider provider) throws KeyManagerException { this(storage, provider.getProviderInstance()); } /** * Internal constructor to be used by the static builder methods. */ private PrivateKeyManager(Storage storage, Provider provider) throws KeyManagerException { super(storage, provider); } private PrivateKeyManager(URI keyStoreLocation, char[] masterPassword, Storage storage) throws KeyManagerException { super(keyStoreLocation, masterPassword, storage); this.keystoreLocation = keyStoreLocation; } public Certificate addKey(String keyName, char[] masterPassword) throws KeyManagerException { return addKey( keyName, masterPassword, DEFAULT_SELF_SIGNED_KEY_ALGORITHM, DEFAULT_SELF_SIGNED_KEY_ISSUER ); } public Certificate addKey(String keyName, char[] masterPassword, String issuer) throws KeyManagerException { return addKey(keyName, masterPassword, DEFAULT_SELF_SIGNED_KEY_ALGORITHM, issuer); } public Certificate addKey(String keyName, char[] masterPassword, AsymmetricKeyAlgorithm keyAlgorithm) throws KeyManagerException { return addKey(keyName, masterPassword, keyAlgorithm, DEFAULT_SELF_SIGNED_KEY_ISSUER); } public Certificate addKey(String keyName, char[] masterPassword, AsymmetricKeyAlgorithm keyAlgorithm, String issuer) throws KeyManagerException { try { if (keyName == null || keyName.equals("")) { throw new KeyManagerException( "Implementation error: Null or empty key alias is not allowed." ); } // Generate key... KeyPair keyPair = generateKey(keyAlgorithm); // Sign the public key to create a certificate... Certificate certificate = keySigner.signPublicKey( KeySigner.Configuration.createDefault(keyPair, issuer) ); // Store the private key and public key + certificate in key store... KeyStore.PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry( keyPair.getPrivate(), new java.security.cert.Certificate[] { certificate } ); KeyStore.PasswordProtection keyProtection = new KeyStore.PasswordProtection(masterPassword); if (masterPassword == null || masterPassword.length == 0) { keyProtection = null; } add(keyName, privateKeyEntry, keyProtection); if (keystoreLocation != null) { save(keystoreLocation, masterPassword); } return certificate; } catch (KeySigner.SigningException exception) { throw new KeyManagerException( "Key signing failed: {0}", exception, exception.getMessage() ); } finally { clearPassword(masterPassword); } } public PrivateKey getKey(String alias) throws KeyManagerException { return getKey(alias, EMPTY_KEY_PASSWORD); } public PrivateKey getKey(String alias, char[] password) throws KeyManagerException { KeyStore.Entry entry = retrieveKey(alias, new KeyStore.PasswordProtection(password)); if (entry instanceof KeyStore.PrivateKeyEntry) { KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)entry; return privateKeyEntry.getPrivateKey(); } else { throw new KeyManagerException("Key alias '{0}' is not a private key entry."); } } }
package org.owasp.esapi.reference; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Level; import org.owasp.esapi.ESAPI; import org.owasp.esapi.LogFactory; import org.owasp.esapi.Logger; import org.owasp.esapi.User; public class Log4JLogFactory implements LogFactory { private static volatile LogFactory singletonInstance; public static LogFactory getInstance() { if ( singletonInstance == null ) { synchronized ( Log4JLogFactory.class ) { if ( singletonInstance == null ) { singletonInstance = new Log4JLogFactory(); } } } return singletonInstance; } protected HashMap loggersMap = new HashMap(); protected Log4JLogFactory() {} /** * {@inheritDoc} */ public Logger getLogger(Class clazz) { // If a logger for this class already exists, we return the same one, otherwise we create a new one. Logger classLogger = (Logger) loggersMap.get(clazz); if (classLogger == null) { classLogger = new Log4JLogger(clazz.getName()); loggersMap.put(clazz, classLogger); } return classLogger; } /** * {@inheritDoc} */ public Logger getLogger(String moduleName) { // If a logger for this module already exists, we return the same one, otherwise we create a new one. Logger moduleLogger = (Logger) loggersMap.get(moduleName); if (moduleLogger == null) { moduleLogger = new Log4JLogger(moduleName); loggersMap.put(moduleName, moduleLogger); } return moduleLogger; } protected static class Log4JLogger implements org.owasp.esapi.Logger { /** The log4j object used by this class to log everything. */ private org.apache.log4j.Logger log4jlogger = null; /** The module name using this log. */ private String moduleName = null; /** The application name defined in ESAPI.properties */ private String applicationName=ESAPI.securityConfiguration().getApplicationName(); /** Log the application name? */ private static boolean logAppName = ESAPI.securityConfiguration().getLogApplicationName(); /** Log the server ip? */ private static boolean logServerIP = ESAPI.securityConfiguration().getLogServerIP(); /** * Public constructor should only ever be called via the appropriate LogFactory * * @param moduleName the module name */ protected Log4JLogger(String moduleName) { this.moduleName = moduleName; this.log4jlogger = org.apache.log4j.Logger.getLogger(applicationName + ":" + moduleName); } /** * {@inheritDoc} * Note: In this implementation, this change is not persistent, * meaning that if the application is restarted, the log level will revert to the level defined in the * ESAPI SecurityConfiguration properties file. */ public void setLevel(int level) { try { log4jlogger.setLevel(convertESAPILeveltoLoggerLevel( level )); } catch (IllegalArgumentException e) { this.error(Logger.SECURITY_FAILURE, "", e); } } private static Level convertESAPILeveltoLoggerLevel(int level) { switch (level) { case Logger.OFF: return Level.OFF; case Logger.FATAL: return Level.FATAL; case Logger.ERROR: return Level.ERROR; case Logger.WARNING: return Level.WARN; case Logger.INFO: return Level.INFO; case Logger.DEBUG: return Level.DEBUG; //fine case Logger.TRACE: return Level.TRACE; //finest case Logger.ALL: return Level.ALL; default: { throw new IllegalArgumentException("Invalid logging level. Value was: " + level); } } } /** * {@inheritDoc} */ public void trace(EventType type, String message, Throwable throwable) { log(Level.TRACE, type, message, throwable); } /** * {@inheritDoc} */ public void trace(EventType type, String message) { log(Level.TRACE, type, message, null); } /** * {@inheritDoc} */ public void debug(EventType type, String message, Throwable throwable) { log(Level.DEBUG, type, message, throwable); } /** * {@inheritDoc} */ public void debug(EventType type, String message) { log(Level.DEBUG, type, message, null); } /** * {@inheritDoc} */ public void info(EventType type, String message) { log(Level.INFO, type, message, null); } /** * {@inheritDoc} */ public void info(EventType type, String message, Throwable throwable) { log(Level.INFO, type, message, throwable); } /** * {@inheritDoc} */ public void warning(EventType type, String message, Throwable throwable) { log(Level.WARN, type, message, throwable); } /** * {@inheritDoc} */ public void warning(EventType type, String message) { log(Level.WARN, type, message, null); } /** * {@inheritDoc} */ public void error(EventType type, String message, Throwable throwable) { log(Level.ERROR, type, message, throwable); } /** * {@inheritDoc} */ public void error(EventType type, String message) { log(Level.ERROR, type, message, null); } /** * {@inheritDoc} */ public void fatal(EventType type, String message, Throwable throwable) { log(Level.FATAL, type, message, throwable); } /** * {@inheritDoc} */ public void fatal(EventType type, String message) { log(Level.FATAL, type, message, null); } /** * Log the message after optionally encoding any special characters that might be dangerous when viewed * by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log * injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging * specific session ID, and the current date/time. * * It will only log the message if the current logging level is enabled, otherwise it will * discard the message. * * @param level defines the set of recognized logging levels (TRACE, INFO, DEBUG, WARNING, ERROR, FATAL) * @param type the type of the event (SECURITY SUCCESS, SECURITY FAILURE, EVENT SUCCESS, EVENT FAILURE) * @param message the message * @param throwable the throwable */ private void log(Level level, EventType type, String message, Throwable throwable) { // Check to see if we need to log if (!log4jlogger.isEnabledFor( level )) return; // ensure there's something to log if ( message == null ) { message = ""; } // ensure no CRLF injection into logs for forging records String clean = message.replace( '\n', '_' ).replace( '\r', '_' ); if ( ESAPI.securityConfiguration().getLogEncodingRequired() ) { clean = ESAPI.encoder().encodeForHTML(message); if (!message.equals(clean)) { clean += " (Encoded)"; } } // log server, port, app name, module name -- server:80/app/module StringBuilder appInfo = new StringBuilder(); if ( ESAPI.currentRequest() != null && logServerIP ) { appInfo.append( ESAPI.currentRequest().getLocalAddr() + ":" + ESAPI.currentRequest().getLocalPort() ); } if ( logAppName ) { appInfo.append( "/" + applicationName ); } appInfo.append( "/" + moduleName ); //get the type text if it exists String typeInfo = ""; if (type != null) { typeInfo += type + " "; } // log the message log4jlogger.log(level, "[" + typeInfo + getUserInfo() + " -> " + appInfo + "] " + clean, throwable); } /** * {@inheritDoc} */ public boolean isDebugEnabled() { return log4jlogger.isEnabledFor(Level.DEBUG); } /** * {@inheritDoc} */ public boolean isErrorEnabled() { return log4jlogger.isEnabledFor(Level.ERROR); } /** * {@inheritDoc} */ public boolean isFatalEnabled() { return log4jlogger.isEnabledFor(Level.FATAL); } /** * {@inheritDoc} */ public boolean isInfoEnabled() { return log4jlogger.isEnabledFor(Level.INFO); } /** * {@inheritDoc} */ public boolean isTraceEnabled() { return log4jlogger.isEnabledFor(Level.TRACE); } /** * {@inheritDoc} */ public boolean isWarningEnabled() { return log4jlogger.isEnabledFor(Level.WARN); } public String getUserInfo() { // create a random session number for the user to represent the user's 'session', if it doesn't exist already String sid = null; HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest(); if ( request != null ) { HttpSession session = request.getSession( false ); if ( session != null ) { sid = (String)session.getAttribute("ESAPI_SESSION"); // if there is no session ID for the user yet, we create one and store it in the user's session if ( sid == null ) { sid = ""+ ESAPI.randomizer().getRandomInteger(0, 1000000); session.setAttribute("ESAPI_SESSION", sid); } } } // log user information - username:session@ipaddr User user = ESAPI.authenticator().getCurrentUser(); String userInfo = ""; //TODO - make type logging configurable if ( user != null) { userInfo += user.getAccountName()+ ":" + sid + "@"+ user.getLastHostAddress(); } return userInfo; } } }
module org.openecard.richclient { /* add module if you want to use a debugger on the client like this in the ./bin/openecard file JLINK_VM_OPTIONS="-agentlib:jdwp=transport=dt_socket,address=5000,server=n,suspend=y" */ //requires jdk.jdwp.agent; requires java.smartcardio; requires java.logging; requires java.desktop; requires java.sql; // for jackson serialization requires java.naming; /* JAXB module */ requires java.xml.bind; /* JavaFX modules */ requires javafx.base; requires javafx.controls; requires javafx.graphics; requires javafx.swing; /* EC ciphers for JSSE */ requires jdk.crypto.ec; /* Open JAXB classes for reflection */ opens de.bund.bsi.ecard.api._1; opens iso.std.iso_iec._24727.tech.schema; opens oasis.names.tc.dss._1_0.core.schema; opens oasis.names.tc.dss_x._1_0.profiles.verificationreport.schema_; opens oasis.names.tc.saml._1_0.assertion; opens oasis.names.tc.saml._2_0.assertion; opens org.etsi.uri._01903.v1_3; opens org.etsi.uri._02231.v3_1; opens org.openecard.ws; opens org.openecard.ws.chipgateway; opens org.openecard.ws.schema; opens org.openecard.addon.bind; opens org.openecard.common; opens org.openecard.addon; opens org.openecard.common.sal.state; opens org.openecard.common.event; opens org.openecard.common.interfaces; opens org.openecard.crypto.common.sal.did; opens org.openecard.common.util; opens org.openecard.bouncycastle.util.encoders; opens org.w3._2000._09.xmldsig_; opens org.w3._2001._04.xmldsig_more_; opens org.w3._2001._04.xmlenc_; opens org.w3._2007._05.xmldsig_more_; opens org.w3._2009.xmlenc11_; opens generated; opens org.openecard.mdlw.sal.config to java.xml.bind; opens org.openecard.addon.manifest to java.xml.bind; opens org.openecard.richclient.gui.update; opens jnasmartcardio to java.base; opens org.jose4j.json.internal.json_simple; opens org.slf4j; /* JNA needs access to the jnidispatch lib on osx*/ opens com.sun.jna.darwin; }
package org.app.application; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import org.app.material.AndroidUtilities; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private static final int dotsMenu = 1; private static final int github = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new DialogFragment(), getResources().getString(R.string.Dialogs)); adapter.addFragment(new ListViewFragment(), getResources().getString(R.string.ListView)); adapter.addFragment(new CardFragment(), getResources().getString(R.string.CardView)); adapter.addFragment(new RecyclerFragment(), getResources().getString(R.string.RecyclerView)); if (viewPager != null) { viewPager.setAdapter(adapter); } TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); if (tabLayout != null) { tabLayout.setupWithViewPager(viewPager); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, github, Menu.NONE, getResources().getString(R.string.OpenGithub)).setIcon(AndroidUtilities.getIcon(R.drawable.github_circle, 0xFFFFFFFF)).setShowAsAction(1); menu.add(0, dotsMenu, Menu.NONE, getResources().getString(R.string.PopupMenu)).setIcon(R.drawable.dots_vertical).setShowAsAction(1); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == github) { AndroidUtilities.openUrl(this, getResources().getString(R.string.GithubURL), 0xFF4285f4, R.drawable.abc_ic_menu_share_mtrl_alpha); } return super.onOptionsItemSelected(item); } public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> fragmentList = new ArrayList<>(); private final List<String> fragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } public void addFragment(Fragment fragment, String title) { fragmentList.add(fragment); fragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return fragmentTitleList.get(position); } } }
package org.repoanalyzer.reporeader.commit; import java.util.LinkedList; import java.util.List; public class Author { private LinkedList<String> names; private LinkedList<String> emails; public Author(String name, String email) { this.names = new LinkedList<>(); this.emails = new LinkedList<>(); this.names.add(name); this.emails.add(email); } public List<String> getNames() { return names; } public String getFirstName() { return names.getFirst(); } public List<String> getEmails() { return emails; } public void addName(String name) { names.add(name); } public void addEmail(String email) { emails.add(email); } @Override public String toString(){ return this.getFirstName(); } }
/** * Used by Simperium to create a WebSocket connection to Simperium. Manages Channels * and listens for channel write events. Notifies channels when the connection is connected * or disconnected. * * WebSocketManager is configured by Simperium and shouldn't need to be access directly * by applications. * */ package com.simperium.android; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.simperium.BuildConfig; import com.simperium.client.Bucket; import com.simperium.client.Channel; import com.simperium.client.ChannelProvider; import com.simperium.util.Logger; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executor; public class WebSocketManager implements ChannelProvider, Channel.OnMessageListener { public enum ConnectionStatus { DISCONNECTING, DISCONNECTED, CONNECTING, CONNECTED } public interface Connection { public void close(); public void send(String message); } public interface ConnectionListener { public void onConnect(Connection connection); public void onDisconnect(Exception exception); public void onError(Exception exception); public void onMessage(String message); } public interface ConnectionProvider { public void connect(ConnectionListener connectionListener); } public static final String TAG = "Simperium.WebSocket"; static public final String COMMAND_HEARTBEAT = "h"; static public final String COMMAND_LOG = "log"; static public final String LOG_FORMAT = "%s:%s"; final protected ConnectionProvider mConnectionProvider; protected Connection mConnection = new NullConnection(); private String mAppId, mSessionId; private boolean mReconnect = true; private HashMap<Channel,Integer> mChannelIndex = new HashMap<Channel,Integer>(); private HashMap<Integer,Channel> mChannels = new HashMap<Integer,Channel>(); private HashSet<HeartbeatListener> mHearbeatListeners = new HashSet<HeartbeatListener>(); public static final long HEARTBEAT_INTERVAL = 20000; // 20 seconds static final long DEFAULT_RECONNECT_INTERVAL = 3000; // 3 seconds private Timer mHeartbeatTimer, mReconnectTimer; private int mHeartbeatCount = 0, mLogLevel = 0; private long mReconnectInterval = DEFAULT_RECONNECT_INTERVAL; private ConnectionStatus mConnectionStatus = ConnectionStatus.DISCONNECTED; final protected Channel.Serializer mSerializer; final protected Executor mExecutor; final protected ConnectivityManager mConnectivityManager; public WebSocketManager(Executor executor, String appId, String sessionId, Channel.Serializer channelSerializer, ConnectionProvider connectionProvider) { this(executor, appId, sessionId, channelSerializer, connectionProvider, null); } public WebSocketManager(Executor executor, String appId, String sessionId, Channel.Serializer channelSerializer, ConnectionProvider connectionProvider, Context context) { mExecutor = executor; mAppId = appId; mSessionId = sessionId; mSerializer = channelSerializer; mConnectionProvider = connectionProvider; if (context != null) { mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean noConnection = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (!noConnection && mReconnect) { connect(); } } }, filter); } else { mConnectivityManager = null; } } /** * Creates a channel for the bucket. Starts the websocket connection if not connected * */ @Override public Channel buildChannel(Bucket bucket) { // create a channel Channel channel = new Channel(mExecutor, mAppId, mSessionId, bucket, mSerializer, this); int channelId = mChannels.size(); mChannelIndex.put(channel, channelId); mChannels.put(channelId, channel); // If we're not connected then connect, if we don't have a user // access token we'll have to hold off until the user does have one if (!isConnected() && bucket.getUser().hasAccessToken()) { connect(); } else if (isConnected()) { channel.onConnect(); } return channel; } @Override public void log(int level, CharSequence message) { try { JSONObject log = new JSONObject(); log.put(COMMAND_LOG, message.toString()); log(level, log); } catch (JSONException e) { Logger.log(TAG, "Could not send log", e); } } protected void log(int level, JSONObject log) { // no logging if disabled if (mLogLevel == ChannelProvider.LOG_DISABLED) return; boolean send = level <= mLogLevel; if (BuildConfig.DEBUG) Log.d(TAG, "Log " + level + " => " + log); if (send) send(String.format(LOG_FORMAT, COMMAND_LOG, log)); } public void addHeartbeatListener(HeartbeatListener listener) { mHearbeatListeners.add(listener); } @Override public int getLogLevel() { return mLogLevel; } public void connect() { // if we have channels, then connect, otherwise wait for a channel cancelReconnect(); if (BuildConfig.DEBUG) { Log.d(TAG, "Asked to connect"); } if (isConnected() || isConnecting() || mChannels.isEmpty()) { // do not attempt to connect, we don't need to return; } if (BuildConfig.DEBUG) { Log.d(TAG, "Connecting"); } Logger.log(TAG, "Connecting to simperium"); setConnectionStatus(ConnectionStatus.CONNECTING); mReconnect = true; // if there is no network available, do not attempt to connect if (!isNetworkConnected()) { if (BuildConfig.DEBUG) { Log.d(TAG, "Network Manager reports no connection available. Wait for network."); } setConnectionStatus(ConnectionStatus.DISCONNECTED); return; } mConnectionProvider.connect(new ConnectionListener() { public void onError(Exception exception) { mConnection = new NullConnection(); WebSocketManager.this.onError(exception); } public void onConnect(Connection connection) { mConnection = connection; WebSocketManager.this.onConnect(); } public void onMessage(String message) { WebSocketManager.this.onMessage(message); } public void onDisconnect(Exception exception) { mConnection = new NullConnection(); WebSocketManager.this.onDisconnect(exception); } }); } protected void send(String message) { if (!isConnected()) return; synchronized(this) { mConnection.send(message); } } public void disconnect() { // disconnect the channel mReconnect = false; cancelReconnect(); if (isConnected()) { setConnectionStatus(ConnectionStatus.DISCONNECTING); Logger.log(TAG, "Disconnecting"); // being told to disconnect so don't automatically reconnect mConnection.close(); onDisconnect(null); } } public boolean isConnected() { return mConnectionStatus == ConnectionStatus.CONNECTED; } public boolean isConnecting() { return mConnectionStatus == ConnectionStatus.CONNECTING; } public boolean isDisconnected() { return mConnectionStatus == ConnectionStatus.DISCONNECTED; } public boolean isDisconnecting() { return mConnectionStatus == ConnectionStatus.DISCONNECTING; } public boolean getConnected() { return isConnected(); } protected void setConnectionStatus(ConnectionStatus status) { mConnectionStatus = status; } private void notifyChannelsConnected() { for(Channel channel : mChannelIndex.keySet()) { channel.onConnect(); } } private void notifyChannelsDisconnected() { for(Channel channel : mChannelIndex.keySet()) { channel.onDisconnect(); } } private void cancelHeartbeat() { if(mHeartbeatTimer != null) mHeartbeatTimer.cancel(); mHeartbeatCount = 0; } private void scheduleHeartbeat() { cancelHeartbeat(); mHeartbeatTimer = new Timer(); mHeartbeatTimer.schedule(new TimerTask() { public void run() { sendHearbeat(); } }, HEARTBEAT_INTERVAL); } synchronized private void sendHearbeat() { mHeartbeatCount ++; String command = String.format(Locale.US, "%s:%d", COMMAND_HEARTBEAT, mHeartbeatCount); send(command); } private void cancelReconnect() { if (mReconnectTimer != null) { mReconnectTimer.cancel(); mReconnectTimer = null; } } private void scheduleReconnect() { // check if we're not already trying to reconnect if (mReconnectTimer != null) return; mReconnectTimer = new Timer(); // exponential backoff long retryIn = nextReconnectInterval(); try { mReconnectTimer.schedule(new TimerTask() { public void run() { connect(); } }, retryIn); } catch (IllegalStateException | NullPointerException e) { Logger.log(TAG, "Unable to schedule timer", e); return; } Logger.log(String.format(Locale.US, "Retrying in %d", retryIn)); } // duplicating javascript reconnect interval calculation // doesn't do exponential backoff private long nextReconnectInterval() { long current = mReconnectInterval; if (mReconnectInterval < 4000) { mReconnectInterval ++; } else { mReconnectInterval = 15000; } return current; } /** * * Channel.OnMessageListener event listener * */ @Override public void onMessage(Channel.MessageEvent event) { Channel channel = (Channel)event.getSource(); Integer channelId = mChannelIndex.get(channel); // Prefix the message with the correct channel id String message = String.format(Locale.US, "%d:%s", channelId, event.getMessage()); send(message); } @Override public void onClose(Channel fromChannel) { // if we're allready disconnected we can ignore if (isDisconnected()) return; // check if all channels are disconnected and if so disconnect from the socket for (Channel channel : mChannels.values()) { if (channel.isStarted()) return; } Logger.log(TAG, String.format(Locale.US, "%s disconnect from socket", Thread.currentThread().getName())); disconnect(); } @Override public void onOpen(Channel fromChannel) { connect(); } static public final String BUCKET_NAME_KEY = "bucket"; @Override public void onLog(Channel channel, int level, CharSequence message) { try { JSONObject log = new JSONObject(); log.put(COMMAND_LOG, message); log.put(BUCKET_NAME_KEY, channel.getBucketName()); log(level, log); } catch (JSONException e) { Logger.log(TAG, "Unable to send channel log message", e); } } protected void onConnect() { Logger.log(TAG, String.format("Connected")); setConnectionStatus(ConnectionStatus.CONNECTED); notifyChannelsConnected(); mHeartbeatCount = 0; // reset heartbeat count scheduleHeartbeat(); cancelReconnect(); mReconnectInterval = DEFAULT_RECONNECT_INTERVAL; } protected void onMessage(String message) { if (BuildConfig.DEBUG) { Log.d(TAG, "Received Message: " + message); } scheduleHeartbeat(); String[] parts = message.split(":", 2); if (parts[0].equals(COMMAND_HEARTBEAT)) { mHeartbeatCount = Integer.parseInt(parts[1]); for (HeartbeatListener listener : mHearbeatListeners) { listener.onBeat(); } return; } else if (parts[0].equals(COMMAND_LOG)) { mLogLevel = Integer.parseInt(parts[1]); return; } try { int channelId = Integer.parseInt(parts[0]); Channel channel = mChannels.get(channelId); channel.receiveMessage(parts[1]); } catch (NumberFormatException e) { Logger.log(TAG, String.format(Locale.US, "Unhandled message %s", parts[0])); } } protected void onDisconnect(Exception ex) { Logger.log(TAG, String.format(Locale.US, "Disconnect %s", ex)); setConnectionStatus(ConnectionStatus.DISCONNECTED); notifyChannelsDisconnected(); cancelHeartbeat(); if(mReconnect) scheduleReconnect(); } protected void onError(Exception error) { Logger.log(TAG, String.format(Locale.US, "Error: %s", error), error); setConnectionStatus(ConnectionStatus.DISCONNECTED); if (java.io.IOException.class.isAssignableFrom(error.getClass()) && mReconnect) { scheduleReconnect(); } } private boolean isNetworkConnected() { // if there is no connectivity manager, assume network is avilable if (mConnectivityManager == null) { if (BuildConfig.DEBUG) { Log.d(TAG, "No network manager available"); } return true; } final NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo(); if (networkInfo == null) { if (BuildConfig.DEBUG) { Log.d(TAG, "No network available"); } return false; } if (BuildConfig.DEBUG) { Log.d(TAG, "Network info available: " + networkInfo); } return networkInfo.isConnected(); } private class NullConnection implements Connection { @Override public void close() { // noop } @Override public void send(String message) { // noop } } }
package io.galeb.router.handlers; import io.galeb.core.enums.SystemEnv; import io.galeb.core.entity.BalancePolicy; import io.galeb.core.entity.Pool; import io.galeb.router.client.ExtendedLoadBalancingProxyClient; import io.galeb.router.client.hostselectors.HostSelector; import io.galeb.router.client.hostselectors.HostSelectorLookup; import io.galeb.router.ResponseCodeOnError; import io.galeb.router.client.hostselectors.RoundRobinHostSelector; import io.undertow.client.UndertowClient; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.proxy.ExclusivityChecker; import io.undertow.server.handlers.proxy.ProxyHandler; import io.undertow.util.Headers; import io.undertow.util.HttpString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; public class PoolHandler implements HttpHandler { private static final String CHECK_RULE_HEADER = "X-Check-Pool"; private static final String X_POOL_NAME_HEADER = "X-Pool-Name"; public static final String PROP_CONN_PER_THREAD = "connPerThread"; public static final String PROP_DISCOVERED_MEMBERS_SIZE = "discoveredMembersSize"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final int maxRequestTime = Integer.parseInt(SystemEnv.POOL_MAX_REQUEST_TIME.getValue()); private final boolean reuseXForwarded = Boolean.parseBoolean(SystemEnv.REUSE_XFORWARDED.getValue()); private final boolean rewriteHostHeader = Boolean.parseBoolean(SystemEnv.REWRITE_HOST_HEADER.getValue()); private final String requestIDHeader = SystemEnv.REQUESTID_HEADER.getValue(); private final HttpHandler defaultHandler; private ProxyHandler proxyHandler = null; private RequestIDHandler requestIDHandler = null; private ExtendedLoadBalancingProxyClient proxyClient; private final Pool pool; public PoolHandler(final Pool pool) { this.pool = pool; this.defaultHandler = buildPoolHandler(); if (!"".equals(requestIDHeader)) { this.requestIDHandler = new RequestIDHandler(requestIDHeader); } } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.getRequestHeaders().contains(CHECK_RULE_HEADER)) { healthcheckPoolHandler().handleRequest(exchange); return; } if (proxyClient != null && proxyClient.isHostsEmpty()) { ResponseCodeOnError.HOSTS_EMPTY.getHandler().handleRequest(exchange); return; } if (requestIDHandler != null) { requestIDHandler.handleRequest(exchange); } if (proxyHandler != null) { proxyHandler.handleRequest(exchange); } else { defaultHandler.handleRequest(exchange); } } public Pool getPool() { return pool; } public ProxyHandler getProxyHandler() { return proxyHandler; } private synchronized HttpHandler buildPoolHandler() { return exchange -> { if (pool != null) { logger.info("creating pool " + pool.getName()); proxyClient = getProxyClient(); addTargets(proxyClient); proxyHandler = new ProxyHandler(proxyClient, maxRequestTime, badGatewayHandler(), rewriteHostHeader, reuseXForwarded); proxyHandler.handleRequest(exchange); return; } ResponseCodeOnError.POOL_NOT_DEFINED.getHandler().handleRequest(exchange); }; } private ExtendedLoadBalancingProxyClient getProxyClient() { final HostSelector hostSelector = defineHostSelector(); logger.info("[Pool " + pool.getName() + "] HostSelector: " + hostSelector.getClass().getSimpleName()); final ExclusivityChecker exclusivityChecker = exclusivityCheckerExchange -> exclusivityCheckerExchange.getRequestHeaders().contains(Headers.UPGRADE); return new ExtendedLoadBalancingProxyClient(UndertowClient.getInstance(), exclusivityChecker, hostSelector) .setTtl(Integer.parseInt(SystemEnv.POOL_CONN_TTL.getValue())) .setConnectionsPerThread(getConnPerThread()) .setSoftMaxConnectionsPerThread(Integer.parseInt(SystemEnv.POOL_SOFTMAXCONN.getValue())); } private int getConnPerThread() { int poolMaxConn = Integer.parseInt(SystemEnv.POOL_MAXCONN.getValue()); int connPerThread = poolMaxConn / Integer.parseInt(SystemEnv.IO_THREADS.getValue()); String propConnPerThread = pool.getProperties().get(PROP_CONN_PER_THREAD); if (propConnPerThread != null) { try { connPerThread = Integer.parseInt(propConnPerThread); } catch (NumberFormatException ignore) {} } String discoveredMembersStr = pool.getProperties().get(PROP_DISCOVERED_MEMBERS_SIZE); float discoveredMembers = 1.0f; if (discoveredMembersStr != null && !"".equals(discoveredMembersStr)) { discoveredMembers = Float.parseFloat(discoveredMembersStr); } float discoveryMembersSize = Math.max(discoveredMembers, 1.0f); connPerThread = Math.round((float) connPerThread / discoveryMembersSize); return connPerThread; } private HttpHandler badGatewayHandler() { return exchange -> exchange.setStatusCode(502); } private HostSelector defineHostSelector() { BalancePolicy hostSelectorName = pool.getBalancePolicy(); if (hostSelectorName != null) { return HostSelectorLookup.getHostSelector(hostSelectorName.getName()); } return new RoundRobinHostSelector(); } private void addTargets(final ExtendedLoadBalancingProxyClient proxyClient) { pool.getTargets().forEach(target -> { String value = target.getName(); URI uri = URI.create(target.getName()); proxyClient.addHost(uri); logger.info("[pool:" + pool.getName() + "] added Target " + value); }); } private HttpHandler healthcheckPoolHandler() { return exchange -> { logger.warn("detected header " + CHECK_RULE_HEADER); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseHeaders().put(Headers.SERVER, "GALEB"); exchange.getResponseHeaders().put(HttpString.tryFromString(X_POOL_NAME_HEADER), pool.getName()); exchange.getResponseSender().send("POOL_REACHABLE"); }; } }
package org.msf.records.ui; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import org.msf.records.R; import org.msf.records.filter.FilterGroup; import org.msf.records.filter.FilterManager; import org.msf.records.filter.LocationUuidFilter; import org.msf.records.filter.SimpleSelectionFilter; import org.msf.records.net.Constants; import org.msf.records.utils.PatientCountDisplay; // TODO(akalachman): Split RoundActivity from Triage and Discharged, which may behave differently. public class RoundActivity extends PatientSearchActivity { private String mLocationName; private String mLocationUuid; private int mLocationPatientCount; private SingleLocationPatientListFragment mFragment; private SimpleSelectionFilter mFilter; public static final String LOCATION_NAME_KEY = "location_name"; public static final String LOCATION_PATIENT_COUNT_KEY = "location_patient_count"; public static final String LOCATION_UUID_KEY = "location_uuid"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { mLocationName = getIntent().getStringExtra(LOCATION_NAME_KEY); mLocationPatientCount = getIntent().getIntExtra(LOCATION_PATIENT_COUNT_KEY, 0); mLocationUuid = getIntent().getStringExtra(LOCATION_UUID_KEY); } else { mLocationName = savedInstanceState.getString(LOCATION_NAME_KEY); mLocationPatientCount = getIntent().getIntExtra(LOCATION_PATIENT_COUNT_KEY, 0); mLocationUuid = savedInstanceState.getString(LOCATION_UUID_KEY); } setTitle(PatientCountDisplay.getPatientCountTitle( this, mLocationPatientCount, mLocationName)); setContentView(R.layout.activity_round); mFilter = new FilterGroup( FilterManager.getDefaultFilter(), new LocationUuidFilter(mLocationUuid)); } @Override public void onExtendOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); // TODO(akalachman): Move this back to onCreate when I figure out why it needs to be here. mFragment = (SingleLocationPatientListFragment)getSupportFragmentManager() .findFragmentById(R.id.round_patient_list); mFragment.filterBy(mFilter); menu.findItem(R.id.action_add).setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { OdkActivityLauncher.fetchAndShowXform( RoundActivity.this, Constants.ADD_PATIENT_UUID, ODK_ACTIVITY_REQUEST); return true; } }); super.onExtendOptionsMenu(menu); } }
// Description: See the class level JavaDoc comments. package com.microsoft.live; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.http.client.HttpClient; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.net.http.SslError; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.SslErrorHandler; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; /** * AuthorizationRequest performs an Authorization Request by launching a WebView Dialog that * displays the login and consent page and then, on a successful login and consent, performs an * async AccessToken request. */ class AuthorizationRequest implements ObservableOAuthRequest, OAuthRequestObserver { /** * OAuthDialog is a Dialog that contains a WebView. The WebView loads the passed in Uri, and * loads the passed in WebViewClient that allows the WebView to be observed (i.e., when a page * loads the WebViewClient will be notified). */ private class OAuthDialog extends Dialog implements OnCancelListener { /** * AuthorizationWebViewClient is a static (i.e., does not have access to the instance that * created it) class that checks for when the end_uri is loaded in to the WebView and calls * the AuthorizationRequest's onEndUri method. */ private class AuthorizationWebViewClient extends WebViewClient { private final CookieManager cookieManager; private final Set<String> cookieKeys; public AuthorizationWebViewClient() { // I believe I need to create a syncManager before I can use a cookie manager. CookieSyncManager.createInstance(getContext()); this.cookieManager = CookieManager.getInstance(); this.cookieKeys = new HashSet<String>(); } /** * Call back used when a page is being started. * * This will check to see if the given URL is one of the end_uris/redirect_uris and * based on the query parameters the method will either return an error, or proceed with * an AccessTokenRequest. * * @param view {@link WebView} that this is attached to. * @param url of the page being started */ @Override public void onPageFinished(WebView view, String url) { Uri uri = Uri.parse(url); // only clear cookies that are on the logout domain. if (uri.getHost().equals(Config.INSTANCE.getOAuthLogoutUri().getHost())) { this.saveCookiesInMemory(this.cookieManager.getCookie(url)); } Uri endUri = Config.INSTANCE.getOAuthDesktopUri(); boolean isEndUri = UriComparator.INSTANCE.compare(uri, endUri) == 0; if (!isEndUri) { return; } this.saveCookiesToPreferences(); AuthorizationRequest.this.onEndUri(uri); OAuthDialog.this.dismiss(); } /** * Callback when the WebView received an Error. * * This method will notify the listener about the error and dismiss the WebView dialog. * * @param view the WebView that received the error * @param errorCode the error code corresponding to a WebViewClient.ERROR_* value * @param description the String containing the description of the error * @param failingUrl the url that encountered an error */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { AuthorizationRequest.this.onError("", description, failingUrl); OAuthDialog.this.dismiss(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // TODO: Android does not like the SSL certificate we use, because it has '*' in // it. Proceed with the errors. handler.proceed(); } private void saveCookiesInMemory(String cookie) { // Not all URLs will have cookies if (TextUtils.isEmpty(cookie)) { return; } String[] pairs = TextUtils.split(cookie, "; "); for (String pair : pairs) { int index = pair.indexOf(EQUALS); String key = pair.substring(0, index); this.cookieKeys.add(key); } } private void saveCookiesToPreferences() { SharedPreferences preferences = getContext().getSharedPreferences(PreferencesConstants.FILE_NAME, Context.MODE_PRIVATE); // If the application tries to login twice, before calling logout, there could // be a cookie that was sent on the first login, that was not sent in the second // login. So, read the cookies in that was saved before, and perform a union // with the new cookies. String value = preferences.getString(PreferencesConstants.COOKIES_KEY, ""); String[] valueSplit = TextUtils.split(value, PreferencesConstants.COOKIE_DELIMITER); this.cookieKeys.addAll(Arrays.asList(valueSplit)); Editor editor = preferences.edit(); value = TextUtils.join(PreferencesConstants.COOKIE_DELIMITER, this.cookieKeys); editor.putString(PreferencesConstants.COOKIES_KEY, value); editor.commit(); // we do not need to hold on to the cookieKeys in memory anymore. // It could be garbage collected when this object does, but let's clear it now, // since it will not be used again in the future. this.cookieKeys.clear(); } } /** Uri to load */ private final Uri requestUri; /** * Constructs a new OAuthDialog. * * @param context to construct the Dialog in * @param requestUri to load in the WebView * @param webViewClient to be placed in the WebView */ public OAuthDialog(Uri requestUri) { super(AuthorizationRequest.this.activity, android.R.style.Theme_Translucent_NoTitleBar); this.setOwnerActivity(AuthorizationRequest.this.activity); assert requestUri != null; this.requestUri = requestUri; } /** Called when the user hits the back button on the dialog. */ @Override public void onCancel(DialogInterface dialog) { LiveAuthException exception = new LiveAuthException(ErrorMessages.SIGNIN_CANCEL); AuthorizationRequest.this.onException(exception); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setOnCancelListener(this); FrameLayout content = new FrameLayout(this.getContext()); LinearLayout webViewContainer = new LinearLayout(this.getContext()); WebView webView = new WebView(this.getContext()); webView.setWebViewClient(new AuthorizationWebViewClient()); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadUrl(this.requestUri.toString()); webView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webView.setVisibility(View.VISIBLE); webViewContainer.addView(webView); webViewContainer.setVisibility(View.VISIBLE); content.addView(webViewContainer); content.setVisibility(View.VISIBLE); content.forceLayout(); webViewContainer.forceLayout(); this.addContentView(content, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } } /** * Compares just the scheme, authority, and path. It does not compare the query parameters or * the fragment. */ private enum UriComparator implements Comparator<Uri> { INSTANCE; @Override public int compare(Uri lhs, Uri rhs) { String[] lhsParts = { lhs.getScheme(), lhs.getAuthority(), lhs.getPath() }; String[] rhsParts = { rhs.getScheme(), rhs.getAuthority(), rhs.getPath() }; assert lhsParts.length == rhsParts.length; for (int i = 0; i < lhsParts.length; i++) { int compare = lhsParts[i].compareTo(rhsParts[i]); if (compare != 0) { return compare; } } return 0; } } private static final String AMPERSAND = "&"; private static final String EQUALS = "="; /** * Turns the fragment parameters of the uri into a map. * * @param uri to get fragment parameters from * @return a map containing the fragment parameters */ private static Map<String, String> getFragmentParametersMap(Uri uri) { String fragment = uri.getFragment(); String[] keyValuePairs = TextUtils.split(fragment, AMPERSAND); Map<String, String> fragementParameters = new HashMap<String, String>(); for (String keyValuePair : keyValuePairs) { int index = keyValuePair.indexOf(EQUALS); String key = keyValuePair.substring(0, index); String value = keyValuePair.substring(index + 1); fragementParameters.put(key, value); } return fragementParameters; } private final Activity activity; private final HttpClient client; private final String clientId; private final DefaultObservableOAuthRequest observable; private final String redirectUri; private final String scope; public AuthorizationRequest(Activity activity, HttpClient client, String clientId, String redirectUri, String scope) { assert activity != null; assert client != null; assert !TextUtils.isEmpty(clientId); assert !TextUtils.isEmpty(redirectUri); assert !TextUtils.isEmpty(scope); this.activity = activity; this.client = client; this.clientId = clientId; this.redirectUri = redirectUri; this.observable = new DefaultObservableOAuthRequest(); this.scope = scope; } @Override public void addObserver(OAuthRequestObserver observer) { this.observable.addObserver(observer); } /** * Launches the login/consent page inside of a Dialog that contains a WebView and then performs * a AccessTokenRequest on successful login and consent. This method is async and will call the * passed in listener when it is completed. */ public void execute() { String displayType = this.getDisplayParameter(); String responseType = OAuth.ResponseType.CODE.toString().toLowerCase(Locale.US); String locale = Locale.getDefault().toString(); Uri requestUri = Config.INSTANCE.getOAuthAuthorizeUri() .buildUpon() .appendQueryParameter(OAuth.CLIENT_ID, this.clientId) .appendQueryParameter(OAuth.SCOPE, this.scope) .appendQueryParameter(OAuth.DISPLAY, displayType) .appendQueryParameter(OAuth.RESPONSE_TYPE, responseType) .appendQueryParameter(OAuth.LOCALE, locale) .appendQueryParameter(OAuth.REDIRECT_URI, this.redirectUri) .build(); OAuthDialog oAuthDialog = new OAuthDialog(requestUri); oAuthDialog.show(); } @Override public void onException(LiveAuthException exception) { this.observable.notifyObservers(exception); } @Override public void onResponse(OAuthResponse response) { this.observable.notifyObservers(response); } @Override public boolean removeObserver(OAuthRequestObserver observer) { return this.observable.removeObserver(observer); } /** * Gets the display parameter by looking at the screen size of the activity. * @return "android_phone" for phones and "android_tablet" for tablets. */ private String getDisplayParameter() { ScreenSize screenSize = ScreenSize.determineScreenSize(this.activity); DeviceType deviceType = screenSize.getDeviceType(); return deviceType.getDisplayParameter().toString().toLowerCase(Locale.US); } private void onAccessTokenResponse(Map<String, String> fragmentParameters) { assert fragmentParameters != null; OAuthSuccessfulResponse response; try { response = OAuthSuccessfulResponse.createFromFragment(fragmentParameters); } catch (LiveAuthException e) { this.onException(e); return; } this.onResponse(response); } private void onAuthorizationResponse(String code) { assert !TextUtils.isEmpty(code); // Since we DO have an authorization code, launch an AccessTokenRequest. // We do this asynchronously to prevent the HTTP IO from occupying the // UI/main thread (which we are on right now). AccessTokenRequest request = new AccessTokenRequest(this.client, this.clientId, this.redirectUri, code); TokenRequestAsync requestAsync = new TokenRequestAsync(request); // We want to know when this request finishes, because we need to notify our // observers. requestAsync.addObserver(this); requestAsync.execute(); } /** * Called when the end uri is loaded. * * This method will read the uri's query parameters and fragment, and respond with the * appropriate action. * * @param endUri that was loaded */ private void onEndUri(Uri endUri) { // If we are on an end uri, the response could either be in // the fragment or the query parameters. The response could // either be successful or it could contain an error. // Check all situations and call the listener's appropriate callback. // Callback the listener on the UI/main thread. We could call it right away since // we are on the UI/main thread, but it is probably better that we finish up with // the WebView code before we callback on the listener. boolean hasFragment = endUri.getFragment() != null; boolean hasQueryParameters = endUri.getQuery() != null; boolean invalidUri = !hasFragment && !hasQueryParameters; // check for an invalid uri, and leave early if (invalidUri) { this.onInvalidUri(); return; } if (hasFragment) { Map<String, String> fragmentParameters = AuthorizationRequest.getFragmentParametersMap(endUri); boolean isSuccessfulResponse = fragmentParameters.containsKey(OAuth.ACCESS_TOKEN) && fragmentParameters.containsKey(OAuth.TOKEN_TYPE); if (isSuccessfulResponse) { this.onAccessTokenResponse(fragmentParameters); return; } String error = fragmentParameters.get(OAuth.ERROR); if (error != null) { String errorDescription = fragmentParameters.get(OAuth.ERROR_DESCRIPTION); String errorUri = fragmentParameters.get(OAuth.ERROR_URI); this.onError(error, errorDescription, errorUri); return; } } if (hasQueryParameters) { String code = endUri.getQueryParameter(OAuth.CODE); if (code != null) { this.onAuthorizationResponse(code); return; } String error = endUri.getQueryParameter(OAuth.ERROR); if (error != null) { String errorDescription = endUri.getQueryParameter(OAuth.ERROR_DESCRIPTION); String errorUri = endUri.getQueryParameter(OAuth.ERROR_URI); this.onError(error, errorDescription, errorUri); return; } } // if the code reaches this point, the uri was invalid // because it did not contain either a successful response // or an error in either the queryParameter or the fragment this.onInvalidUri(); } /** * Called when end uri had an error in either the fragment or the query parameter. * * This method constructs the proper exception, calls the listener's appropriate callback method * on the main/UI thread, and then dismisses the dialog window. * * @param error containing an error code * @param errorDescription optional text with additional information * @param errorUri optional uri that is associated with the error. */ private void onError(String error, String errorDescription, String errorUri) { LiveAuthException exception = new LiveAuthException(error, errorDescription, errorUri); this.onException(exception); } /** * Called when an invalid uri (i.e., a uri that does not contain an error or a successful * response). * * This method constructs an exception, calls the listener's appropriate callback on the main/UI * thread, and then dismisses the dialog window. */ private void onInvalidUri() { LiveAuthException exception = new LiveAuthException(ErrorMessages.SERVER_ERROR); this.onException(exception); } }
package org.tndata.android.compass.model; import android.content.Context; import android.widget.ImageView; import org.tndata.android.compass.util.ImageCache; import java.io.Serializable; import java.util.ArrayList; public class Behavior extends TDCBase implements Serializable, Comparable<Behavior> { private static final long serialVersionUID = 7747989797893422842L; private String more_info = ""; private String html_more_info = ""; private String external_resource = ""; private String notification_text = ""; private String icon_url = ""; private String image_url = ""; private ArrayList<Goal> goals = new ArrayList<Goal>(); private ArrayList<Action> actions = new ArrayList<Action>(); public Behavior() { } public Behavior(int id, int order, String title, String titleSlug, String description, String html_description, String moreInfo, String htmlMoreInfo, String externalResource, String notificationText, String iconUrl, String imageUrl) { super(id, title, titleSlug, description, html_description); this.more_info = moreInfo; this.html_more_info = htmlMoreInfo; this.external_resource = externalResource; this.notification_text = notificationText; this.icon_url = iconUrl; this.image_url = imageUrl; } public Behavior(int id, int order, String title, String titleSlug, String description, String html_description, String moreInfo, String htmlMoreInfo, String externalResource, String notificationText, String iconUrl, String imageUrl, ArrayList<Goal> goals) { super(id, title, titleSlug, description, html_description); this.more_info = moreInfo; this.html_more_info = htmlMoreInfo; this.external_resource = externalResource; this.notification_text = notificationText; this.icon_url = iconUrl; this.image_url = imageUrl; this.goals = goals; } public String getMoreInfo() { return more_info; } public String getHTMLMoreInfo() { return html_more_info; } public void setMoreInfo(String more_info) { this.more_info = more_info; } public void setHTMLMoreInfo(String html_more_info) { this.html_more_info = html_more_info; } public String getExternalResource() { return external_resource; } public void setExternalResource(String external_resource) { this.external_resource = external_resource; } public String getNotificationText() { return notification_text; } public void setNotificationText(String notification_text) { this.notification_text = notification_text; } public String getIconUrl() { return icon_url; } public void setIconUrl(String icon_url) { this.icon_url = icon_url; } public String getImageUrl() { return image_url; } public void setImageUrl(String image_url) { this.image_url = image_url; } public ArrayList<Goal> getGoals() { return goals; } public void setGoals(ArrayList<Goal> goals) { this.goals = goals; } public ArrayList<Action> getActions() { return actions; } public void setActions(ArrayList<Action> actions) { this.actions = actions; } @Override public boolean equals(Object object) { boolean result = false; if (object == null) { result = false; } else if (object == this) { result = true; } else if (object instanceof Behavior) { if (this.getId() == ((Behavior) object).getId()) { result = true; } } return result; } @Override public int hashCode() { int hash = 3; hash = 7 * hash + this.getTitle().hashCode(); return hash; } @Override public int compareTo(Behavior another) { if (getId() == another.getId()) { return 0; } else if (getId() < another.getId()) { return -1; } else return 1; } /** * Given a Context and an ImageView, load this Behavior's icon into the ImageView. * * @param context: an application context * @param imageView: an ImageView */ public void loadIconIntoView(Context context, ImageView imageView) { String iconUrl = getIconUrl(); if(iconUrl != null && !iconUrl.isEmpty()) { ImageCache.instance(context).loadBitmap(imageView, iconUrl, false); } } }
package dyvil.tools.repl.command; import dyvil.collection.Set; import dyvil.collection.mutable.IdentityHashSet; import dyvil.collection.mutable.TreeSet; import dyvil.reflect.Modifiers; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.classes.IClassBody; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.field.IDataMember; import dyvil.tools.compiler.ast.field.IField; import dyvil.tools.compiler.ast.field.IProperty; import dyvil.tools.compiler.ast.member.IMember; import dyvil.tools.compiler.ast.method.IMethod; import dyvil.tools.compiler.ast.parameter.IParameter; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.Types; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.lexer.BaseSymbols; import dyvil.tools.repl.DyvilREPL; import dyvil.tools.repl.REPLContext; public class CompleteCommand implements ICommand { @Override public String getName() { return "complete"; } @Override public String getDescription() { return "Prints a list of possible completions"; } @Override public void execute(DyvilREPL repl, String... args) { REPLContext context = repl.getContext(); if (args.length == 0) { // REPL Variables this.printMembers(repl, context, ""); return; } String argument = args[0]; int index = args[0].indexOf('.'); if (index <= 0) { // REPL Variable Completions this.printMembers(repl, context, BaseSymbols.qualify(argument)); return; } Name varName = Name.get(argument.substring(0, index)); String memberStart = BaseSymbols.qualify(argument.substring(index + 1)); IDataMember variable = context.resolveField(varName); if (variable != null) { // Field Completions IType type = variable.getType(); repl.getOutput().println("Available completions for '" + varName + "' of type '" + type + "':"); this.printCompletions(repl, memberStart, type, false); return; } IType type = IContext.resolveType(context, varName); if (type != null) { // Type Completions repl.getOutput().println("Available completions for type '" + type + "':"); this.printCompletions(repl, memberStart, type, true); return; } // No Completions available repl.getOutput().println("'" + varName + "' could not be resolved"); return; } private void printCompletions(DyvilREPL repl, String memberStart, IType type, boolean statics) { Set<String> fields = new TreeSet<>(); Set<String> properties = new TreeSet<>(); Set<String> methods = new TreeSet<>(); this.findCompletions(type, fields, properties, methods, memberStart, statics, new IdentityHashSet<>()); boolean output = false; if (!fields.isEmpty()) { output = true; repl.getOutput().println("Fields:"); for (String field : fields) { repl.getOutput().print('\t'); repl.getOutput().println(field); } } if (!properties.isEmpty()) { output = true; repl.getOutput().println("Properties:"); for (String property : properties) { repl.getOutput().print('\t'); repl.getOutput().println(property); } } if (!methods.isEmpty()) { output = true; repl.getOutput().println("Methods:"); for (String method : methods) { repl.getOutput().print('\t'); repl.getOutput().println(method); } } if (!output) { if (statics) { repl.getOutput().println("No static completions available for type " + type); } else { repl.getOutput().println("No completions available for type " + type); } } } private void printMembers(DyvilREPL repl, REPLContext context, String start) { Set<String> fields = new TreeSet<>(); Set<String> methods = new TreeSet<>(); for (IField variable : context.getFields().values()) { if (variable.getName().startWith(start)) { fields.add(getSignature(Types.UNKNOWN, variable)); } } for (IMethod method : context.getMethods()) { if (method.getName().startWith(start)) { methods.add(getSignature(Types.UNKNOWN, method)); } } boolean output = false; if (!fields.isEmpty()) { output = true; repl.getOutput().println("Fields:"); for (String field : fields) { repl.getOutput().print('\t'); repl.getOutput().println(field); } } if (!methods.isEmpty()) { output = true; repl.getOutput().println("Methods:"); for (String method : methods) { repl.getOutput().print('\t'); repl.getOutput().println(method); } } if (!output) { repl.getOutput().println("No completions available"); } } private void findCompletions(IType type, Set<String> fields, Set<String> properties, Set<String> methods, String start, boolean statics, Set<IClass> dejaVu) { IClass iclass = type.getTheClass(); if (dejaVu.contains(iclass)) { return; } dejaVu.add(iclass); // Add members for (int i = 0, count = iclass.parameterCount(); i < count; i++) { final IParameter parameter = iclass.getParameter(i); if (matches(start, parameter, statics)) { fields.add(getSignature(type, parameter)); } } final IClassBody body = iclass.getBody(); if (body != null) { for (int i = 0, count = body.fieldCount(); i < count; i++) { final IField field = body.getField(i); if (matches(start, field, statics)) { fields.add(getSignature(type, field)); } } for (int i = 0, count = body.propertyCount(); i < count; i++) { final IProperty property = body.getProperty(i); if (matches(start, property, statics)) { properties.add(getSignature(type, property)); } } for (int i = 0, count = body.methodCount(); i < count; i++) { final IMethod method = body.getMethod(i); if (matches(start, method, statics)) { methods.add(getSignature(type, method)); } } } if (statics) { return; } // Recursively scan super types final IType superType = iclass.getSuperType(); if (superType != null) { this.findCompletions(superType.getConcreteType(type), fields, properties, methods, start, false, dejaVu); } for (int i = 0, count = iclass.interfaceCount(); i < count; i++) { final IType superInterface = iclass.getInterface(i); if (superInterface != null) { this.findCompletions(superInterface.getConcreteType(type), fields, properties, methods, start, false, dejaVu); } } } private static boolean matches(String start, IMember member, boolean statics) { if (!member.getName().startWith(start)) { return false; } int modifiers = member.getModifiers().toFlags(); return (modifiers & Modifiers.PUBLIC) != 0 && statics == ((modifiers & Modifiers.STATIC) != 0); } private static String getSignature(IType type, IMember member) { StringBuilder sb = new StringBuilder(); sb.append(member.getName()); sb.append(" : "); member.getType().getConcreteType(type).toString("", sb); return sb.toString(); } private static String getSignature(IType type, IMethod method) { StringBuilder sb = new StringBuilder(); sb.append(method.getName()); sb.append('('); int paramCount = method.parameterCount(); if (paramCount > 0) { method.getParameter(0).getType().getConcreteType(type).toString("", sb); for (int i = 1; i < paramCount; i++) { sb.append(", "); method.getParameter(i).getType().getConcreteType(type).toString("", sb); } } sb.append(") : "); method.getType().getConcreteType(type).toString("", sb); return sb.toString(); } }
package org.pentaho.di.core.database; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.row.ValueMetaInterface; /** * Contains HP Neoview specific information through static final members * * @author Jens * @since 2008-04-18 */ public class NeoviewDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface { /** * Construct a new database connections. Note that not all these parameters are not allways mandatory. * * @param name The database name * @param access The type of database access * @param host The hostname or IP address * @param db The database name * @param port The port on which the database listens. * @param user The username * @param pass The password */ public NeoviewDatabaseMeta(String name, String access, String host, String db, String port, String user, String pass) { super(name, access, host, db, port, user, pass); } public NeoviewDatabaseMeta() { } public String getDatabaseTypeDesc() { return "NEOVIEW"; } public String getDatabaseTypeDescLong() { return "Neoview"; } /** * @return Returns the databaseType. */ public int getDatabaseType() { return DatabaseMeta.TYPE_DATABASE_NEOVIEW; } public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI}; } public int getDefaultDatabasePort() { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) return 18650; return -1; } /** * @return Whether or not the database can use auto increment type of fields (pk) */ public boolean supportsAutoInc() { return false; // Neoview can support this but can not read it back } /** * @see org.pentaho.di.core.database.DatabaseInterface#getLimitClause(int) */ public String getLimitClause(int nrRows) { // it is SELECT [FIRST N] * FROM xyz but this is not supported by the Database class return ""; } /** * Returns the minimal SQL to launch in order to determine the layout of the resultset for a given database table * @param tableName The name of the table to determine the layout for * @return The SQL to launch. */ public String getSQLQueryFields(String tableName) { return "SELECT [FIRST 1] * FROM "+tableName; } public String getSQLTableExists(String tablename) { return getSQLQueryFields(tablename); } public String getSQLColumnExists(String columnname, String tablename) { return getSQLQueryColumnFields(columnname, tablename); } public String getSQLQueryColumnFields(String columnname, String tableName) { return "SELECT [FIRST 1] " + columnname + " FROM "+tableName; } public boolean needsToLockAllTables() { return false; } public String getDriverClass() { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC) { return "sun.jdbc.odbc.JdbcOdbcDriver"; } else { return "com.hp.t4jdbc.HPT4Driver"; } } public String getURL(String hostname, String port, String databaseName) throws KettleDatabaseException { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC) { return "jdbc:odbc:"+databaseName; } else { String appendix=""; if (!Const.isEmpty(databaseName)) { if (databaseName.contains("=")) { // some properties here like serverDataSource, catalog, schema etc. already given appendix=":"+databaseName; } else { // assume to set the schema appendix=":schema="+databaseName; } } return "jdbc:hpt4jdbc://"+hostname+":"+port+"/"+appendix; } } /** * Neoview supports options in the URL. */ public boolean supportsOptionsInURL() { return true; } /** * @return true if we need to supply the schema-name to getTables in order to get a correct list of items. */ public boolean useSchemaNameForTableList() { return true; } /** * @return true if the database supports synonyms */ public boolean supportsSynonyms() { return true; } /** * Generates the SQL statement to add a column to the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" ADD ( "+getFieldDefinition(v, tk, pk, use_autoinc, true, false)+" ) "; } /** * Generates the SQL statement to drop a column from the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to drop a column from the specified table */ public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" DROP ( "+v.getName()+" ) "+Const.CR; } /** * Generates the SQL statement to modify a column in the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" MODIFY "+getFieldDefinition(v, tk, pk, use_autoinc, true, false); } public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr) { String retval=""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if (add_fieldname) retval+=fieldname+" "; int type = v.getType(); switch(type) { case ValueMetaInterface.TYPE_DATE : retval+="TIMESTAMP"; break; case ValueMetaInterface.TYPE_BOOLEAN : retval+="CHAR(1)"; break; case ValueMetaInterface.TYPE_NUMBER : case ValueMetaInterface.TYPE_INTEGER : case ValueMetaInterface.TYPE_BIGNUMBER : if (fieldname.equalsIgnoreCase(tk) || // Technical key fieldname.equalsIgnoreCase(pk) // Primary key ) { retval+="INTEGER NOT NULL PRIMARY KEY"; } else { // Integer values... if (precision==0) { if (length>9) { if (length<=18) { // can hold max. 18 retval+="NUMERIC("+length+")"; } else { retval+="FLOAT"; } } else { retval+="INTEGER"; } } // Floating point values... else { // A double-precision floating-point number is accurate to approximately 15 decimal places. //+/- 2.2250738585072014e-308 through +/-1.7976931348623157e+308; stored in 8 byte // NUMERIC values are stored in less bytes, so we try to use them instead of a FLOAT: // 1 to 4 digits in 2 bytes, 5 to 9 digits in 4 bytes, 10 to 18 digits in 8 bytes if (length<=18) { retval+="NUMERIC("+length; if (precision>0) retval+=", "+precision; retval+=")"; } else { retval+="FLOAT"; } } } break; case ValueMetaInterface.TYPE_STRING: // for LOB support see Neoview_JDBC_T4_Driver_Prog_Ref_2.2.pdf if (length>0) { if (length<=4028) retval+="VARCHAR("+length+")"; else if (length<=4036) retval+="CHAR("+length+")"; //squeezing 8 bytes ;-) else retval+="CLOB"; // before we go to CLOB } else { retval+="CHAR(1)"; } break; case ValueMetaInterface.TYPE_BINARY: retval+="BLOB"; break; default: retval+=" UNKNOWN"; break; } if (add_cr) retval+=Const.CR; return retval; } /* (non-Javadoc) * @see com.ibridge.kettle.core.database.DatabaseInterface#getReservedWords() */ public String[] getReservedWords() { return new String[] { "ACTION", "FOR", "PROTOTYPE", "ADD", "FOREIGN", "PUBLIC", "ADMIN", "FOUND", "READ", "AFTER", "FRACTION", "READS", "AGGREGATE", "FREE", "REAL", "ALIAS", "FROM", "RECURSIVE", "ALL", "FULL", "REF", "ALLOCATE", "FUNCTION", "REFERENCES", "ALTER", "GENERAL", "REFERENCING", "AND", "GET", "RELATIVE", "ANY", "GLOBAL", "REPLACE", "ARE", "GO", "RESIGNAL", "ARRAY", "GOTO", "RESTRICT", "AS", "GRANT", "RESULT", "ASC", "GROUP", "RETURN", "ASSERTION", "GROUPING", "RETURNS", "ASYNC", "HAVING", "REVOKE", "AT", "HOST", "RIGHT", "AUTHORIZATION", "HOUR", "ROLE", "AVG", "IDENTITY", "ROLLBACK", "BEFORE", "IF", "ROLLUP", "BEGIN", "IGNORE", "ROUTINE", "BETWEEN", "IMMEDIATE", "ROW", "BINARY", "IN", "ROWS", "BIT", "INDICATOR", "SAVEPOINT", "BIT_LENGTH", "INITIALLY", "SCHEMA", "BLOB", "INNER", "SCOPE", "BOOLEAN", "INOUT", "SCROLL", "BOTH", "INPUT", "SEARCH", "BREADTH", "INSENSITIVE", "SECOND", "BY", "INSERT", "SECTION", "CALL", "INT", "SELECT", "CASE", "INTEGER", "SENSITIVE", "CASCADE", "INTERSECT", "SESSION", "CASCADED", "INTERVAL", "SESSION_USER", "CAST", "INTO", "SET", "CATALOG", "IS", "SETS", "CHAR", "ISOLATION", "SIGNAL", "CHAR_LENGTH", "ITERATE", "SIMILAR", "CHARACTER", "JOIN", "SIZE", "CHARACTER_LENGTH", "KEY", "SMALLINT", "CHECK", "LANGUAGE", "SOME", "CLASS", "LARGE", "CLOB", "LAST", "SPECIFIC", "CLOSE", "LATERAL", "SPECIFICTYPE", "COALESCE", "LEADING", "SQL", "COLLATE", "LEAVE", "SQL_CHAR", "COLLATION", "LEFT", "SQL_DATE", "COLUMN", "LESS", "SQL_DECIMAL", "COMMIT", "LEVEL", "SQL_DOUBLE", "COMPLETION", "LIKE", "SQL_FLOAT", "CONNECT", "LIMIT", "SQL_INT", "CONNECTION", "LOCAL", "SQL_INTEGER", "CONSTRAINT", "LOCALTIME", "SQL_REAL", "CONSTRAINTS", "LOCALTIMESTAMP", "SQL_SMALLINT", "CONSTRUCTOR", "LOCATOR", "SQL_TIME", "CONTINUE", "LOOP", "SQL_TIMESTAMP", "CONVERT", "LOWER", "SQL_VARCHAR", "CORRESPONDING", "MAP", "SQLCODE", "COUNT", "MATCH", "SQLERROR", "CREATE", "MAX", "SQLEXCEPTION", "CROSS", "MIN", "SQLSTATE", "CUBE", "MINUTE", "SQLWARNING", "CURRENT", "MODIFIES", "STRUCTURE", "CURRENT_DATE", "MODIFY", "SUBSTRING", "CURRENT_PATH", "MODULE", "SUM", "CURRENT_ROLE", "MONTH", "SYSTEM_USER", "CURRENT_TIME", "NAMES", "TABLE", "CURRENT_TIMESTAMP", "NATIONAL", "TEMPORARY", "CURRENT_USER", "NATURAL", "TERMINATE", "CURSOR", "NCHAR", "TEST", "CYCLE", "NCLOB", "THAN", "DATE", "NEW", "THEN", "DATETIME", "NEXT", "THERE", "DAY", "NO", "TIME", "DEALLOCATE", "NONE", "TIMESTAMP", "DEC", "NOT", "TIMEZONE_HOUR", "DECIMAL", "NULL", "TIMEZONE_MINUTE", "DECLARE", "NULLIF", "TO", "DEFAULT", "NUMERIC", "TRAILING", "DEFERRABLE", "OBJECT", "TRANSACTION", "DEFERRED", "OCTET_LENGTH", "TRANSLATE", "DELETE", "OF", "TRANSLATION", "DEPTH", "OFF", "TRANSPOSE", "DEREF", "OID", "TREAT", "DESC", "OLD", "TRIGGER", "DESCRIBE", "ON", "TRIM", "DESCRIPTOR", "ONLY", "TRUE", "DESTROY", "OPEN", "UNDER", "DESTRUCTOR", "OPERATORS", "UNION", "DETERMINISTIC", "OPTION", "UNIQUE", "DIAGNOSTICS", "OR", "UNKNOWN", "DISTINCT", "ORDER", "UNNEST", "DICTIONARY", "ORDINALITY", "UPDATE", "DISCONNECT", "OTHERS", "UPPER", "DOMAIN", "OUT", "UPSHIFT", "DOUBLE", "OUTER", "USAGE", "DROP", "OUTPUT", "USER", "DYNAMIC", "OVERLAPS", "USING", "EACH", "PAD", "VALUE", "ELSE", "PARAMETER", "VALUES", "ELSEIF", "PARAMETERS", "VARCHAR", "END", "PARTIAL", "VARIABLE", "END-EXEC", "PENDANT", "VARYING", "EQUALS", "POSITION", "VIEW", "ESCAPE", "POSTFIX", "VIRTUAL", "EXCEPT", "PRECISION", "VISIBLE", "EXCEPTION", "PREFIX", "WAIT", "EXEC", "PREORDER", "WHEN", "EXECUTE", "PREPARE", "WHENEVER", "EXISTS", "PRESERVE", "WHERE", "EXTERNAL", "PRIMARY", "WHILE", "EXTRACT", "PRIOR", "WITH", "FALSE", "PRIVATE", "WITHOUT", "FETCH", "PRIVILEGES", "WORK", "FIRST", "PROCEDURE", "WRITE", "FLOAT", "PROTECTED", "YEAR", "ZONE" }; } public String getSQLLockTables(String tableNames[]) { StringBuffer sql=new StringBuffer(128); for (int i=0;i<tableNames.length;i++) { sql.append("LOCK TABLE ").append(tableNames[i]).append(" IN EXCLUSIVE MODE;").append(Const.CR); } return sql.toString(); } public String getSQLUnlockTables(String tableNames[]) { return null; // commit handles the unlocking! } /** * @return extra help text on the supported options on the selected database platform. */ public String getExtraOptionsHelpText() { return "http://docs.hp.com/en/busintellsol.html"; } public String[] getUsedLibraries() { return new String[] { "hpt4jdbc.jar" }; } public boolean supportsBitmapIndex() { return false; } public int getMaxVARCHARLength() { return 4028; } public boolean supportsRepository() { // not tested, yet: due to constraints on BLOB fields return false; } public String getTruncateTableStatement(String tableName) { return "DELETE FROM "+tableName; } }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "7.0.0-SNAPSHOT"; static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n" + "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n" + "|____| \\___/ |_| |___| \\___| |___| /_/ "; static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n" + "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n" + "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n" + "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package org.pentaho.di.ui.core.dialog; import java.util.Locale; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.ColorDialog; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FontDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.Props; import org.pentaho.di.core.gui.GUIOption; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.i18n.GlobalMessages; import org.pentaho.di.i18n.LanguageChoice; import org.pentaho.di.ui.core.ConstUI; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.database.dialog.DatabaseDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.trans.step.BaseStepDialog; /** * Allows you to set the configurable options for the Kettle environment * * @author Matt * @since 15-12-2003 */ public class EnterOptionsDialog extends Dialog { private static Class<?> PKG = DatabaseDialog.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private Display display; private CTabFolder wTabFolder; private FormData fdTabFolder; private CTabItem wLookTab, wGeneralTab; private ScrolledComposite sLookComp, sGeneralComp; private Composite wLookComp, wGeneralComp; private FormData fdLookComp, fdGeneralComp; private FontData fixedFontData, graphFontData, noteFontData; private Font fixedFont, graphFont, noteFont; private RGB backgroundRGB, graphColorRGB, tabColorRGB; private Color background, graphColor, tabColor; private Canvas wFFont; private Button wbFFont, wdFFont; private Canvas wGFont; private Button wbGFont, wdGFont; private Canvas wNFont; private Button wbNFont, wdNFont; private Canvas wBGColor; private Button wbBGColor, wdBGcolor; private Canvas wGrColor; private Button wbGrColor, wdGrColor; private Canvas wTabColor; private Button wbTabColor, wdTabColor; private Text wIconsize; private Text wLineWidth; private Text wShadowSize; private Text wMaxUndo; private Text wDefaultPreview; private Text wMaxNrLogLines; private Text wMaxLogLineTimeout; private Text wMaxNrHistLines; private Text wMiddlePct; private Text wGridSize; private Button wAntiAlias; private Button wOriginalLook; private Button wBranding; private Button wShowTips; private Button wShowWelcome; private Button wUseCache; private Button wOpenLast; private Button wAutoSave; private Button wOnlyActiveFile; private Button wDBConnXML; private Button wAskReplaceDB; private Button wReplaceDB; private Button wSaveConf; private Button wAutoSplit; private Button wCopyDistrib; private Button wShowRep; private Button wExitWarning; private Button wClearCustom; private Combo wDefaultLocale; private Combo wFailoverLocale; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private SelectionAdapter lsDef; private PropsUI props; private int middle; private int margin; private Button tooltipBtn; private Button helptipBtn; private Button autoCollapseBtn; /** * @deprecated Use CT without <i>props</i> parameter instead */ public EnterOptionsDialog(Shell parent, PropsUI props) { super(parent, SWT.NONE); this.props = props; } public EnterOptionsDialog(Shell parent) { super(parent, SWT.NONE); props = PropsUI.getInstance(); } public Props open() { Shell parent = getParent(); display = parent.getDisplay(); getData(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE); props.setLook(shell); shell.setImage(GUIResource.getInstance().getImageLogoSmall()); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.Title")); middle = props.getMiddlePct(); margin = Const.MARGIN; wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); wTabFolder.setSimple(false); addGeneralTab(); addLookTab(); // Some buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, null); fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(0, 0); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.bottom = new FormAttachment(wOK, -margin); wTabFolder.setLayoutData(fdTabFolder); // / END OF TABS // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wOK.addListener(SWT.Selection, lsOK); wCancel.addListener(SWT.Selection, lsCancel); lsDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wIconsize.addSelectionListener(lsDef); wLineWidth.addSelectionListener(lsDef); wShadowSize.addSelectionListener(lsDef); wMaxUndo.addSelectionListener(lsDef); wMiddlePct.addSelectionListener(lsDef); wDefaultPreview.addSelectionListener(lsDef); wMaxNrLogLines.addSelectionListener(lsDef); wMaxLogLineTimeout.addSelectionListener(lsDef); wMaxNrHistLines.addSelectionListener(lsDef); wGridSize.addSelectionListener(lsDef); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } }); wTabFolder.setSelection(0); BaseStepDialog.setSize(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return props; } private void addLookTab() { int h = 40; // START OF LOOK TAB/// wLookTab = new CTabItem(wTabFolder, SWT.NONE); wLookTab.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.LookAndFeel.Label")); sLookComp = new ScrolledComposite(wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL); sLookComp.setLayout(new FillLayout()); wLookComp = new Composite(sLookComp, SWT.NONE); props.setLook(wLookComp); FormLayout lookLayout = new FormLayout(); lookLayout.marginWidth = 3; lookLayout.marginHeight = 3; wLookComp.setLayout(lookLayout); // Fixed font int nr = 0; Label wlFFont = new Label(wLookComp, SWT.RIGHT); wlFFont.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.FixedWidthFont.Label")); props.setLook(wlFFont); FormData fdlFFont = new FormData(); fdlFFont.left = new FormAttachment(0, 0); fdlFFont.right = new FormAttachment(middle, -margin); fdlFFont.top = new FormAttachment(0, nr * h + margin + 10); wlFFont.setLayoutData(fdlFFont); wdFFont = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wdFFont); FormData fddFFont = layoutResetOptionButton(wdFFont); fddFFont.right = new FormAttachment(100, 0); fddFFont.top = new FormAttachment(0, nr * h + margin); fddFFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wdFFont.setLayoutData(fddFFont); wdFFont.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { fixedFontData = new FontData(ConstUI.FONT_FIXED_NAME, ConstUI.FONT_FIXED_SIZE, ConstUI.FONT_FIXED_TYPE); fixedFont.dispose(); fixedFont = new Font(display, fixedFontData); wFFont.redraw(); } }); wbFFont = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wbFFont); FormData fdbFFont = layoutEditOptionButton(wbFFont); fdbFFont.right = new FormAttachment(wdFFont, -margin); fdbFFont.top = new FormAttachment(0, nr * h + margin); fdbFFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wbFFont.setLayoutData(fdbFFont); wbFFont.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { FontDialog fd = new FontDialog(shell); fd.setFontList(new FontData[] { fixedFontData }); FontData newfd = fd.open(); if (newfd != null) { fixedFontData = newfd; fixedFont.dispose(); fixedFont = new Font(display, fixedFontData); wFFont.redraw(); } } }); wFFont = new Canvas(wLookComp, SWT.BORDER); props.setLook(wFFont); FormData fdFFont = new FormData(); fdFFont.left = new FormAttachment(middle, 0); fdFFont.right = new FormAttachment(wbFFont, -margin); fdFFont.top = new FormAttachment(0, margin); fdFFont.bottom = new FormAttachment(0, h); wFFont.setLayoutData(fdFFont); wFFont.addPaintListener(new PaintListener() { public void paintControl(PaintEvent pe) { pe.gc.setFont(fixedFont); Rectangle max = wFFont.getBounds(); String name = fixedFontData.getName() + " - " + fixedFontData.getHeight(); //$NON-NLS-1$ Point size = pe.gc.textExtent(name); pe.gc.drawText(name, (max.width - size.x) / 2, (max.height - size.y) / 2, true); } }); // Graph font nr++; Label wlGFont = new Label(wLookComp, SWT.RIGHT); wlGFont.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.GraphFont.Label")); props.setLook(wlGFont); FormData fdlGFont = new FormData(); fdlGFont.left = new FormAttachment(0, 0); fdlGFont.right = new FormAttachment(middle, -margin); fdlGFont.top = new FormAttachment(0, nr * h + margin + 10); wlGFont.setLayoutData(fdlGFont); wdGFont = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wdGFont); FormData fddGFont = layoutResetOptionButton(wdGFont); fddGFont.right = new FormAttachment(100, 0); fddGFont.top = new FormAttachment(0, nr * h + margin); fddGFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wdGFont.setLayoutData(fddGFont); wdGFont.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { graphFont.dispose(); graphFontData = props.getDefaultFontData(); graphFont = new Font(display, graphFontData); wGFont.redraw(); } }); wbGFont = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wbGFont); FormData fdbGFont = layoutEditOptionButton(wbGFont); fdbGFont.right = new FormAttachment(wdGFont, -margin); fdbGFont.top = new FormAttachment(0, nr * h + margin); fdbGFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wbGFont.setLayoutData(fdbGFont); wbGFont.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { FontDialog fd = new FontDialog(shell); fd.setFontList(new FontData[] { graphFontData }); FontData newfd = fd.open(); if (newfd != null) { graphFontData = newfd; graphFont.dispose(); graphFont = new Font(display, graphFontData); wGFont.redraw(); } } }); wGFont = new Canvas(wLookComp, SWT.BORDER); props.setLook(wGFont); FormData fdGFont = new FormData(); fdGFont.left = new FormAttachment(middle, 0); fdGFont.right = new FormAttachment(wbGFont, -margin); fdGFont.top = new FormAttachment(0, nr * h + margin); fdGFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wGFont.setLayoutData(fdGFont); wGFont.addPaintListener(new PaintListener() { public void paintControl(PaintEvent pe) { pe.gc.setFont(graphFont); Rectangle max = wGFont.getBounds(); String name = graphFontData.getName() + " - " + graphFontData.getHeight(); //$NON-NLS-1$ Point size = pe.gc.textExtent(name); pe.gc.drawText(name, (max.width - size.x) / 2, (max.height - size.y) / 2, true); } }); // Note font nr++; Label wlNFont = new Label(wLookComp, SWT.RIGHT); wlNFont.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.NoteFont.Label")); props.setLook(wlNFont); FormData fdlNFont = new FormData(); fdlNFont.left = new FormAttachment(0, 0); fdlNFont.right = new FormAttachment(middle, -margin); fdlNFont.top = new FormAttachment(0, nr * h + margin + 10); wlNFont.setLayoutData(fdlNFont); wdNFont = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wdNFont); FormData fddNFont = layoutResetOptionButton(wdNFont); fddNFont.right = new FormAttachment(100, 0); fddNFont.top = new FormAttachment(0, nr * h + margin); fddNFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wdNFont.setLayoutData(fddNFont); wdNFont.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { noteFontData = props.getDefaultFontData(); noteFont.dispose(); noteFont = new Font(display, noteFontData); wNFont.redraw(); } }); wbNFont = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wbNFont); FormData fdbNFont = layoutEditOptionButton(wbNFont); fdbNFont.right = new FormAttachment(wdNFont, -margin); fdbNFont.top = new FormAttachment(0, nr * h + margin); fdbNFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wbNFont.setLayoutData(fdbNFont); wbNFont.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { FontDialog fd = new FontDialog(shell); fd.setFontList(new FontData[] { noteFontData }); FontData newfd = fd.open(); if (newfd != null) { noteFontData = newfd; noteFont.dispose(); noteFont = new Font(display, noteFontData); wNFont.redraw(); } } }); wNFont = new Canvas(wLookComp, SWT.BORDER); props.setLook(wNFont); FormData fdNFont = new FormData(); fdNFont.left = new FormAttachment(middle, 0); fdNFont.right = new FormAttachment(wbNFont, -margin); fdNFont.top = new FormAttachment(0, nr * h + margin); fdNFont.bottom = new FormAttachment(0, (nr + 1) * h + margin); wNFont.setLayoutData(fdNFont); wNFont.addPaintListener(new PaintListener() { public void paintControl(PaintEvent pe) { pe.gc.setFont(noteFont); Rectangle max = wNFont.getBounds(); String name = noteFontData.getName() + " - " + noteFontData.getHeight(); //$NON-NLS-1$ Point size = pe.gc.textExtent(name); pe.gc.drawText(name, (max.width - size.x) / 2, (max.height - size.y) / 2, true); } }); // Background color nr++; Label wlBGColor = new Label(wLookComp, SWT.RIGHT); wlBGColor.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.BackgroundColor.Label")); props.setLook(wlBGColor); FormData fdlBGColor = new FormData(); fdlBGColor.left = new FormAttachment(0, 0); fdlBGColor.right = new FormAttachment(middle, -margin); fdlBGColor.top = new FormAttachment(0, nr * h + margin + 10); wlBGColor.setLayoutData(fdlBGColor); wdBGcolor = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wdBGcolor); FormData fddBGColor = layoutResetOptionButton(wdBGcolor); fddBGColor.right = new FormAttachment(100, 0); // to the right of the // dialog fddBGColor.top = new FormAttachment(0, nr * h + margin); fddBGColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wdBGcolor.setLayoutData(fddBGColor); wdBGcolor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { background.dispose(); backgroundRGB = new RGB(ConstUI.COLOR_BACKGROUND_RED, ConstUI.COLOR_BACKGROUND_GREEN, ConstUI.COLOR_BACKGROUND_BLUE); background = new Color(display, backgroundRGB); wBGColor.setBackground(background); wBGColor.redraw(); } }); wbBGColor = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wbBGColor); FormData fdbBGColor = layoutEditOptionButton(wbBGColor); fdbBGColor.right = new FormAttachment(wdBGcolor, -margin); // to the // left of // the // "default" // button fdbBGColor.top = new FormAttachment(0, nr * h + margin); fdbBGColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wbBGColor.setLayoutData(fdbBGColor); wbBGColor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { ColorDialog cd = new ColorDialog(shell); cd.setRGB(props.getBackgroundRGB()); RGB newbg = cd.open(); if (newbg != null) { backgroundRGB = newbg; background.dispose(); background = new Color(display, backgroundRGB); wBGColor.setBackground(background); wBGColor.redraw(); } } }); wBGColor = new Canvas(wLookComp, SWT.BORDER); props.setLook(wBGColor); wBGColor.setBackground(background); FormData fdBGColor = new FormData(); fdBGColor.left = new FormAttachment(middle, 0); fdBGColor.right = new FormAttachment(wbBGColor, -margin); fdBGColor.top = new FormAttachment(0, nr * h + margin); fdBGColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wBGColor.setLayoutData(fdBGColor); // Graph background color nr++; Label wlGrColor = new Label(wLookComp, SWT.RIGHT); wlGrColor.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.BackgroundColorGraph.Label")); props.setLook(wlGrColor); FormData fdlGrColor = new FormData(); fdlGrColor.left = new FormAttachment(0, 0); fdlGrColor.right = new FormAttachment(middle, -margin); fdlGrColor.top = new FormAttachment(0, nr * h + margin + 10); wlGrColor.setLayoutData(fdlGrColor); wdGrColor = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wdGrColor); FormData fddGrColor = layoutResetOptionButton(wdGrColor); fddGrColor.right = new FormAttachment(100, 0); fddGrColor.top = new FormAttachment(0, nr * h + margin); fddGrColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wdGrColor.setLayoutData(fddGrColor); wdGrColor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { graphColor.dispose(); graphColorRGB = new RGB(ConstUI.COLOR_GRAPH_RED, ConstUI.COLOR_GRAPH_GREEN, ConstUI.COLOR_GRAPH_BLUE); graphColor = new Color(display, graphColorRGB); wGrColor.setBackground(graphColor); wGrColor.redraw(); } }); wbGrColor = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wbGrColor); FormData fdbGrColor = layoutEditOptionButton(wbGrColor); fdbGrColor.right = new FormAttachment(wdGrColor, -margin); fdbGrColor.top = new FormAttachment(0, nr * h + margin); fdbGrColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wbGrColor.setLayoutData(fdbGrColor); wbGrColor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { ColorDialog cd = new ColorDialog(shell); cd.setRGB(props.getGraphColorRGB()); RGB newbg = cd.open(); if (newbg != null) { graphColorRGB = newbg; graphColor.dispose(); graphColor = new Color(display, graphColorRGB); wGrColor.setBackground(graphColor); wGrColor.redraw(); } } }); wGrColor = new Canvas(wLookComp, SWT.BORDER); props.setLook(wGrColor); wGrColor.setBackground(graphColor); FormData fdGrColor = new FormData(); fdGrColor.left = new FormAttachment(middle, 0); fdGrColor.right = new FormAttachment(wbGrColor, -margin); fdGrColor.top = new FormAttachment(0, nr * h + margin); fdGrColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wGrColor.setLayoutData(fdGrColor); // Tab selected color nr++; Label wlTabColor = new Label(wLookComp, SWT.RIGHT); wlTabColor.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.TabColor.Label")); props.setLook(wlTabColor); FormData fdlTabColor = new FormData(); fdlTabColor.left = new FormAttachment(0, 0); fdlTabColor.right = new FormAttachment(middle, -margin); fdlTabColor.top = new FormAttachment(0, nr * h + margin + 10); wlTabColor.setLayoutData(fdlTabColor); wdTabColor = new Button(wLookComp, SWT.PUSH | SWT.BORDER | SWT.CENTER); props.setLook(wdTabColor); FormData fddTabColor = layoutResetOptionButton(wdTabColor); fddTabColor.right = new FormAttachment(100, 0); fddTabColor.top = new FormAttachment(0, nr * h + margin); fddTabColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wdTabColor.setLayoutData(fddTabColor); wdTabColor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { tabColor.dispose(); tabColorRGB = new RGB(ConstUI.COLOR_TAB_RED, ConstUI.COLOR_TAB_GREEN, ConstUI.COLOR_TAB_BLUE); tabColor = new Color(display, tabColorRGB); wTabColor.setBackground(tabColor); wTabColor.redraw(); } }); wbTabColor = new Button(wLookComp, SWT.PUSH | SWT.BORDER); props.setLook(wbTabColor); FormData fdbTabColor = layoutEditOptionButton(wbTabColor); fdbTabColor.right = new FormAttachment(wdTabColor, -margin); fdbTabColor.top = new FormAttachment(0, nr * h + margin); fdbTabColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wbTabColor.setLayoutData(fdbTabColor); wbTabColor.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { ColorDialog cd = new ColorDialog(shell); cd.setRGB(props.getTabColorRGB()); RGB newbg = cd.open(); if (newbg != null) { tabColorRGB = newbg; tabColor.dispose(); tabColor = new Color(display, tabColorRGB); wTabColor.setBackground(tabColor); wTabColor.redraw(); } } }); wTabColor = new Canvas(wLookComp, SWT.BORDER); props.setLook(wTabColor); wTabColor.setBackground(tabColor); FormData fdTabColor = new FormData(); fdTabColor.left = new FormAttachment(middle, 0); fdTabColor.right = new FormAttachment(wbTabColor, -margin); fdTabColor.top = new FormAttachment(0, nr * h + margin); fdTabColor.bottom = new FormAttachment(0, (nr + 1) * h + margin); wTabColor.setLayoutData(fdTabColor); // Iconsize line Label wlIconsize = new Label(wLookComp, SWT.RIGHT); wlIconsize.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.IconSize.Label")); props.setLook(wlIconsize); FormData fdlIconsize = new FormData(); fdlIconsize.left = new FormAttachment(0, 0); fdlIconsize.right = new FormAttachment(middle, -margin); fdlIconsize.top = new FormAttachment(wTabColor, margin); wlIconsize.setLayoutData(fdlIconsize); wIconsize = new Text(wLookComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wIconsize.setText(Integer.toString(props.getIconSize())); props.setLook(wIconsize); FormData fdIconsize = new FormData(); fdIconsize.left = new FormAttachment(middle, 0); fdIconsize.right = new FormAttachment(100, -margin); fdIconsize.top = new FormAttachment(wTabColor, margin); wIconsize.setLayoutData(fdIconsize); // LineWidth line Label wlLineWidth = new Label(wLookComp, SWT.RIGHT); wlLineWidth.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.LineWidth.Label")); props.setLook(wlLineWidth); FormData fdlLineWidth = new FormData(); fdlLineWidth.left = new FormAttachment(0, 0); fdlLineWidth.right = new FormAttachment(middle, -margin); fdlLineWidth.top = new FormAttachment(wIconsize, margin); wlLineWidth.setLayoutData(fdlLineWidth); wLineWidth = new Text(wLookComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wLineWidth.setText(Integer.toString(props.getLineWidth())); props.setLook(wLineWidth); FormData fdLineWidth = new FormData(); fdLineWidth.left = new FormAttachment(middle, 0); fdLineWidth.right = new FormAttachment(100, -margin); fdLineWidth.top = new FormAttachment(wIconsize, margin); wLineWidth.setLayoutData(fdLineWidth); // ShadowSize line Label wlShadowSize = new Label(wLookComp, SWT.RIGHT); wlShadowSize.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ShadowSize.Label")); props.setLook(wlShadowSize); FormData fdlShadowSize = new FormData(); fdlShadowSize.left = new FormAttachment(0, 0); fdlShadowSize.right = new FormAttachment(middle, -margin); fdlShadowSize.top = new FormAttachment(wLineWidth, margin); wlShadowSize.setLayoutData(fdlShadowSize); wShadowSize = new Text(wLookComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wShadowSize.setText(Integer.toString(props.getShadowSize())); props.setLook(wShadowSize); FormData fdShadowSize = new FormData(); fdShadowSize.left = new FormAttachment(middle, 0); fdShadowSize.right = new FormAttachment(100, -margin); fdShadowSize.top = new FormAttachment(wLineWidth, margin); wShadowSize.setLayoutData(fdShadowSize); // MiddlePct line Label wlMiddlePct = new Label(wLookComp, SWT.RIGHT); wlMiddlePct.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.DialogMiddlePercentage.Label")); props.setLook(wlMiddlePct); FormData fdlMiddlePct = new FormData(); fdlMiddlePct.left = new FormAttachment(0, 0); fdlMiddlePct.right = new FormAttachment(middle, -margin); fdlMiddlePct.top = new FormAttachment(wShadowSize, margin); wlMiddlePct.setLayoutData(fdlMiddlePct); wMiddlePct = new Text(wLookComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wMiddlePct.setText(Integer.toString(props.getMiddlePct())); props.setLook(wMiddlePct); FormData fdMiddlePct = new FormData(); fdMiddlePct.left = new FormAttachment(middle, 0); fdMiddlePct.right = new FormAttachment(100, -margin); fdMiddlePct.top = new FormAttachment(wShadowSize, margin); wMiddlePct.setLayoutData(fdMiddlePct); // GridSize line Label wlGridSize = new Label(wLookComp, SWT.RIGHT); wlGridSize.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.GridSize.Label")); wlGridSize.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.GridSize.ToolTip")); props.setLook(wlGridSize); FormData fdlGridSize = new FormData(); fdlGridSize.left = new FormAttachment(0, 0); fdlGridSize.right = new FormAttachment(middle, -margin); fdlGridSize.top = new FormAttachment(wMiddlePct, margin); wlGridSize.setLayoutData(fdlGridSize); wGridSize = new Text(wLookComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wGridSize.setText(Integer.toString(props.getCanvasGridSize())); wGridSize.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.GridSize.ToolTip")); props.setLook(wGridSize); FormData fdGridSize = new FormData(); fdGridSize.left = new FormAttachment(middle, 0); fdGridSize.right = new FormAttachment(100, -margin); fdGridSize.top = new FormAttachment(wMiddlePct, margin); wGridSize.setLayoutData(fdGridSize); // Enable anti-aliasing Label wlAntiAlias = new Label(wLookComp, SWT.RIGHT); wlAntiAlias.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.CanvasAntiAliasing.Label")); props.setLook(wlAntiAlias); FormData fdlAntiAlias = new FormData(); fdlAntiAlias.left = new FormAttachment(0, 0); fdlAntiAlias.top = new FormAttachment(wGridSize, margin); fdlAntiAlias.right = new FormAttachment(middle, -margin); wlAntiAlias.setLayoutData(fdlAntiAlias); wAntiAlias = new Button(wLookComp, SWT.CHECK); props.setLook(wAntiAlias); wAntiAlias.setSelection(props.isAntiAliasingEnabled()); FormData fdAntiAlias = new FormData(); fdAntiAlias.left = new FormAttachment(middle, 0); fdAntiAlias.top = new FormAttachment(wGridSize, margin); fdAntiAlias.right = new FormAttachment(100, 0); wAntiAlias.setLayoutData(fdAntiAlias); // Show original look Label wlOriginalLook = new Label(wLookComp, SWT.RIGHT); wlOriginalLook.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.UseOSLook.Label")); props.setLook(wlOriginalLook); FormData fdlOriginalLook = new FormData(); fdlOriginalLook.left = new FormAttachment(0, 0); fdlOriginalLook.top = new FormAttachment(wAntiAlias, margin); fdlOriginalLook.right = new FormAttachment(middle, -margin); wlOriginalLook.setLayoutData(fdlOriginalLook); wOriginalLook = new Button(wLookComp, SWT.CHECK); props.setLook(wOriginalLook); wOriginalLook.setSelection(props.isOSLookShown()); FormData fdOriginalLook = new FormData(); fdOriginalLook.left = new FormAttachment(middle, 0); fdOriginalLook.top = new FormAttachment(wAntiAlias, margin); fdOriginalLook.right = new FormAttachment(100, 0); wOriginalLook.setLayoutData(fdOriginalLook); // Show branding graphics Label wlBranding = new Label(wLookComp, SWT.RIGHT); wlBranding.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.Branding.Label")); props.setLook(wlBranding); FormData fdlBranding = new FormData(); fdlBranding.left = new FormAttachment(0, 0); fdlBranding.top = new FormAttachment(wOriginalLook, margin); fdlBranding.right = new FormAttachment(middle, -margin); wlBranding.setLayoutData(fdlBranding); wBranding = new Button(wLookComp, SWT.CHECK); props.setLook(wBranding); wBranding.setSelection(props.isBrandingActive()); FormData fdBranding = new FormData(); fdBranding.left = new FormAttachment(middle, 0); fdBranding.top = new FormAttachment(wOriginalLook, margin); fdBranding.right = new FormAttachment(100, 0); wBranding.setLayoutData(fdBranding); // DefaultLocale line Label wlDefaultLocale = new Label(wLookComp, SWT.RIGHT); wlDefaultLocale.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.DefaultLocale.Label")); props.setLook(wlDefaultLocale); FormData fdlDefaultLocale = new FormData(); fdlDefaultLocale.left = new FormAttachment(0, 0); fdlDefaultLocale.right = new FormAttachment(middle, -margin); fdlDefaultLocale.top = new FormAttachment(wBranding, margin); wlDefaultLocale.setLayoutData(fdlDefaultLocale); wDefaultLocale = new Combo(wLookComp, SWT.SINGLE | SWT.READ_ONLY | SWT.LEFT | SWT.BORDER); wDefaultLocale.setItems(GlobalMessages.localeDescr); props.setLook(wDefaultLocale); FormData fdDefaultLocale = new FormData(); fdDefaultLocale.left = new FormAttachment(middle, 0); fdDefaultLocale.right = new FormAttachment(100, -margin); fdDefaultLocale.top = new FormAttachment(wBranding, margin); wDefaultLocale.setLayoutData(fdDefaultLocale); // language selections... int idxDefault = Const.indexOfString(LanguageChoice.getInstance().getDefaultLocale().toString(), GlobalMessages.localeCodes); if (idxDefault >= 0) wDefaultLocale.select(idxDefault); // FailoverLocale line Label wlFailoverLocale = new Label(wLookComp, SWT.RIGHT); wlFailoverLocale.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.FailoverLocale.Label")); props.setLook(wlFailoverLocale); FormData fdlFailoverLocale = new FormData(); fdlFailoverLocale.left = new FormAttachment(0, 0); fdlFailoverLocale.right = new FormAttachment(middle, -margin); fdlFailoverLocale.top = new FormAttachment(wDefaultLocale, margin); wlFailoverLocale.setLayoutData(fdlFailoverLocale); wFailoverLocale = new Combo(wLookComp, SWT.SINGLE | SWT.READ_ONLY | SWT.LEFT | SWT.BORDER); wFailoverLocale.setItems(GlobalMessages.localeDescr); props.setLook(wFailoverLocale); FormData fdFailoverLocale = new FormData(); fdFailoverLocale.left = new FormAttachment(middle, 0); fdFailoverLocale.right = new FormAttachment(100, -margin); fdFailoverLocale.top = new FormAttachment(wDefaultLocale, margin); wFailoverLocale.setLayoutData(fdFailoverLocale); int idxFailover = Const.indexOfString(LanguageChoice.getInstance().getFailoverLocale().toString(), GlobalMessages.localeCodes); if (idxFailover >= 0) wFailoverLocale.select(idxFailover); fdLookComp = new FormData(); fdLookComp.left = new FormAttachment(0, 0); fdLookComp.right = new FormAttachment(100, 0); fdLookComp.top = new FormAttachment(0, 0); fdLookComp.bottom = new FormAttachment(100, 100); wLookComp.setLayoutData(fdLookComp); wLookComp.pack(); Rectangle bounds = wLookComp.getBounds(); sLookComp.setContent(wLookComp); sLookComp.setExpandHorizontal(true); sLookComp.setExpandVertical(true); sLookComp.setMinWidth(bounds.width); sLookComp.setMinHeight(bounds.height); wLookTab.setControl(sLookComp); // / END OF LOOK TAB } private void addGeneralTab() { // START OF GENERAL TAB/// wGeneralTab = new CTabItem(wTabFolder, SWT.NONE); wGeneralTab.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.General.Label")); FormLayout generalLayout = new FormLayout(); generalLayout.marginWidth = 3; generalLayout.marginHeight = 3; sGeneralComp = new ScrolledComposite(wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL); sGeneralComp.setLayout(new FillLayout()); wGeneralComp = new Composite(sGeneralComp, SWT.NONE); props.setLook(wGeneralComp); wGeneralComp.setLayout(generalLayout); // MaxUndo line Label wlMaxUndo = new Label(wGeneralComp, SWT.RIGHT); wlMaxUndo.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.MaximumUndo.Label")); props.setLook(wlMaxUndo); FormData fdlMaxUndo = new FormData(); fdlMaxUndo.left = new FormAttachment(0, 0); fdlMaxUndo.right = new FormAttachment(middle, -margin); fdlMaxUndo.top = new FormAttachment(0, 0); wlMaxUndo.setLayoutData(fdlMaxUndo); wMaxUndo = new Text(wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wMaxUndo.setText(Integer.toString(props.getMaxUndo())); props.setLook(wMaxUndo); FormData fdMaxUndo = new FormData(); fdMaxUndo.left = new FormAttachment(middle, 0); fdMaxUndo.right = new FormAttachment(100, -margin); fdMaxUndo.top = new FormAttachment(0, 0); wMaxUndo.setLayoutData(fdMaxUndo); // Default preview size Label wlDefaultPreview = new Label(wGeneralComp, SWT.RIGHT); wlDefaultPreview.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.DefaultPreviewSize.Label")); props.setLook(wlDefaultPreview); FormData fdlDefaultPreview = new FormData(); fdlDefaultPreview.left = new FormAttachment(0, 0); fdlDefaultPreview.right = new FormAttachment(middle, -margin); fdlDefaultPreview.top = new FormAttachment(wMaxUndo, margin); wlDefaultPreview.setLayoutData(fdlDefaultPreview); wDefaultPreview = new Text(wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wDefaultPreview.setText(Integer.toString(props.getDefaultPreviewSize())); props.setLook(wDefaultPreview); FormData fdDefaultPreview = new FormData(); fdDefaultPreview.left = new FormAttachment(middle, 0); fdDefaultPreview.right = new FormAttachment(100, -margin); fdDefaultPreview.top = new FormAttachment(wMaxUndo, margin); wDefaultPreview.setLayoutData(fdDefaultPreview); // Max Nr of log lines Label wlMaxNrLogLines = new Label(wGeneralComp, SWT.RIGHT); wlMaxNrLogLines.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.MaxNrLogLinesSize.Label")); props.setLook(wlMaxNrLogLines); FormData fdlMaxNrLogLines = new FormData(); fdlMaxNrLogLines.left = new FormAttachment(0, 0); fdlMaxNrLogLines.right = new FormAttachment(middle, -margin); fdlMaxNrLogLines.top = new FormAttachment(wDefaultPreview, margin); wlMaxNrLogLines.setLayoutData(fdlMaxNrLogLines); wMaxNrLogLines = new Text(wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wMaxNrLogLines.setText(Integer.toString(props.getMaxNrLinesInLog())); props.setLook(wMaxNrLogLines); FormData fdMaxNrLogLines = new FormData(); fdMaxNrLogLines.left = new FormAttachment(middle, 0); fdMaxNrLogLines.right = new FormAttachment(100, -margin); fdMaxNrLogLines.top = new FormAttachment(wDefaultPreview, margin); wMaxNrLogLines.setLayoutData(fdMaxNrLogLines); // Max log line timeout (minutes) Label wlMaxLogLineTimeout = new Label(wGeneralComp, SWT.RIGHT); wlMaxLogLineTimeout.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.MaxLogLineTimeout.Label")); props.setLook(wlMaxLogLineTimeout); FormData fdlMaxLogLineTimeout = new FormData(); fdlMaxLogLineTimeout.left = new FormAttachment(0, 0); fdlMaxLogLineTimeout.right = new FormAttachment(middle, -margin); fdlMaxLogLineTimeout.top = new FormAttachment(wMaxNrLogLines, margin); wlMaxLogLineTimeout.setLayoutData(fdlMaxLogLineTimeout); wMaxLogLineTimeout = new Text(wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wMaxLogLineTimeout.setText(Integer.toString(props.getMaxLogLineTimeoutMinutes())); props.setLook(wMaxLogLineTimeout); FormData fdMaxLogLineTimeout = new FormData(); fdMaxLogLineTimeout.left = new FormAttachment(middle, 0); fdMaxLogLineTimeout.right = new FormAttachment(100, -margin); fdMaxLogLineTimeout.top = new FormAttachment(wMaxNrLogLines, margin); wMaxLogLineTimeout.setLayoutData(fdMaxLogLineTimeout); // Max Nr of history lines Label wlMaxNrHistLines = new Label(wGeneralComp, SWT.RIGHT); wlMaxNrHistLines.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.MaxNrHistLinesSize.Label")); props.setLook(wlMaxNrHistLines); FormData fdlMaxNrHistLines = new FormData(); fdlMaxNrHistLines.left = new FormAttachment(0, 0); fdlMaxNrHistLines.right = new FormAttachment(middle, -margin); fdlMaxNrHistLines.top = new FormAttachment(wMaxLogLineTimeout, margin); wlMaxNrHistLines.setLayoutData(fdlMaxNrHistLines); wMaxNrHistLines = new Text(wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wMaxNrHistLines.setText(Integer.toString(props.getMaxNrLinesInHistory())); props.setLook(wMaxNrHistLines); FormData fdMaxNrHistLines = new FormData(); fdMaxNrHistLines.left = new FormAttachment(middle, 0); fdMaxNrHistLines.right = new FormAttachment(100, -margin); fdMaxNrHistLines.top = new FormAttachment(wMaxLogLineTimeout, margin); wMaxNrHistLines.setLayoutData(fdMaxNrHistLines); // Show tips on startup? Label wlShowTips = new Label(wGeneralComp, SWT.RIGHT); wlShowTips.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ShowTipsStartup.Label")); props.setLook(wlShowTips); FormData fdlShowTips = new FormData(); fdlShowTips.left = new FormAttachment(0, 0); fdlShowTips.top = new FormAttachment(wMaxNrHistLines, margin); fdlShowTips.right = new FormAttachment(middle, -margin); wlShowTips.setLayoutData(fdlShowTips); wShowTips = new Button(wGeneralComp, SWT.CHECK); props.setLook(wShowTips); wShowTips.setSelection(props.showTips()); FormData fdShowTips = new FormData(); fdShowTips.left = new FormAttachment(middle, 0); fdShowTips.top = new FormAttachment(wMaxNrHistLines, margin); fdShowTips.right = new FormAttachment(100, 0); wShowTips.setLayoutData(fdShowTips); // Show welcome page on startup? Label wlShowWelcome = new Label(wGeneralComp, SWT.RIGHT); wlShowWelcome.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ShowWelcomePage.Label")); props.setLook(wlShowWelcome); FormData fdlShowWelcome = new FormData(); fdlShowWelcome.left = new FormAttachment(0, 0); fdlShowWelcome.top = new FormAttachment(wShowTips, margin); fdlShowWelcome.right = new FormAttachment(middle, -margin); wlShowWelcome.setLayoutData(fdlShowWelcome); wShowWelcome = new Button(wGeneralComp, SWT.CHECK); props.setLook(wShowWelcome); wShowWelcome.setSelection(props.showWelcomePageOnStartup()); FormData fdShowWelcome = new FormData(); fdShowWelcome.left = new FormAttachment(middle, 0); fdShowWelcome.top = new FormAttachment(wShowTips, margin); fdShowWelcome.right = new FormAttachment(100, 0); wShowWelcome.setLayoutData(fdShowWelcome); // Use DB Cache? Label wlUseCache = new Label(wGeneralComp, SWT.RIGHT); wlUseCache.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.UseDatabaseCache.Label")); props.setLook(wlUseCache); FormData fdlUseCache = new FormData(); fdlUseCache.left = new FormAttachment(0, 0); fdlUseCache.top = new FormAttachment(wShowWelcome, margin); fdlUseCache.right = new FormAttachment(middle, -margin); wlUseCache.setLayoutData(fdlUseCache); wUseCache = new Button(wGeneralComp, SWT.CHECK); props.setLook(wUseCache); wUseCache.setSelection(props.useDBCache()); FormData fdUseCache = new FormData(); fdUseCache.left = new FormAttachment(middle, 0); fdUseCache.top = new FormAttachment(wShowWelcome, margin); fdUseCache.right = new FormAttachment(100, 0); wUseCache.setLayoutData(fdUseCache); // Auto load last file at startup? Label wlOpenLast = new Label(wGeneralComp, SWT.RIGHT); wlOpenLast.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.OpenLastFileStartup.Label")); props.setLook(wlOpenLast); FormData fdlOpenLast = new FormData(); fdlOpenLast.left = new FormAttachment(0, 0); fdlOpenLast.top = new FormAttachment(wUseCache, margin); fdlOpenLast.right = new FormAttachment(middle, -margin); wlOpenLast.setLayoutData(fdlOpenLast); wOpenLast = new Button(wGeneralComp, SWT.CHECK); props.setLook(wOpenLast); wOpenLast.setSelection(props.openLastFile()); FormData fdOpenLast = new FormData(); fdOpenLast.left = new FormAttachment(middle, 0); fdOpenLast.top = new FormAttachment(wUseCache, margin); fdOpenLast.right = new FormAttachment(100, 0); wOpenLast.setLayoutData(fdOpenLast); // Auto save changed files? Label wlAutoSave = new Label(wGeneralComp, SWT.RIGHT); wlAutoSave.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.AutoSave.Label")); props.setLook(wlAutoSave); FormData fdlAutoSave = new FormData(); fdlAutoSave.left = new FormAttachment(0, 0); fdlAutoSave.top = new FormAttachment(wOpenLast, margin); fdlAutoSave.right = new FormAttachment(middle, -margin); wlAutoSave.setLayoutData(fdlAutoSave); wAutoSave = new Button(wGeneralComp, SWT.CHECK); props.setLook(wAutoSave); wAutoSave.setSelection(props.getAutoSave()); FormData fdAutoSave = new FormData(); fdAutoSave.left = new FormAttachment(middle, 0); fdAutoSave.top = new FormAttachment(wOpenLast, margin); fdAutoSave.right = new FormAttachment(100, 0); wAutoSave.setLayoutData(fdAutoSave); // Auto save changed files? Label wlOnlyActiveFile = new Label(wGeneralComp, SWT.RIGHT); wlOnlyActiveFile.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.OnlyActiveFile.Label")); props.setLook(wlOnlyActiveFile); FormData fdlOnlyActiveFile = new FormData(); fdlOnlyActiveFile.left = new FormAttachment(0, 0); fdlOnlyActiveFile.top = new FormAttachment(wAutoSave, margin); fdlOnlyActiveFile.right = new FormAttachment(middle, -margin); wlOnlyActiveFile.setLayoutData(fdlOnlyActiveFile); wOnlyActiveFile = new Button(wGeneralComp, SWT.CHECK); props.setLook(wOnlyActiveFile); wOnlyActiveFile.setSelection(props.isOnlyActiveFileShownInTree()); FormData fdOnlyActiveFile = new FormData(); fdOnlyActiveFile.left = new FormAttachment(middle, 0); fdOnlyActiveFile.top = new FormAttachment(wAutoSave, margin); fdOnlyActiveFile.right = new FormAttachment(100, 0); wOnlyActiveFile.setLayoutData(fdOnlyActiveFile); // Only save used connections to XML? Label wlDBConnXML = new Label(wGeneralComp, SWT.RIGHT); wlDBConnXML.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.OnlySaveUsedConnections.Label")); props.setLook(wlDBConnXML); FormData fdlDBConnXML = new FormData(); fdlDBConnXML.left = new FormAttachment(0, 0); fdlDBConnXML.top = new FormAttachment(wOnlyActiveFile, margin); fdlDBConnXML.right = new FormAttachment(middle, -margin); wlDBConnXML.setLayoutData(fdlDBConnXML); wDBConnXML = new Button(wGeneralComp, SWT.CHECK); props.setLook(wDBConnXML); wDBConnXML.setSelection(props.areOnlyUsedConnectionsSavedToXML()); FormData fdDBConnXML = new FormData(); fdDBConnXML.left = new FormAttachment(middle, 0); fdDBConnXML.top = new FormAttachment(wOnlyActiveFile, margin); fdDBConnXML.right = new FormAttachment(100, 0); wDBConnXML.setLayoutData(fdDBConnXML); // Ask about replacing existing connections? Label wlAskReplaceDB = new Label(wGeneralComp, SWT.RIGHT); wlAskReplaceDB.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ReplaceDBAsk.Label")); props.setLook(wlAskReplaceDB); FormData fdlAskReplaceDB = new FormData(); fdlAskReplaceDB.left = new FormAttachment(0, 0); fdlAskReplaceDB.top = new FormAttachment(wDBConnXML, margin); fdlAskReplaceDB.right = new FormAttachment(middle, -margin); wlAskReplaceDB.setLayoutData(fdlAskReplaceDB); wAskReplaceDB = new Button(wGeneralComp, SWT.CHECK); props.setLook(wAskReplaceDB); wAskReplaceDB.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.ReplaceDBAsk.Tooltip")); wAskReplaceDB.setSelection(props.askAboutReplacingDatabaseConnections()); FormData fdAskReplaceDB = new FormData(); fdAskReplaceDB.left = new FormAttachment(middle, 0); fdAskReplaceDB.top = new FormAttachment(wDBConnXML, margin); fdAskReplaceDB.right = new FormAttachment(100, 0); wAskReplaceDB.setLayoutData(fdAskReplaceDB); // Only save used connections to XML? Label wlReplaceDB = new Label(wGeneralComp, SWT.RIGHT); wlReplaceDB.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ReplaceDB.Label")); props.setLook(wlReplaceDB); FormData fdlReplaceDB = new FormData(); fdlReplaceDB.left = new FormAttachment(0, 0); fdlReplaceDB.top = new FormAttachment(wAskReplaceDB, margin); fdlReplaceDB.right = new FormAttachment(middle, -margin); wlReplaceDB.setLayoutData(fdlReplaceDB); wReplaceDB = new Button(wGeneralComp, SWT.CHECK); props.setLook(wReplaceDB); wReplaceDB.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.ReplaceDB.Tooltip")); wReplaceDB.setSelection(props.replaceExistingDatabaseConnections()); FormData fdReplaceDB = new FormData(); fdReplaceDB.left = new FormAttachment(middle, 0); fdReplaceDB.top = new FormAttachment(wAskReplaceDB, margin); fdReplaceDB.right = new FormAttachment(100, 0); wReplaceDB.setLayoutData(fdReplaceDB); // Show confirmation after save? Label wlSaveConf = new Label(wGeneralComp, SWT.RIGHT); wlSaveConf.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ShowSaveConfirmation.Label")); props.setLook(wlSaveConf); FormData fdlSaveConf = new FormData(); fdlSaveConf.left = new FormAttachment(0, 0); fdlSaveConf.top = new FormAttachment(wReplaceDB, margin); fdlSaveConf.right = new FormAttachment(middle, -margin); wlSaveConf.setLayoutData(fdlSaveConf); wSaveConf = new Button(wGeneralComp, SWT.CHECK); props.setLook(wSaveConf); wSaveConf.setSelection(props.getSaveConfirmation()); FormData fdSaveConf = new FormData(); fdSaveConf.left = new FormAttachment(middle, 0); fdSaveConf.top = new FormAttachment(wReplaceDB, margin); fdSaveConf.right = new FormAttachment(100, 0); wSaveConf.setLayoutData(fdSaveConf); // Automatically split hops? Label wlAutoSplit = new Label(wGeneralComp, SWT.RIGHT); wlAutoSplit.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.AutoSplitHops.Label")); props.setLook(wlAutoSplit); FormData fdlAutoSplit = new FormData(); fdlAutoSplit.left = new FormAttachment(0, 0); fdlAutoSplit.top = new FormAttachment(wSaveConf, margin); fdlAutoSplit.right = new FormAttachment(middle, -margin); wlAutoSplit.setLayoutData(fdlAutoSplit); wAutoSplit = new Button(wGeneralComp, SWT.CHECK); props.setLook(wAutoSplit); wAutoSplit.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.AutoSplitHops.Tooltip")); wAutoSplit.setSelection(props.getAutoSplit()); FormData fdAutoSplit = new FormData(); fdAutoSplit.left = new FormAttachment(middle, 0); fdAutoSplit.top = new FormAttachment(wSaveConf, margin); fdAutoSplit.right = new FormAttachment(100, 0); wAutoSplit.setLayoutData(fdAutoSplit); // Show warning for copy / distribute... Label wlCopyDistrib = new Label(wGeneralComp, SWT.RIGHT); wlCopyDistrib.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.CopyOrDistributeDialog.Label")); props.setLook(wlCopyDistrib); FormData fdlCopyDistrib = new FormData(); fdlCopyDistrib.left = new FormAttachment(0, 0); fdlCopyDistrib.top = new FormAttachment(wAutoSplit, margin); fdlCopyDistrib.right = new FormAttachment(middle, -margin); wlCopyDistrib.setLayoutData(fdlCopyDistrib); wCopyDistrib = new Button(wGeneralComp, SWT.CHECK); props.setLook(wCopyDistrib); wCopyDistrib.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.CopyOrDistributeDialog.Tooltip")); wCopyDistrib.setSelection(props.showCopyOrDistributeWarning()); FormData fdCopyDistrib = new FormData(); fdCopyDistrib.left = new FormAttachment(middle, 0); fdCopyDistrib.top = new FormAttachment(wAutoSplit, margin); fdCopyDistrib.right = new FormAttachment(100, 0); wCopyDistrib.setLayoutData(fdCopyDistrib); // Show repository dialog at startup? Label wlShowRep = new Label(wGeneralComp, SWT.RIGHT); wlShowRep.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ShowRepoDialog.Label")); props.setLook(wlShowRep); FormData fdlShowRep = new FormData(); fdlShowRep.left = new FormAttachment(0, 0); fdlShowRep.top = new FormAttachment(wCopyDistrib, margin); fdlShowRep.right = new FormAttachment(middle, -margin); wlShowRep.setLayoutData(fdlShowRep); wShowRep = new Button(wGeneralComp, SWT.CHECK); props.setLook(wShowRep); wShowRep.setSelection(props.showRepositoriesDialogAtStartup()); FormData fdShowRep = new FormData(); fdShowRep.left = new FormAttachment(middle, 0); fdShowRep.top = new FormAttachment(wCopyDistrib, margin); fdShowRep.right = new FormAttachment(100, 0); wShowRep.setLayoutData(fdShowRep); // Show exit warning? Label wlExitWarning = new Label(wGeneralComp, SWT.RIGHT); wlExitWarning.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.AskOnExit.Label")); props.setLook(wlExitWarning); FormData fdlExitWarning = new FormData(); fdlExitWarning.left = new FormAttachment(0, 0); fdlExitWarning.top = new FormAttachment(wShowRep, margin); fdlExitWarning.right = new FormAttachment(middle, -margin); wlExitWarning.setLayoutData(fdlExitWarning); wExitWarning = new Button(wGeneralComp, SWT.CHECK); props.setLook(wExitWarning); wExitWarning.setSelection(props.showExitWarning()); FormData fdExitWarning = new FormData(); fdExitWarning.left = new FormAttachment(middle, 0); fdExitWarning.top = new FormAttachment(wShowRep, margin); fdExitWarning.right = new FormAttachment(100, 0); wExitWarning.setLayoutData(fdExitWarning); // Clear custom parameters. (from step) Label wlClearCustom = new Label(wGeneralComp, SWT.RIGHT); wlClearCustom.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ClearCustomParameters.Label")); props.setLook(wlClearCustom); FormData fdlClearCustom = new FormData(); fdlClearCustom.left = new FormAttachment(0, 0); fdlClearCustom.top = new FormAttachment(wExitWarning, margin + 10); fdlClearCustom.right = new FormAttachment(middle, -margin); wlClearCustom.setLayoutData(fdlClearCustom); wClearCustom = new Button(wGeneralComp, SWT.PUSH | SWT.BORDER); props.setLook(wClearCustom); FormData fdClearCustom = layoutResetOptionButton(wClearCustom); fdClearCustom.left = new FormAttachment(middle, 0); fdClearCustom.top = new FormAttachment(wExitWarning, margin); wClearCustom.setLayoutData(fdClearCustom); wClearCustom.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.ClearCustomParameters.Tooltip")); wClearCustom.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION); mb.setMessage(BaseMessages.getString(PKG, "EnterOptionsDialog.ClearCustomParameters.Question")); mb.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ClearCustomParameters.Title")); int id = mb.open(); if (id == SWT.YES) { props.clearCustomParameters(); props.saveProps(); MessageBox ok = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); ok.setMessage(BaseMessages.getString(PKG, "EnterOptionsDialog.ClearCustomParameters.Confirmation")); ok.open(); } } }); // Auto-collapse core objects tree branches? Label autoCollapseLbl = new Label(wGeneralComp, SWT.RIGHT); autoCollapseLbl.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.EnableAutoCollapseCoreObjectTree.Label")); props.setLook(autoCollapseLbl); FormData fdautoCollapse = new FormData(); fdautoCollapse.left = new FormAttachment(0, 0); fdautoCollapse.top = new FormAttachment(wlClearCustom, margin); fdautoCollapse.right = new FormAttachment(middle, -margin); autoCollapseLbl.setLayoutData(fdautoCollapse); autoCollapseBtn = new Button(wGeneralComp, SWT.CHECK); props.setLook(autoCollapseBtn); autoCollapseBtn.setSelection(props.getAutoCollapseCoreObjectsTree()); FormData helpautoCollapse = new FormData(); helpautoCollapse.left = new FormAttachment(middle, 0); helpautoCollapse.top = new FormAttachment(wlClearCustom, margin); helpautoCollapse.right = new FormAttachment(100, 0); autoCollapseBtn.setLayoutData(helpautoCollapse); // Tooltips Label tooltipLbl = new Label(wGeneralComp, SWT.RIGHT); tooltipLbl.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.ToolTipsEnabled.Label")); props.setLook(tooltipLbl); FormData fdlToolTipData = new FormData(); fdlToolTipData.left = new FormAttachment(0, 0); fdlToolTipData.top = new FormAttachment(autoCollapseLbl, margin); fdlToolTipData.right = new FormAttachment(middle, -margin); tooltipLbl.setLayoutData(fdlToolTipData); tooltipBtn = new Button(wGeneralComp, SWT.CHECK); props.setLook(tooltipBtn); tooltipBtn.setSelection(props.showToolTips()); FormData toolTipBtnData = new FormData(); toolTipBtnData.left = new FormAttachment(middle, 0); toolTipBtnData.top = new FormAttachment(autoCollapseLbl, margin); toolTipBtnData.right = new FormAttachment(100, 0); tooltipBtn.setLayoutData(toolTipBtnData); // Help tool tips Label helptipLbl = new Label(wGeneralComp, SWT.RIGHT); helptipLbl.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.HelpToolTipsEnabled.Label")); props.setLook(helptipLbl); FormData fdlHelpTipData = new FormData(); fdlHelpTipData.left = new FormAttachment(0, 0); fdlHelpTipData.top = new FormAttachment(tooltipLbl, margin); fdlHelpTipData.right = new FormAttachment(middle, -margin); helptipLbl.setLayoutData(fdlHelpTipData); helptipBtn = new Button(wGeneralComp, SWT.CHECK); props.setLook(helptipBtn); helptipBtn.setSelection(props.isShowingHelpToolTips()); FormData helpTipBtnData = new FormData(); helpTipBtnData.left = new FormAttachment(middle, 0); helpTipBtnData.top = new FormAttachment(tooltipLbl, margin); helpTipBtnData.right = new FormAttachment(100, 0); helptipBtn.setLayoutData(helpTipBtnData); fdGeneralComp = new FormData(); fdGeneralComp.left = new FormAttachment(0, 0); fdGeneralComp.right = new FormAttachment(100, 0); fdGeneralComp.top = new FormAttachment(0, 0); fdGeneralComp.bottom = new FormAttachment(100, 100); wGeneralComp.setLayoutData(fdGeneralComp); wGeneralComp.pack(); Rectangle bounds = wGeneralComp.getBounds(); sGeneralComp.setContent(wGeneralComp); sGeneralComp.setExpandHorizontal(true); sGeneralComp.setExpandVertical(true); sGeneralComp.setMinWidth(bounds.width); sGeneralComp.setMinHeight(bounds.height); wGeneralTab.setControl(sGeneralComp); // editables Label refLabel = new Label(wGeneralComp, SWT.RIGHT); refLabel = tooltipLbl; Button lastbtn = helptipBtn; for (final GUIOption<Object> e : PropsUI.getInstance().getRegisteredEditableComponents()) { Label wlMaxNrLogLines1 = new Label(wGeneralComp, SWT.RIGHT); wlMaxNrLogLines1.setText(e.getLabelText() == null ? "" : e.getLabelText()); props.setLook(wlMaxNrLogLines1); FormData fdlMaxNrLogLinesTemp = new FormData(); fdlMaxNrLogLinesTemp.left = new FormAttachment(0, 0); fdlMaxNrLogLinesTemp.right = new FormAttachment(middle, -margin); fdlMaxNrLogLinesTemp.top = new FormAttachment(refLabel, margin); wlMaxNrLogLines1.setLayoutData(fdlMaxNrLogLinesTemp); switch (e.getType()) { case TEXT_FIELD: //TODO: IMPLEMENT! break; case CHECK_BOX: final Button btn = new Button(wGeneralComp, SWT.CHECK); props.setLook(btn); btn.setSelection(new Boolean(e.getLastValue().toString()).booleanValue()); btn.setText(e.getLabelText()); FormData btnData = new FormData(); btnData.left = new FormAttachment(middle, 0); btnData.top = new FormAttachment(lastbtn, margin); btnData.right = new FormAttachment(100, 0); btn.setLayoutData(btnData); btn.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0){} public void widgetSelected(SelectionEvent ev) { e.setValue(btn.getSelection()); }}); lastbtn = btn; } } // / END OF GENERAL TAB } /** * Setting the layout of a <i>Reset</i> option button. Either a button * image is set - if existing - or a text. * * @param button * The button */ private FormData layoutResetOptionButton(Button button) { FormData fd = new FormData(); Image editButton = GUIResource.getInstance().getResetOptionButton(); if (editButton != null) { button.setImage(editButton); button.setBackground(GUIResource.getInstance().getColorWhite()); fd.width = editButton.getBounds().width + 4; fd.height = editButton.getBounds().height; } else { button.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.Button.Reset")); } button.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.Button.Reset.Tooltip")); return fd; } /** * Setting the layout of an <i>Edit</i> option button. Either a button * image is set - if existing - or a text. * * @param button * The button */ private FormData layoutEditOptionButton(Button button) { FormData fd = new FormData(); Image editButton = GUIResource.getInstance().getEditOptionButton(); if (editButton != null) { button.setImage(editButton); button.setBackground(GUIResource.getInstance().getColorWhite()); fd.width = editButton.getBounds().width + 4; fd.height = editButton.getBounds().height; } else { button.setText(BaseMessages.getString(PKG, "EnterOptionsDialog.Button.Edit")); } button.setToolTipText(BaseMessages.getString(PKG, "EnterOptionsDialog.Button.Edit.Tooltip")); return fd; } public void dispose() { fixedFont.dispose(); graphFont.dispose(); noteFont.dispose(); background.dispose(); graphColor.dispose(); tabColor.dispose(); shell.dispose(); } public void getData() { fixedFontData = props.getFixedFont(); fixedFont = new Font(display, fixedFontData); graphFontData = props.getGraphFont(); graphFont = new Font(display, graphFontData); noteFontData = props.getNoteFont(); noteFont = new Font(display, noteFontData); backgroundRGB = props.getBackgroundRGB(); if (backgroundRGB == null) backgroundRGB = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND).getRGB(); background = new Color(display, backgroundRGB); graphColorRGB = props.getGraphColorRGB(); graphColor = new Color(display, graphColorRGB); tabColorRGB = props.getTabColorRGB(); tabColor = new Color(display, tabColorRGB); } private void cancel() { props.setScreen(new WindowProperty(shell)); props = null; dispose(); } private void ok() { props.setFixedFont(fixedFontData); props.setGraphFont(graphFontData); props.setNoteFont(noteFontData); props.setBackgroundRGB(backgroundRGB); props.setGraphColorRGB(graphColorRGB); props.setTabColorRGB(tabColorRGB); props.setIconSize(Const.toInt(wIconsize.getText(), props.getIconSize())); props.setLineWidth(Const.toInt(wLineWidth.getText(), props.getLineWidth())); props.setShadowSize(Const.toInt(wShadowSize.getText(), props.getShadowSize())); props.setMiddlePct(Const.toInt(wMiddlePct.getText(), props.getMiddlePct())); props.setCanvasGridSize(Const.toInt(wGridSize.getText(), 1)); props.setDefaultPreviewSize(Const.toInt(wDefaultPreview.getText(), props.getDefaultPreviewSize())); props.setMaxNrLinesInLog(Const.toInt(wMaxNrLogLines.getText(), Const.MAX_NR_LOG_LINES)); props.setMaxLogLineTimeoutMinutes(Const.toInt(wMaxLogLineTimeout.getText(), Const.MAX_LOG_LINE_TIMEOUT_MINUTES)); props.setMaxNrLinesInHistory(Const.toInt(wMaxNrHistLines.getText(), Const.MAX_NR_HISTORY_LINES)); props.setMaxUndo(Const.toInt(wMaxUndo.getText(), props.getMaxUndo())); props.setShowTips(wShowTips.getSelection()); props.setShowWelcomePageOnStartup(wShowWelcome.getSelection()); props.setUseDBCache(wUseCache.getSelection()); props.setOpenLastFile(wOpenLast.getSelection()); props.setAutoSave(wAutoSave.getSelection()); props.setOnlyActiveFileShownInTree(wOnlyActiveFile.getSelection()); props.setOnlyUsedConnectionsSavedToXML(wDBConnXML.getSelection()); props.setAskAboutReplacingDatabaseConnections(wAskReplaceDB.getSelection()); props.setReplaceDatabaseConnections(wReplaceDB.getSelection()); props.setSaveConfirmation(wSaveConf.getSelection()); props.setAutoSplit(wAutoSplit.getSelection()); props.setShowCopyOrDistributeWarning(wCopyDistrib.getSelection()); props.setRepositoriesDialogAtStartupShown(wShowRep.getSelection()); props.setAntiAliasingEnabled(wAntiAlias.getSelection()); props.setExitWarningShown(wExitWarning.getSelection()); props.setOSLookShown(wOriginalLook.getSelection()); props.setBrandingActive(wBranding.getSelection()); props.setShowToolTips(tooltipBtn.getSelection()); props.setAutoCollapseCoreObjectsTree(autoCollapseBtn.getSelection()); props.setShowingHelpToolTips(helptipBtn.getSelection()); int defaultLocaleIndex = wDefaultLocale.getSelectionIndex(); if (defaultLocaleIndex < 0 || defaultLocaleIndex >= GlobalMessages.localeCodes.length) { // Code hardening, when the combo-box ever gets in a strange state, // use the first language as default (should be English) defaultLocaleIndex = 0; } int failoverLocaleIndex = wFailoverLocale.getSelectionIndex(); if (failoverLocaleIndex < 0 || failoverLocaleIndex >= GlobalMessages.localeCodes.length) { failoverLocaleIndex = 0; } LanguageChoice.getInstance().setDefaultLocale( new Locale(GlobalMessages.localeCodes[defaultLocaleIndex])); LanguageChoice.getInstance().setFailoverLocale( new Locale(GlobalMessages.localeCodes[failoverLocaleIndex])); LanguageChoice.getInstance().saveSettings(); props.saveProps(); dispose(); } }
package ru.mail.park.chat.api; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.jivesoftware.smack.proxy.ProxyInfo; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.security.KeyManagementException; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Random; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; import ru.mail.park.chat.message_interfaces.IChatListener; import ru.mail.park.chat.message_interfaces.IMessageSender; import ru.mail.park.chat.models.Message; import ru.mail.park.chat.security.SSLServerStuffFactory; // TODO: review flow and architecture in context of security // TODO: consider using java NIO public class P2PService extends Service implements IMessageSender { public static final String ACTION_START_SERVER = P2PService.class.getCanonicalName() + ".ACTION_START_SERVER"; public static final String ACTION_START_CLIENT = P2PService.class.getCanonicalName() + ".ACTION_START_CLIENT"; public static final String DESTINATION_URL = P2PService.class.getCanonicalName() + ".DESTINATION_URL"; public static final String DESTINATION_PORT = P2PService.class.getCanonicalName() + ".DESTINATION_PORT"; private static final int DEFAULT_LISTENING_PORT = 8275; private ServerSocket serverSocket; private final Object inputSynchronizer = new Object(); private final Object outputSynchronizer = new Object(); private volatile ObjectInputStream input; private volatile ObjectOutputStream output; private volatile IChatListener chatListener; private volatile boolean noStop = true; @Override public void onCreate() { super.onCreate(); Log.d(P2PService.class.getSimpleName(), "Starting thread"); Server server = new Server(); server.start(); Log.d(P2PService.class.getSimpleName(), "Finishing onCreate"); } public void sendMessage(String chatID, Message message) { send(message); } public void sendFirstMessage(String userID, Message message) { send(message); } private void send(final Message message) { Log.i(P2PService.class.getSimpleName() + " OUT message", message.getMessageBody()); new Thread() { public void run() { if (output != null) { synchronized (outputSynchronizer) { if (output != null) { try { if (output != null) { synchronized (outputSynchronizer) { if (output != null) { output.writeObject(message); acknowledgeOutgoingMessage(message); } } } } catch (IOException e) { e.printStackTrace(); } } } } } }.start(); } public void addListener(IChatListener chatListener) { this.chatListener = chatListener; } @Nullable @Override public IBinder onBind(final Intent intent) { new Thread() { @Override public void run() { onHandleIntent(intent); } }.start(); return mBinder; } private final IBinder mBinder = new P2PServiceSingletonBinder(); public class P2PServiceSingletonBinder extends Binder { public P2PService getService() { return P2PService.this; } } protected synchronized void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (action.equals(ACTION_START_CLIENT)) { String destination = intent.getStringExtra(DESTINATION_URL); int port = intent.getIntExtra(DESTINATION_PORT, DEFAULT_LISTENING_PORT); handleActionStartClient(destination, port); } else if (action.equals(ACTION_START_SERVER)) { int port = DEFAULT_LISTENING_PORT; handleActionStartServer(port); } } } public void handleActionStartClient(String destination, int port) { final Random rndForTorCircuits = new Random(); final String user = rndForTorCircuits.nextInt(100000) + ""; final String pass = rndForTorCircuits.nextInt(100000) + ""; final int proxyPort = 9050; final String proxyHost = "127.0.0.1"; Log.d(P2PService.class.getSimpleName(), "Destination " + destination); Log.d(P2PService.class.getSimpleName(), "Port " + String.valueOf(port)); ProxyInfo proxyInfo = new ProxyInfo(ProxyInfo.ProxyType.SOCKS5, proxyHost, proxyPort, user, pass); try { closeStreams(); Socket socket = proxyInfo.getSocketFactory().createSocket(destination, port); socket = wrapSocketWithSSL(socket, true); synchronized (outputSynchronizer) { output = new ObjectOutputStream(socket.getOutputStream()); } synchronized (inputSynchronizer) { input = new ObjectInputStream(socket.getInputStream()); } Log.i(P2PService.class.getSimpleName(), "got a connection"); Log.i(P2PService.class.getSimpleName(), destination); } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } } @NonNull private static SSLContext getSSLContext(KeyManager[] km, TrustManager[] trustManagers) throws KeyManagementException, NoSuchAlgorithmException { SecureRandom secureRandom = new SecureRandom(); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); Log.d("KeyManager", Arrays.toString(km)); Log.d("TrustManagers", Arrays.toString(trustManagers)); sslContext.init(km, trustManagers, secureRandom); return sslContext; } /** * @return Insecure dummy TrustManager which trusts everyone */ @Deprecated private TrustManager getTrustManager() { return new X509TrustManager() { String TAG = "TrustManager"; public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { Log.d(TAG, "Check client trusted"); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Log.d(TAG, "Check server trusted"); for (X509Certificate cert : chain) { Log.d(TAG + ".cert", cert.toString()); } } public X509Certificate[] getAcceptedIssuers() { Log.d(TAG, "getAcceptedIssuers"); return null; } }; } /** * @return Insecure dummy KeyManager which trusts everyone */ @Deprecated private KeyManager[] getKeyManagers() { try { byte[] nonce = SSLServerStuffFactory.generateNonce(); KeyPair kp = SSLServerStuffFactory.generateKeyPair(new SecureRandom()); X509Certificate cert = SSLServerStuffFactory.createCACert(kp.getPublic(), kp.getPrivate()); KeyStore ks = SSLServerStuffFactory.generateKeyStore(nonce, kp, cert); Log.d("Cert alias", ks.getCertificateAlias(cert)); Log.d("Cert sigalg", cert.getSigAlgName()); //byte[] keyData = SSLServerStuffFactory.generateKeyData(ks, nonce); //KeyStore fks = SSLServerStuffFactory.initializeKeyStore(keyData, nonce); KeyManager[] kms = SSLServerStuffFactory.getKeyManagers(nonce, ks); Log.d("getKeyManagers", String.valueOf(kms.length)); for (int i = 0; i < kms.length; i++) { kms[i] = new LogMan((X509KeyManager) kms[i]); } return kms; } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException | UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.e("getKeyManagers", "Could not create.."); return null; } private static class LogMan implements X509KeyManager { private static final String TAG = LogMan.class.getSimpleName(); private final X509KeyManager km; public LogMan(X509KeyManager wrapped) { km = wrapped; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { Log.d(TAG, "chooseClientAlias"); return km.chooseClientAlias(keyType, issuers, socket); } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { Log.d(TAG, "chooseServerAlias"); return km.chooseServerAlias(keyType, issuers, socket); } @Override public X509Certificate[] getCertificateChain(String alias) { Log.d(TAG, "getCertificateChain"); return km.getCertificateChain(alias); } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { Log.d(TAG, "getClientAliases"); return km.getClientAliases(keyType, issuers); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { Log.d(TAG, "getServerAliases"); return km.getServerAliases(keyType, issuers); } @Override public PrivateKey getPrivateKey(String alias) { Log.d(TAG, "getPrivateKey"); return km.getPrivateKey(alias); } } /** * * @param socket plain socket to wrap * @param isClient whether we're on a client side (needed for handshake) * @return SSL socket created over an existing plain socket * @throws IOException */ private SSLSocket wrapSocketWithSSL(Socket socket, boolean isClient) throws IOException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext; if (!isClient) { Log.d("Server", "cool!"); sslContext = getSSLContext(getKeyManagers(), new TrustManager[]{getTrustManager()}); } else { Log.d("Client", "not cool... =("); sslContext = getSSLContext(null, new TrustManager[]{getTrustManager()}); } // sslContext = getSSLContext(getKeyManagers(), new TrustManager[]{getTrustManager()}); SSLSocketFactory factory = (SSLSocketFactory) sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(isClient); sslSocket.setEnabledProtocols(sslSocket.getSupportedProtocols()); sslSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites()); for (String suite : sslSocket.getEnabledCipherSuites()) { Log.d("Suite", suite); } sslSocket.startHandshake(); return sslSocket; } // TODO: implement error dispatch // TODO: move generation methods to (?) subclass public void handleActionStartServer(int port) { try { closeStreams(); serverSocket = new ServerSocket(port); Log.i(P2PService.class.getSimpleName() + " IP", serverSocket.getInetAddress().getCanonicalHostName()); Socket socket = serverSocket.accept(); Log.i(P2PService.class.getSimpleName() + " IP", "Incoming: " + socket.getInetAddress().getCanonicalHostName()); socket = wrapSocketWithSSL(socket, false); synchronized (inputSynchronizer) { input = new ObjectInputStream(socket.getInputStream()); } synchronized (outputSynchronizer) { output = new ObjectOutputStream(socket.getOutputStream()); } Log.i(P2PService.class.getSimpleName(), "connection finished!"); } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } } private void handleIncomingMessage(final Message message) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { if (chatListener != null) { chatListener.onIncomeMessage(message); } } }); } private void acknowledgeOutgoingMessage(final Message message) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { if (chatListener != null) { chatListener.onAcknowledgeSendMessage(message); } } }); } private class Server extends Thread { @Override public void run() { try { while (noStop) { Message message = null; if (input != null) { synchronized (inputSynchronizer) { if (input != null) { Object object = input.readObject(); if (object instanceof Message) { message = (Message) object; } } } } if (message != null) { Log.i(P2PService.class.getSimpleName() + " IN message", message.toString()); handleIncomingMessage(message); } } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } private void closeStreams() { Log.d(P2PService.class.getSimpleName(), "Closing streams"); try { if (output != null) { synchronized (outputSynchronizer) { if (output != null) { output.flush(); output.close(); output = null; } } } if (input != null) { synchronized (inputSynchronizer) { if (input != null) { input.close(); input = null; } } } if (serverSocket != null) { serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } @Override public boolean isConnected() { return output != null && input != null; } @Override public void reconnect() { } @Override public void write(@NonNull String cid) { } @Override public void disconnect() { closeStreams(); noStop = false; } @Override public void onDestroy() { Log.d(P2PService.class.getSimpleName(), "onDestroy"); super.onDestroy(); closeStreams(); noStop = false; } }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "7.0.6-SNAPSHOT"; static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n" + "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n" + "|____| \\___/ |_| |___| \\___| |___| /_/ "; static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n" + "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n" + "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n" + "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package game; abstract public class Ownable extends Field { protected Player owner; protected int price; protected int multiplier; protected int pawn; protected Updater updater; /** * Ownable Constructor * @param Name - The name of the Field * @param Price - The price of the field */ public Ownable(String name, int price){ super(name); this.price = price; } public void landOnField(Player player, Updater updater) { this.updater = updater; if (owner == null) { if (updater.getUserLeftButtonPressed("Vil De købe " + name + " for " + price + "?", "Ja", "Nej")) { if (player.getAccount() >= price) { owner = player; owner.alterAccount(-price); owner.setAssets((int)(price * 0.5)); if(this instanceof Brewery) { owner.setBrewery(); } if(this instanceof Fleet) { owner.setFleet(); } updater.showMessage(player.getName() + " købte og ejer nu " + name); updater.setOwner(player.getPosition(), player.getName()); } else { updater.showMessage("De har ikke nok penge til at købe denne grund."); } } else { Auction auction = new Auction(this.updater, player, players, this.field); auction.runAction(); auction = null; } } else if (!isOwner(player)) { this.multiplier = player.getRollSum(); updater.showMessage(player.getName() + " betaler " + getRent() + " til " + owner.getName()); player.payRent(getRent(), owner); } } public boolean isOwner(Player player) { return player == owner; } public int getPawn() { return this.pawn; } public void resetOwner() { owner = null; } public int getPrice(){ return this.price; } abstract int getRent(); public void setOwner(Player player){ owner = player; } }
package uz.samtuit.sammap.samapp; import android.annotation.TargetApi; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SlidingDrawer; import android.widget.TextView; import com.cocoahero.android.geojson.FeatureCollection; import com.mapbox.mapboxsdk.api.ILatLng; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.overlay.Icon; import com.mapbox.mapboxsdk.overlay.Marker; import com.mapbox.mapboxsdk.overlay.PathOverlay; import com.mapbox.mapboxsdk.tileprovider.tilesource.MBTilesLayer; import com.mapbox.mapboxsdk.tileprovider.tilesource.TileLayer; import com.mapbox.mapboxsdk.util.DataLoadingUtils; import com.mapbox.mapboxsdk.views.MapView; import com.mapbox.mapboxsdk.views.util.OnMapOrientationChangeListener; import java.util.ArrayList; public class MainMap extends ActionBarActivity { private LinearLayout linLay; private Button newBtn; private ArrayList<MenuItems> Items = new ArrayList<MenuItems>(); private ImageView btn,compass; private SlidingDrawer slidingDrawer; private boolean updateAvailable = true; private int height; private MapView mapView; private EditText searchText; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_map); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //search text typeface Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Thin.ttf"); searchText = (EditText)findViewById(R.id.search_text); searchText.setTypeface(tf); searchText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { } }); //MapView Settings mapView = (MapView)findViewById(R.id.mapview); compass = (ImageView)findViewById(R.id.compass); TileLayer mbTileLayer = new MBTilesLayer(this, "Sample.mbtiles"); mapView.setTileSource(mbTileLayer); mapView.setMinZoomLevel(mapView.getTileProvider().getMinimumZoomLevel()); mapView.setMaxZoomLevel(mapView.getTileProvider().getMaximumZoomLevel()); mapView.setCenter(mapView.getTileProvider().getCenterCoordinate()); mapView.setCenter(new ILatLng() { @Override public double getLatitude() { return 39.65487; } @Override public double getLongitude() { return 66.97562; } @Override public double getAltitude() { return 0; } }); // checkGpsSetting(); mapView.setUserLocationEnabled(true); mapView.setZoom(18); mapView.setMapRotationEnabled(true); mapView.setOnMapOrientationChangeListener(new OnMapOrientationChangeListener() { @Override public void onMapOrientationChange(float v) { compass.setRotation(mapView.getMapOrientation()); } }); //end Bundle extras = getIntent().getExtras(); if(extras!=null) { double lat,longt; lat = extras.getDouble("lat"); longt = extras.getDouble("long"); LatLng loc = new LatLng(lat,longt); // mapView.getController().goTo(loc, null); mapView.getController().animateTo(loc); }else { //Action when Update is Available if(updateAvailable) { new Handler().postDelayed(new Runnable() { @Override public void run() { Intent splash = new Intent(MainMap.this, Splash.class); startActivity(splash); } }, 0); Log.e("Error","None of time"); } //End } //generate Menu items MenuItems item = new MenuItems(0,"About City","drawable/about_city"); Items.add(item); item = new MenuItems(1,"Attractions","drawable/attractions"); Items.add(item); item = new MenuItems(2,"Food & Drink","drawable/food_drink"); Items.add(item); item = new MenuItems(3,"Hotels","drawable/hotel"); Items.add(item); item = new MenuItems(4,"Shopping","drawable/shop"); Items.add(item); item = new MenuItems(5,"My Schedule","drawable/my_schuld"); Items.add(item); item = new MenuItems(6,"Itinerary Wizard","drawable/itinerary"); Items.add(item); item = new MenuItems(7,"Train Timetable","drawable/trains"); Items.add(item); item = new MenuItems(8,"Tashkent -> Samarkand","drawable/shop"); Items.add(item); item = new MenuItems(9,"About This App","drawable/about_app"); Items.add(item); btn = (ImageView)findViewById(R.id.slideButton); slidingDrawer = (SlidingDrawer)findViewById(R.id.slidingDrawer); slidingDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() { @Override public void onDrawerOpened() { btn.setRotation(180); } }); slidingDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() { @Override public void onDrawerClosed() { btn.setRotation(0); } }); Animation fadeIn = AnimationUtils.loadAnimation(MainMap.this,R.anim.fade_in); btn.startAnimation(fadeIn); fadeIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { Animation fadeOut = AnimationUtils.loadAnimation(MainMap.this, R.anim.fade_out); btn.startAnimation(fadeOut); } @Override public void onAnimationRepeat(Animation animation) { } }); linLay = (LinearLayout)findViewById(R.id.menuScrollLinear); linLay.post(new Runnable() { @Override public void run() { Log.e("TEST", "SIZE: " + linLay.getHeight()); height = linLay.getHeight(); for (int i = 0; i < Items.size(); i++) { final int index = i; newBtn = new Button(MainMap.this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(height - 20, LinearLayout.LayoutParams.MATCH_PARENT); params.setMargins(5, 10, 5, 10); newBtn.setLayoutParams(params); newBtn.setText(" "); String path = Items.get(index).imageSrc; int mainImgResource = getResources().getIdentifier(path, null, getPackageName()); newBtn.setBackground(getResources().getDrawable(mainImgResource)); newBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent = GetIntent(Items.get(index).Title); startActivity(intent); } }); linLay.addView(newBtn); } } }); //Location Settings /* locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { Marker m = new Marker(mapView,"Here", "Your Current Location",new LatLng(location.getLatitude(),location.getLongitude())); m.setIcon(new Icon(MainMap.this, Icon.Size.LARGE, "land-use", "00FF00")); mapView.addMarker(m); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; */ //end } /** * Check current GPS setting * if GPS is OFF, let it turn ON * * @return * false: Need to turn on GPS * ture: Already GPS On * */ //compass click public void CompassClick(View view) { mapView.setMapOrientation(0); compass.setRotation(0); } //Search public void Search(View view) { EditText searchText = (EditText)findViewById(R.id.search_text); if(searchText.getVisibility()==View.VISIBLE) { //search searchText.setVisibility(View.INVISIBLE); } else { searchText.setVisibility(View.VISIBLE); } } private boolean checkGpsSetting() { int gpsStatus = 0; try { gpsStatus = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE); } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } Log.d("GPS", "checkGpsSetting():LOCATION_MODE:" + gpsStatus); if (gpsStatus == 0) { // if LOCATION_MODE_OFF AlertDialog.Builder gsDialog = new AlertDialog.Builder(this); gsDialog.setTitle("Location Service Setting"); gsDialog.setMessage("To find your correct position, you should turn on GPS.\nDo you want to turn on the GPS?"); gsDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Go to the GPS setting Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); startActivity(intent); } }) .setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }).create().show(); return false; } else { return true; // Already GPS ON } } /** * Start Location Service */ // private void startLocationService() { // LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // GPSListener gpsListener = new GPSListener(); // long minTime = 10000; // 10s // float minDistance = 0; // manager.requestLocationUpdates( // LocationManager.GPS_PROVIDER, // minTime, // minDistance, // gpsListener); // // Even though position is not confirmed, Find the recentest current position. // String msg = "LocationService Started!!!"; // Log.d("GPS", "startLocationService():" + msg); /** * GPS Location Listener */ private class GPSListener implements LocationListener { public void onLocationChanged(Location location) { } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } private Intent GetIntent(String name) { Intent intent = null; switch (name) { case "Hotels": intent = new Intent(MainMap.this, HotelsActivity.class); break; case "Attractions": intent = new Intent(MainMap.this, AttractionsActivity.class); break; case "About This App": intent = new Intent(MainMap.this, AboutCityActivity.class); break; case "Shopping": intent = new Intent(MainMap.this, ShoppingActivity.class); break; case "Food & Drink": intent = new Intent(MainMap.this, FoodAndDrinkActivity.class); break; case "About City": intent = new Intent(MainMap.this, AboutCityActivity.class); break; case "My Schedule": intent = new Intent(MainMap.this, MyScheduleActivity.class); break; case "Suggested Itinerary": intent = new Intent(MainMap.this, SuggestedItinerary.class); break; case "Train Timetable": intent = new Intent(MainMap.this, TrainsTimeTableActivity.class); break; case "Tashkent -> Samarkand": intent = new Intent(MainMap.this, TashkentSamarkandActivity.class); break; } return intent; } @Override protected void onResume() { super.onResume(); // Load GeoJSON String[] files = {"hotels_0_001.geojson", "foodanddrinks_0_001.geojson", "attractions_0_001.geojson","shops_0_001.geojson"}; Drawable[] drawables = { getResources().getDrawable(R.drawable.hotel_marker), getResources().getDrawable(R.drawable.food_marker), getResources().getDrawable(R.drawable.attraction_marker), getResources().getDrawable(R.drawable.shop_marker) }; for(int i = 0; i < files.length; i++) { try { FeatureCollection features = DataLoadingUtils.loadGeoJSONFromAssets(MainMap.this, files[i]); ArrayList<Object> uiObjects = DataLoadingUtils.createUIObjectsFromGeoJSONObjects(features, null); for (Object obj : uiObjects) { if (obj instanceof Marker) { Marker m = (Marker)obj; m.setIcon(new Icon(drawables[i])); mapView.addMarker(m); } else if (obj instanceof PathOverlay) { mapView.getOverlays().add((PathOverlay) obj); } } if (uiObjects.size() > 0) { mapView.invalidate(); } } catch (Exception e) { e.printStackTrace(); } } } }
package org.vosao.business.impl.imex; import java.util.Iterator; import java.util.List; import org.dom4j.Element; import org.vosao.business.Business; import org.vosao.dao.Dao; import org.vosao.entity.FieldEntity; import org.vosao.entity.FormConfigEntity; import org.vosao.entity.FormEntity; import org.vosao.enums.FieldType; import org.vosao.utils.XmlUtil; public class FormExporter extends AbstractExporter { public FormExporter(Dao aDao, Business aBusiness) { super(aDao, aBusiness); } public void createFormsXML(Element formsElement) { createFormConfigXML(formsElement); List<FormEntity> list = getDao().getFormDao().select(); for (FormEntity form : list) { createFormXML(formsElement, form); } } private void createFormConfigXML(Element formsElement) { FormConfigEntity config = getDao().getFormDao().getConfig(); Element configElement = formsElement.addElement("form-config"); Element formTemplateElement = configElement.addElement("formTemplate"); formTemplateElement.setText(config.getFormTemplate()); Element formLetterElement = configElement.addElement("letterTemplate"); formLetterElement.setText(config.getLetterTemplate()); } private void createFormXML(Element formsElement, final FormEntity form) { Element formElement = formsElement.addElement("form"); formElement.addAttribute("name", form.getName()); formElement.addAttribute("title", form.getTitle()); formElement.addAttribute("email", form.getEmail()); formElement.addAttribute("letterSubject", form.getLetterSubject()); formElement.addAttribute("sendButtonTitle", form.getSendButtonTitle()); formElement.addAttribute("showResetButton", String.valueOf( form.isShowResetButton())); formElement.addAttribute("enableCaptcha", String.valueOf( form.isEnableCaptcha())); formElement.addAttribute("resetButtonTitle", form.getResetButtonTitle()); List<FieldEntity> fields = getDao().getFieldDao().getByForm(form); for (FieldEntity field : fields) { createFieldXML(formElement, field); } } public void readForms(Element formsElement) { for (Iterator<Element> i = formsElement.elementIterator(); i.hasNext(); ) { Element element = i.next(); if (element.getName().equals("form")) { String name = element.attributeValue("name"); String title = element.attributeValue("title"); String email = element.attributeValue("email"); String letterSubject = element.attributeValue("letterSubject"); FormEntity form = new FormEntity(name, email, title, letterSubject); form.setSendButtonTitle(element.attributeValue("sendButtonTitle")); form.setShowResetButton(XmlUtil.readBooleanAttr(element, "showResetButton", false)); form.setEnableCaptcha(XmlUtil.readBooleanAttr(element, "enableCaptcha", false)); form.setResetButtonTitle(element.attributeValue("resetButtonTitle")); getDao().getFormDao().save(form); readFields(element, form); } if (element.getName().equals("form-config")) { readFormConfig(element); } } } private void createFieldXML(Element formElement, FieldEntity field) { Element fieldElement = formElement.addElement("field"); fieldElement.addAttribute("name", field.getName()); fieldElement.addAttribute("title", field.getTitle()); fieldElement.addAttribute("fieldType", field.getFieldType().name()); fieldElement.addAttribute("optional", String.valueOf(field.isOptional())); fieldElement.addAttribute("values", field.getValues()); fieldElement.addAttribute("defaultValue", field.getDefaultValue()); fieldElement.addAttribute("height", String.valueOf(field.getHeight())); fieldElement.addAttribute("width", String.valueOf(field.getWidth())); } public void readFields(Element formElement, FormEntity form) { for (Iterator<Element> i = formElement.elementIterator(); i.hasNext(); ) { Element element = i.next(); if (element.getName().equals("field")) { FieldEntity field = new FieldEntity(); field.setFormId(form.getId()); field.setName(element.attributeValue("name")); field.setTitle(element.attributeValue("title")); try { field.setFieldType(FieldType.valueOf(element .attributeValue("fieldType"))); } catch (Exception e) { field.setFieldType(FieldType.TEXT); } field.setOptional(XmlUtil.readBooleanAttr(element, "optional", false)); field.setValues(element.attributeValue("values")); field.setDefaultValue(element.attributeValue("defaultValue")); field.setHeight(XmlUtil.readIntAttr(element, "height", 0)); field.setWidth(XmlUtil.readIntAttr(element, "width", 20)); getDao().getFieldDao().save(field); } } } public void readFormConfig(Element configElement) { FormConfigEntity config = getDao().getFormDao().getConfig(); for (Iterator<Element> i = configElement.elementIterator(); i.hasNext(); ) { Element element = i.next(); if (element.getName().equals("formTemplate")) { config.setFormTemplate(element.getText()); } if (element.getName().equals("letterTemplate")) { config.setLetterTemplate(element.getText()); } } getDao().getFormDao().save(config); } }
package evoker; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Vector; /** * Change the genotype information within a bed file (and write to a new one) */ public class BEDFileChanger { /** Holds the list of inds (in correct order) */ Vector<String> inds = null; /** Holds the changes made to the collection (_not_ in correct order)*/ HashMap<String, HashMap<String, HashMap<String, Byte>>> changes; // chromosome -> snp -> [ind -> change] HashMap<String, Marker> markerTable; /** Name of the collection to save */ String collection = null; /** Path for file to be read */ String path = null; /** internal ID of collection */ int collectionID = -1; /** Absolute path of output file */ String toWriteTo = null; /** Information about conversion from the internal genotype notation to the bed-one. */ HashMap<Byte, Integer> genotpeCoding = new HashMap<Byte, Integer>(); /** Number of SNPs contained in this collection */ int noOfSnps = -1; /** * Create a bed file from a given one according to the specified changes * * @param collectionID * @param collection * @param path * @param sd * @param noOfSnps * @param markerTable * @param changes * @param toWriteTo * @throws IOException */ BEDFileChanger(int collectionID, String collection, String path, Vector<String> inds, int noOfSnps, HashMap<String, Marker> markerTable, HashMap<String, HashMap<String, HashMap<String, Byte>>> changes, String toWriteTo) throws IOException { assert collectionID >= 0 && collection != null && path != null && inds != null && noOfSnps != 0 && markerTable != null && changes != null && !changes.keySet().isEmpty() && toWriteTo != null; this.inds = inds; this.changes = (HashMap<String, HashMap<String, HashMap<String, Byte>>>) changes.clone(); this.markerTable = markerTable; this.collection = collection; this.collectionID = collectionID; this.path = path; this.toWriteTo = toWriteTo; this.noOfSnps = noOfSnps; setGenotypeCoding(); write(); } /** * Create a bed file from a given one according to the specified changes. * Same as the other constructor, but collects the information itself. * * @param containing related information * @param collection name to save * @param absolute file(path) to write to * @throws IOException */ BEDFileChanger(DataDirectory db, String collection, String file) throws IOException { new BEDFileChanger(db.getMarkerData().collectionIndices.get(collection), collection, db.getDisplayName(), db.samplesByCollection.get(collection).inds, db.getMarkerData().getNumSNPs(collection), db.getMarkerData().getMarkerTable(), db.changesByCollection.get(collection), file); } /** * Sets the connection between the internal genotype coding and the bed-file-one */ private void setGenotypeCoding() { genotpeCoding.put((byte) 0, 0x00); //homo1 genotpeCoding.put((byte) 1, 0x40); //missing genotpeCoding.put((byte) 2, 0x80); //hetero genotpeCoding.put((byte) 3, 0xc0); //homo2 } /** * The writing algorithm. * * @throws FileNotFoundException * @throws IOException */ private void write() throws FileNotFoundException, IOException { int bytesPerSnp = (int) Math.ceil(((double) inds.size()) / 4); // for all the changed chromosomes. for (String chromosome : changes.keySet()) { //read file File f = new File(path + "/" + collection + "." + chromosome + ".bed"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f), 8192); //write file File f_write = new File(toWriteTo + "." + chromosome + ".bed"); if(f_write.exists()) f_write.delete(); BEDFileWriter bfw = new BEDFileWriter(f_write); //skip header long toskip = 3; while ((toskip = toskip - bis.skip(toskip)) > 0); long snpAt = 0; byte[] rawSnpData = null; // until there is no snp left for this chromosome to change. while (changes.get(chromosome).keySet().size() > 0) { String nextSnpToStopAt = null; long nextSnpIndex = Long.MAX_VALUE; // find the first snip to be changed for (String s : changes.get(chromosome).keySet()) { Marker m = markerTable.get(s); int index = m.getIndex(collectionID); if (index < nextSnpIndex) { nextSnpIndex = index; nextSnpToStopAt = s; } } // read in snp per snp, write it to file until we reach a changed snp long skip = nextSnpIndex - snpAt; for (int i = 0; i < skip; i++) { rawSnpData = new byte[bytesPerSnp]; bis.read(rawSnpData, 0, bytesPerSnp); bfw.write(rawSnpData); snpAt++; } // read that whole snp in rawSnpData = new byte[bytesPerSnp]; bis.read(rawSnpData, 0, bytesPerSnp); // find changed inds for (String ind : changes.get(chromosome).get(nextSnpToStopAt).keySet()) { long indexOfInd = inds.indexOf(ind); int indexOfIndInArray = (int) (indexOfInd / 4); int posInTheByteFromBeginning = (int) (3 - (indexOfInd % 4)); // still to be used as index, as it is turned around, big endian >.< rawSnpData[indexOfIndInArray] = changeByte(rawSnpData[indexOfIndInArray], posInTheByteFromBeginning, changes.get(chromosome).get(nextSnpToStopAt).get(ind)); } bfw.write(rawSnpData); snpAt++; // remove snp from the todo list changes.get(chromosome).remove(nextSnpToStopAt); } // there is nothing to change anymore, but there are still snps to coppy. for (; snpAt < noOfSnps; snpAt++) { rawSnpData = new byte[bytesPerSnp]; bis.read(rawSnpData, 0, bytesPerSnp); bfw.write(rawSnpData); } bfw.flush(); bfw.close(); } } /** * Change genotype within a byte * * @param byte to change * @param potition of the double-bit to change * @param genotype to change to (internal id-notation) * @return changed bit */ private byte changeByte(byte b, int posInTheByteFromBeginning, byte changeTo) { int byteToChange = b & 0xff; // java seems to convert bytes to ints while processing them, that'd give problems... (no, java does not suck, java is great.) int toOrWith = genotpeCoding.get(changeTo); int toResetTo0 = 0xc0; toOrWith = toOrWith >>> (posInTheByteFromBeginning * 2); toResetTo0 = toResetTo0 >>> (posInTheByteFromBeginning * 2); return (byte) ((byteToChange & ~toResetTo0) | toOrWith); } }
package org.commcare.views.widgets; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.commcare.dalvik.R; import org.commcare.utils.UniversalDate; import org.javarosa.form.api.FormEntryPrompt; import org.joda.time.DateTime; import java.util.Calendar; public class GregorianWidget extends AbstractUniversalDateWidget { private EditText dayTxt; private EditText monthTxt; private EditText yearTxt; private Calendar myCal; private String[] myMonths; public GregorianWidget(Context context, FormEntryPrompt prompt){ super(context, prompt); //Adds all the stuff for abstract date widget myCal = Calendar.getInstance(); //TODO: Validate input from text fields: Use a TextWatcher for this, use myCal to validate days in month //TODO: Update month array pointer based on text entered..check to see how super does this though } @Override protected void initText(){ dayTxt = (EditText)findViewById(R.id.daytxt); monthTxt = (EditText)findViewById(R.id.monthtxt); yearTxt = (EditText)findViewById(R.id.yeartxt); } @Override protected void inflateView(Context context){ LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View vv = vi.inflate(R.layout.gregorian_date_widget, null); addView(vv); } @Override protected void updateDateDisplay(long millisFromJavaEpoch) { UniversalDate dateUniv = fromMillis(millisFromJavaEpoch); dayTxt.setText(String.format("%02d", dateUniv.day)); monthTxt.setText(monthsArray[dateUniv.month - 1]); monthArrayPointer = dateUniv.month - 1; yearTxt.setText(String.format("%04d", dateUniv.year)); if(myCal == null) { myCal = Calendar.getInstance(); } myCal.setTimeInMillis(millisFromJavaEpoch); } @Override protected long getCurrentMillis() { int day = Integer.parseInt(dayTxt.getText().toString()); int month = monthArrayPointer + 1; int year = Integer.parseInt(yearTxt.getText().toString()); return toMillisFromJavaEpoch(year, month, day, millisOfDayOffset); } @Override protected void updateGregorianDateHelperDisplay(){} @Override protected UniversalDate decrementMonth(long millisFromJavaEpoch) { DateTime dt = new DateTime(millisFromJavaEpoch).minusMonths(1); return constructUniversalDate(dt); } @Override protected UniversalDate decrementYear(long millisFromJavaEpoch) { DateTime dt = new DateTime(millisFromJavaEpoch).minusYears(1); return constructUniversalDate(dt); } @Override protected UniversalDate fromMillis(long millisFromJavaEpoch) { return constructUniversalDate(new DateTime(millisFromJavaEpoch)); } @Override protected String[] getMonthsArray() { if(myMonths == null){ myMonths = new String[]{"January", "February", "March", "April", "May", "June", "July", "August","September","October","November","December"}; } return myMonths; } @Override protected UniversalDate incrementMonth(long millisFromJavaEpoch) { DateTime dt = new DateTime(millisFromJavaEpoch).plusMonths(1); return constructUniversalDate(dt); } @Override protected UniversalDate incrementYear(long millisFromJavaEpoch) { DateTime dt = new DateTime(millisFromJavaEpoch).plusYears(1); return constructUniversalDate(dt); } @Override protected long toMillisFromJavaEpoch(int year, int month, int day, long millisOffset) { DateTime dt = new DateTime() .withYear(year) .withMonthOfYear(month) .withDayOfMonth(day) .withMillisOfDay((int)millisOffset); return dt.getMillis(); } private UniversalDate constructUniversalDate(DateTime dt) { return new UniversalDate( dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getMillis() ); } }
package org.xbib.elasticsearch.plugin.jdbc; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; /** * This class represents one or many values. Each value is represented at most * once. New values are appended. */ public class Values<O extends Object> implements ToXContent { /** * The values are implemented as an object array */ @SuppressWarnings({"unchecked"}) private O[] values = (O[]) new Object[0]; /** * Create new Values from an existing values by appending a value. * * @param old existing values or null if values should be created * @param value a new value * @param sequence true if value should be splitted by commas to multiple values */ @SuppressWarnings({"unchecked"}) public Values(Object old, O value, boolean sequence) { if (old instanceof Values) { O[] vals = (O[]) ((Values) old).getValues(); if (vals != null) { this.values = vals; } } O[] newValues; if (sequence && value != null) { newValues = (O[]) value.toString().split(","); } else if (value instanceof Object[]) { newValues = (O[]) value; } else { newValues = (O[]) new Object[]{value}; } for (O v : newValues) { addValue(v); } } /** * Append value to existing values. * * @param v the value to add */ @SuppressWarnings({"unchecked"}) public void addValue(O v) { int l = this.values.length; for (O aValue : this.values) { if (v != null && v.equals(aValue)) { //value already found, do nothing return; } } if (l == 0) { this.values = (O[]) new Object[]{v}; } else { // never add a null value to an existing list of values if (v != null) { if (l == 1 && this.values[0] == null) { // if there's one existing value and it's null, replace it with the new one this.values = (O[]) new Object[]{v}; } else { // otherwise copy the existing value(s) and add the new one O[] oldValues = this.values; this.values = (O[]) new Object[l + 1]; System.arraycopy(oldValues, 0, this.values, 0, l); this.values[l] = v; } } } } /** * Get the values. * * @return the values */ public O[] getValues() { return this.values; } public boolean isNull() { return this.values.length == 0 || (this.values.length == 1 && this.values[0] == null); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.values.length > 1) { sb.append('['); } for (int i = 0; i < this.values.length; i++) { if (i > 0) { sb.append(','); } sb.append(format(this.values[i])); } if (this.values.length > 1) { sb.append(']'); } return sb.toString(); } /** * Format a value for JSON. * * @param o the value * @return the formtted value */ private String format(Object o) { if (o == null) { return "null"; } if (o instanceof Integer) { return Integer.toString((Integer) o); } if (o instanceof Long) { return Long.toString((Long) o); } if (o instanceof Boolean) { return Boolean.toString((Boolean) o); } if (o instanceof Float) { // suppress scientific notation return String.format("%.12f", (Float)o); } if (o instanceof Double) { // suppress scientific notation return String.format("%.12f", (Double)o); } // stringify String t = o.toString(); t = t.replaceAll("\"", "\\\""); return '"' + t + '"'; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (this.values.length == 0) { builder.nullValue(); return builder; } if (this.values.length > 1) { builder.startArray(); } for (O aValue : this.values) { builder.value(aValue); } if (this.values.length > 1) { builder.endArray(); } return builder; } }
package org.apache.commons.collections; import java.util.*; import java.io.*; /** * <code>MultiHashMap</code> is the default implementation of the * {@link MultiMap} interface. A <code>MultiMap</code> is a Map * with slightly different semantics. * Instead of returning an Object, it returns a Collection. * So for example, you can put( key, new Integer(1) ); * and then a Object get( key ); will return you a Collection * instead of an Integer. * * @since 2.0 * @author Christopher Berry * @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @author Steve Downey * @author Stephen Colebourne */ public class MultiHashMap extends HashMap implements MultiMap { private static int sCount = 0; private String mName = null; public MultiHashMap() { super(); setName(); } public MultiHashMap( int initialCapacity ) { super( initialCapacity ); setName(); } public MultiHashMap(int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor); setName(); } public MultiHashMap( Map mapToCopy ) { super( mapToCopy ); } private void setName() { sCount++; mName = "MultiMap-" + sCount; } public String getName() { return mName; } public Object put( Object key, Object value ) { // NOTE:: put might be called during deserialization !!!!!! // so we must provide a hook to handle this case // This means that we cannot make MultiMaps of ArrayLists !!! if ( value instanceof ArrayList ) { return ( super.put( key, value ) ); } ArrayList keyList = (ArrayList)(super.get( key )); if ( keyList == null ) { keyList = new ArrayList(10); super.put( key, keyList ); } boolean results = keyList.add( value ); return ( results ? value : null ); } public boolean containsValue( Object value ) { Set pairs = super.entrySet(); if ( pairs == null ) return false; Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); if( list.contains( value ) ) return true; } return false; } public Object remove( Object key, Object item ) { ArrayList valuesForKey = (ArrayList) super.get( key ); if ( valuesForKey == null ) return null; valuesForKey.remove( item ); return item; } public void clear() { Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); list.clear(); } super.clear(); } public void putAll( Map mapToPut ) { super.putAll( mapToPut ); } public Collection values() { ArrayList returnList = new ArrayList( super.size() ); Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); Object[] values = list.toArray(); for ( int ii=0; ii < values.length; ii++ ) { returnList.add( values[ii] ); } } return returnList; } // FIXME:: do we need to implement this?? // public boolean equals( Object obj ) {} public Object clone() { MultiHashMap obj = (MultiHashMap)(super.clone()); obj.mName = mName; return obj; } }
package cn.aofeng.threadpool4j; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import cn.aofeng.common4j.ILifeCycle; /** * * * @author <a href="mailto:aofengblog@163.com"></a> */ public class ThreadPoolImpl implements ILifeCycle, ThreadPool { private static Logger _logger = Logger.getLogger(ThreadPoolImpl.class); ThreadPoolConfig _threadPoolConfig = new ThreadPoolConfig(); Map<String, ExecutorService> _multiThreadPool = new HashMap<String, ExecutorService>(); private ThreadStateJob _threadStateJob; private static ThreadPoolImpl _instance = new ThreadPoolImpl(); public static ThreadPoolImpl getInstance() { return _instance; } @Override public void init() { initThreadPool(); startThreadStateJob(); } private void initThreadPool() { _threadPoolConfig.init(); Collection<ThreadPoolInfo> threadPoolInfoList = _threadPoolConfig.getThreadPoolConfig(); for (ThreadPoolInfo threadPoolInfo : threadPoolInfoList) { BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(threadPoolInfo.getQueueSize()); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadPoolInfo.getCoreSize(), threadPoolInfo.getMaxSize(), threadPoolInfo.getThreadKeepAliveTime(), TimeUnit.SECONDS, workQueue, new DefaultThreadFactory(threadPoolInfo.getName())); _multiThreadPool.put(threadPoolInfo.getName(), threadPool); _logger.info( String.format("initialization thread pool %s successfully", threadPoolInfo.getName()) ); } _logger.info( String.format("initialization %d thread pool successfully", threadPoolInfoList.size()) ); } /** * Job */ private void startThreadStateJob() { if (_threadPoolConfig.getThreadStateSwitch()) { _threadStateJob = new ThreadStateJob(_threadPoolConfig.getThreadStateInterval()); _threadStateJob.init(); Thread jobThread = new Thread(_threadStateJob); jobThread.setName("threadpool4j-threadstate"); jobThread.start(); _logger.info("thread state statitics job start successfully"); } } public Future<?> submit(Runnable task) { return submit(task, "default"); } public Future<?> submit(Runnable task, String threadpoolName) { ExecutorService threadPool = _multiThreadPool.get(threadpoolName); if (null == task) { throw new IllegalArgumentException("task is null"); } if (null == threadPool) { throw new IllegalArgumentException( String.format("thread pool %s not exists", threadpoolName) ); } if (_logger.isDebugEnabled()) { _logger.debug("submit a task to thread pool "+threadpoolName); } return threadPool.submit(task); } @Override public ThreadPoolInfo getThreadPoolInfo(String threadpoolName) { ThreadPoolInfo info = _threadPoolConfig.getThreadPoolConfig(threadpoolName); return info.clone(); } @Override public void destroy() { for (Entry<String, ExecutorService> entry : _multiThreadPool.entrySet()) { _logger.info("shutdown the thread pool "+entry.getKey()); entry.getValue().shutdown(); } _threadStateJob.destroy(); } }
package org.zalando.nakadi.service; import com.google.common.collect.ImmutableList; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.zalando.nakadi.domain.CursorError; import org.zalando.nakadi.domain.EventType; import org.zalando.nakadi.domain.Subscription; import org.zalando.nakadi.domain.SubscriptionCursor; import org.zalando.nakadi.exceptions.InternalNakadiException; import org.zalando.nakadi.exceptions.InvalidCursorException; import org.zalando.nakadi.exceptions.InvalidStreamIdException; import org.zalando.nakadi.exceptions.NakadiException; import org.zalando.nakadi.exceptions.NoSuchEventTypeException; import org.zalando.nakadi.exceptions.NoSuchSubscriptionException; import org.zalando.nakadi.exceptions.ServiceUnavailableException; import org.zalando.nakadi.exceptions.Try; import org.zalando.nakadi.repository.EventTypeRepository; import org.zalando.nakadi.repository.TopicRepository; import org.zalando.nakadi.repository.db.SubscriptionDbRepository; import org.zalando.nakadi.repository.zookeeper.ZooKeeperHolder; import org.zalando.nakadi.repository.zookeeper.ZooKeeperLockFactory; import org.zalando.nakadi.service.subscription.model.Partition; import org.zalando.nakadi.service.subscription.zk.ZkSubscriptionClient; import org.zalando.nakadi.service.subscription.zk.ZkSubscriptionClientFactory; import org.zalando.nakadi.service.subscription.zk.ZkSubscriptionNode; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import static java.text.MessageFormat.format; import static org.zalando.nakadi.repository.zookeeper.ZookeeperUtils.runLocked; @Component public class CursorsService { private static final Logger LOG = LoggerFactory.getLogger(CursorsService.class); private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); private static final String PATH_ZK_OFFSET = "/nakadi/subscriptions/{0}/topics/{1}/{2}/offset"; private static final String PATH_ZK_PARTITIONS = "/nakadi/subscriptions/{0}/topics/{1}"; private static final String ERROR_COMMUNICATING_WITH_ZOOKEEPER = "Error communicating with zookeeper"; private final ZooKeeperHolder zkHolder; private final TopicRepository topicRepository; private final SubscriptionDbRepository subscriptionRepository; private final EventTypeRepository eventTypeRepository; private final ZooKeeperLockFactory zkLockFactory; private final ZkSubscriptionClientFactory zkSubscriptionClientFactory; private final CursorTokenService cursorTokenService; @Autowired public CursorsService(final ZooKeeperHolder zkHolder, final TopicRepository topicRepository, final SubscriptionDbRepository subscriptionRepository, final EventTypeRepository eventTypeRepository, final ZooKeeperLockFactory zkLockFactory, final ZkSubscriptionClientFactory zkSubscriptionClientFactory, final CursorTokenService cursorTokenService) { this.zkHolder = zkHolder; this.topicRepository = topicRepository; this.subscriptionRepository = subscriptionRepository; this.eventTypeRepository = eventTypeRepository; this.zkLockFactory = zkLockFactory; this.zkSubscriptionClientFactory = zkSubscriptionClientFactory; this.cursorTokenService = cursorTokenService; } public Map<SubscriptionCursor, Boolean> commitCursors(final String streamId, final String subscriptionId, final List<SubscriptionCursor> cursors) throws NakadiException, InvalidCursorException { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); final ZkSubscriptionClient subscriptionClient = zkSubscriptionClientFactory.createZkSubscriptionClient( subscription.getId()); validateCursors(subscriptionClient, cursors, streamId); return cursors.stream().collect(Collectors.toMap(Function.identity(), Try.<SubscriptionCursor, Boolean>wrap(cursor -> processCursor(subscriptionId, cursor)) .andThen(Try::getOrThrow))); } private void validateCursors(final ZkSubscriptionClient subscriptionClient, final List<SubscriptionCursor> cursors, final String streamId) throws NakadiException { final ZkSubscriptionNode subscription = subscriptionClient.getZkSubscriptionNodeLocked(); if (!Arrays.stream(subscription.getSessions()).anyMatch(session -> session.getId().equals(streamId))) { throw new InvalidStreamIdException("Session with stream id " + streamId + " not found"); } final Map<Partition.PartitionKey, Partition> partitions = Arrays.stream(subscription.getPartitions()) .collect(Collectors.toMap(Partition::getKey, Function.identity())); final List<SubscriptionCursor> invalidCursors = cursors.stream().filter(cursor -> Try.cons(() -> eventTypeRepository.findByName(cursor.getEventType())).getO().map(eventType -> { final Partition.PartitionKey key = new Partition.PartitionKey(eventType.getTopic(), cursor.getPartition()); final Partition partition = partitions.get(key); return partition == null || !streamId.equals(partition.getSession()); }).orElseGet(() -> false)).collect(Collectors.toList()); if (!invalidCursors.isEmpty()) { throw new InvalidStreamIdException("Cursors " + invalidCursors + " cannot be committed with stream id " + streamId); } } private boolean processCursor(final String subscriptionId, final SubscriptionCursor cursor) throws InternalNakadiException, NoSuchEventTypeException, InvalidCursorException, ServiceUnavailableException, NoSuchSubscriptionException { final EventType eventType = eventTypeRepository.findByName(cursor.getEventType()); topicRepository.validateCommitCursors(eventType.getTopic(), ImmutableList.of(cursor)); return commitCursor(subscriptionId, eventType.getTopic(), cursor); } private boolean commitCursor(final String subscriptionId, final String eventType, final SubscriptionCursor cursor) throws ServiceUnavailableException, NoSuchSubscriptionException, InvalidCursorException { final String offsetPath = format(PATH_ZK_OFFSET, subscriptionId, eventType, cursor.getPartition()); try { return runLocked(() -> { final String currentOffset = new String(zkHolder.get().getData().forPath(offsetPath), CHARSET_UTF8); if (topicRepository.compareOffsets(cursor.getOffset(), currentOffset) > 0) { zkHolder.get().setData().forPath(offsetPath, cursor.getOffset().getBytes(CHARSET_UTF8)); return true; } else { return false; } }, zkLockFactory.createLock(offsetPath)); } catch (final IllegalArgumentException e) { throw new InvalidCursorException(CursorError.INVALID_FORMAT, cursor); } catch (final Exception e) { throw new ServiceUnavailableException(ERROR_COMMUNICATING_WITH_ZOOKEEPER, e); } } public List<SubscriptionCursor> getSubscriptionCursors(final String subscriptionId) throws NakadiException { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); final ImmutableList.Builder<SubscriptionCursor> cursorsListBuilder = ImmutableList.builder(); for (final String eventType : subscription.getEventTypes()) { final String topic = eventTypeRepository.findByName(eventType).getTopic(); final String partitionsPath = format(PATH_ZK_PARTITIONS, subscriptionId, topic); try { final List<String> partitions = zkHolder.get().getChildren().forPath(partitionsPath); final List<SubscriptionCursor> eventTypeCursors = partitions.stream() .map(partition -> readCursor(subscriptionId, topic, partition, eventType)) .collect(Collectors.toList()); cursorsListBuilder.addAll(eventTypeCursors); } catch (final KeeperException.NoNodeException nne) { LOG.debug(nne.getMessage(), nne); return Collections.emptyList(); } catch (final Exception e) { LOG.error(e.getMessage(), e); throw new ServiceUnavailableException(ERROR_COMMUNICATING_WITH_ZOOKEEPER, e); } } return cursorsListBuilder.build(); } private SubscriptionCursor readCursor(final String subscriptionId, final String topic, final String partition, final String eventType) throws RuntimeException { try { final String offsetPath = format(PATH_ZK_OFFSET, subscriptionId, topic, partition); final String currentOffset = new String(zkHolder.get().getData().forPath(offsetPath), CHARSET_UTF8); return new SubscriptionCursor(partition, currentOffset, eventType, cursorTokenService.generateToken()); } catch (final Exception e) { throw new RuntimeException(e); } } }
package com.android.deskclock; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View; import com.android.deskclock.stopwatch.Stopwatches; /** * TODO: Insert description here. (generated by isaackatz) */ public class CircleTimerView extends View { private int mRedColor; private int mWhiteColor; private long mIntervalTime = 0; private long mIntervalStartTime = -1; private long mMarkerTime = -1; private long mCurrentIntervalTime = 0; private long mAccumulatedTime = 0; private boolean mPaused = false; private static float mStrokeSize = 4; private static float mDiamondStrokeSize = 12; private static float mMarkerStrokeSize = 2; private final Paint mPaint = new Paint(); private final RectF mArcRect = new RectF(); private Bitmap mDiamondBitmap = null; private Resources mResources; private float mRadiusOffset; // amount to remove from radius to account for markers on circle private float mScreenDensity; // Class has 2 modes: // Timer mode - counting down. in this mode the animation is counter-clockwise and stops at 0 // Stop watch mode - counting up - in this mode the animation is clockwise and will keep the // animation until stopped. private boolean mTimerMode = false; // default is stop watch view Runnable mAnimationThread = new Runnable() { @Override public void run() { mCurrentIntervalTime = Utils.getTimeNow() - mIntervalStartTime + mAccumulatedTime; invalidate(); postDelayed(mAnimationThread, 20); } }; public CircleTimerView(Context context) { this(context, null); } public CircleTimerView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public void setIntervalTime(long t) { mIntervalTime = t; postInvalidate(); } public void setMarkerTime(long t) { mMarkerTime = t; postInvalidate(); } public void reset() { mIntervalStartTime = -1; mMarkerTime = -1; postInvalidate(); } public void startIntervalAnimation() { mIntervalStartTime = Utils.getTimeNow(); this.post(mAnimationThread); mPaused = false; } public void stopIntervalAnimation() { this.removeCallbacks(mAnimationThread); mIntervalStartTime = -1; mAccumulatedTime = 0; } public boolean isAnimating() { return (mIntervalStartTime != -1); } public void pauseIntervalAnimation() { this.removeCallbacks(mAnimationThread); mAccumulatedTime += Utils.getTimeNow() - mIntervalStartTime; mPaused = true; } public void setPassedTime(long time) { mAccumulatedTime = time; postInvalidate(); } private void init(Context c) { mResources = c.getResources(); mStrokeSize = mResources.getDimension(R.dimen.circletimer_circle_size); mDiamondStrokeSize = mResources.getDimension(R.dimen.circletimer_diamond_size); mMarkerStrokeSize = mResources.getDimension(R.dimen.circletimer_marker_size); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mWhiteColor = mResources.getColor(R.color.clock_white); mRedColor = mResources.getColor(R.color.clock_red); mDiamondBitmap = BitmapFactory.decodeResource(mResources, R.drawable.ic_diamond_red); mScreenDensity = mResources.getDisplayMetrics().density; mRadiusOffset = Math.max(mStrokeSize, Math.max(mDiamondStrokeSize, mMarkerStrokeSize)); } public void setTimerMode(boolean mode) { mTimerMode = mode; } @Override public void onDraw(Canvas canvas) { int xCenter = getWidth() / 2 + 1; int yCenter = getHeight() / 2; mPaint.setStrokeWidth(mStrokeSize); float radius = Math.min(xCenter, yCenter) - mRadiusOffset; if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { xCenter = (int) (radius + mRadiusOffset); } if (mIntervalStartTime == -1) { // just draw a complete white circle, no red arc needed mPaint.setColor(mWhiteColor); canvas.drawCircle (xCenter, yCenter, radius, mPaint); } else { //draw a combination of red and white arcs to create a circle mArcRect.top = yCenter - radius; mArcRect.bottom = yCenter + radius; mArcRect.left = xCenter - radius; mArcRect.right = xCenter + radius; float redPercent = (float)mCurrentIntervalTime / (float)mIntervalTime; // prevent timer from doing more than one full circle redPercent = (redPercent > 1 && mTimerMode) ? 1 : redPercent; float whitePercent = 1 - (redPercent > 1 ? 1 : redPercent); // draw red arc here mPaint.setColor(mRedColor); if (mTimerMode){ canvas.drawArc (mArcRect, 270, - redPercent * 360 , false, mPaint); } else { canvas.drawArc (mArcRect, 270, + redPercent * 360 , false, mPaint); } // draw white arc here mPaint.setStrokeWidth(mStrokeSize); mPaint.setColor(mWhiteColor); if (mTimerMode) { canvas.drawArc(mArcRect, 270, + whitePercent * 360, false, mPaint); } else { canvas.drawArc(mArcRect, 270 + (1 - whitePercent) * 360, whitePercent * 360, false, mPaint); } if (mMarkerTime != -1 && radius > 0 && mIntervalTime != 0) { mPaint.setStrokeWidth(mMarkerStrokeSize); float angle = (float)(mMarkerTime % mIntervalTime) / (float)mIntervalTime * 360; // draw 2dips thick marker // the formula to draw the marker 1 unit thick is: // 180 / (radius * Math.PI) // after that we have to scale it by the screen density canvas.drawArc (mArcRect, 270 + angle, mScreenDensity * (float) (360 / (radius * Math.PI)) , false, mPaint); } // draw red diamond here float diamondPercent; if (mTimerMode) { diamondPercent = 270 - redPercent * 360; } else { diamondPercent = 270 + redPercent * 360; } Matrix rotator = new Matrix(); final int width = mDiamondBitmap.getWidth(); final int height = mDiamondBitmap.getHeight(); rotator.setRotate(diamondPercent, (float) width / 2, (float) height / 2); Bitmap rotatedDiamondBitmap = Bitmap.createBitmap(mDiamondBitmap, 0, 0, width, height, rotator, true); final double diamondRadians = Math.toRadians(diamondPercent); final float diamondXPos = (float) (xCenter + radius * Math.cos(diamondRadians)) - rotatedDiamondBitmap.getWidth() / 2; final float diamondYPos = (float) (yCenter + radius * Math.sin(diamondRadians)) - rotatedDiamondBitmap.getHeight() / 2; canvas.drawBitmap(rotatedDiamondBitmap, diamondXPos, diamondYPos, mPaint); } } public static final String PREF_CTV_PAUSED = "_ctv_paused"; public static final String PREF_CTV_INTERVAL = "_ctv_interval"; public static final String PREF_CTV_INTERVAL_START = "_ctv_interval_start"; public static final String PREF_CTV_CURRENT_INTERVAL = "_ctv_current_interval"; public static final String PREF_CTV_ACCUM_TIME = "_ctv_accum_time"; public static final String PREF_CTV_TIMER_MODE = "_ctv_timer_mode"; public static final String PREF_CTV_MARKER_TIME = "_ctv_marker_time"; // Since this view is used in multiple places, use the key to save different instances public void writeToSharedPref(SharedPreferences prefs, String key) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean (key + PREF_CTV_PAUSED, mPaused); editor.putLong (key + PREF_CTV_INTERVAL, mIntervalTime); editor.putLong (key + PREF_CTV_INTERVAL_START, mIntervalStartTime); editor.putLong (key + PREF_CTV_CURRENT_INTERVAL, mCurrentIntervalTime); editor.putLong (key + PREF_CTV_ACCUM_TIME, mAccumulatedTime); editor.putLong (key + PREF_CTV_MARKER_TIME, mMarkerTime); editor.putBoolean (key + PREF_CTV_TIMER_MODE, mTimerMode); editor.apply(); } public void readFromSharedPref(SharedPreferences prefs, String key) { mPaused = prefs.getBoolean(key + PREF_CTV_PAUSED, false); mIntervalTime = prefs.getLong(key + PREF_CTV_INTERVAL, 0); mIntervalStartTime = prefs.getLong(key + PREF_CTV_INTERVAL_START, -1); mCurrentIntervalTime = prefs.getLong(key + PREF_CTV_CURRENT_INTERVAL, 0); mAccumulatedTime = prefs.getLong(key + PREF_CTV_ACCUM_TIME, 0); mMarkerTime = prefs.getLong(key + PREF_CTV_MARKER_TIME, -1); mTimerMode = prefs.getBoolean(key + PREF_CTV_TIMER_MODE, false); if (mIntervalStartTime != -1 && !mPaused) { this.post(mAnimationThread); } } public void clearSharedPref(SharedPreferences prefs, String key) { SharedPreferences.Editor editor = prefs.edit(); editor.remove (Stopwatches.PREF_START_TIME); editor.remove (Stopwatches.PREF_ACCUM_TIME); editor.remove (Stopwatches.PREF_STATE); editor.remove (key + PREF_CTV_PAUSED); editor.remove (key + PREF_CTV_INTERVAL); editor.remove (key + PREF_CTV_INTERVAL_START); editor.remove (key + PREF_CTV_CURRENT_INTERVAL); editor.remove (key + PREF_CTV_ACCUM_TIME); editor.remove (key + PREF_CTV_MARKER_TIME); editor.remove (key + PREF_CTV_TIMER_MODE); editor.apply(); } }
package repositories; import models.*; import javax.persistence.criteria.CriteriaBuilder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class FinantialStatementRepository { private Connection conn; private Client client; private Long billId; public FinantialStatementRepository(Connection conn, Client client, Long billId) { this.conn = conn; this.client = client; this.billId = billId; } public ArrayList<Purchase> getPurchases() { ArrayList<Purchase> purchases = new ArrayList<Purchase>(); StringBuilder sqlSelect = new StringBuilder(); sqlSelect.append("SELECT PURCHASES.ID, PURCHASES.PURCHASE_VALUE, ESTABLISHMENTS.NAME AS ESTABLISHMENT_NAME, ") .append("FINANTIAL_STATEMENTS.PROCESS_DATE AS PROCESS_DATE, ") .append("CATEGORIES.NAME AS CATEGORY, INSTALLMENTS.INSTALLMENT_VALUE, INSTALLMENTS.SEQUENTIAL, ") .append("COUNT(ALL_INSTALLMENTS.ID) AS AMOUNT_INSTALLMENTS ") .append("FROM INSTALLMENTS ") .append("INNER JOIN FINANTIAL_STATEMENTS ") .append("ON FINANTIAL_STATEMENTS.ID = PURCHASES.ID ") .append("INNER JOIN PURCHASES ") .append("ON INSTALLMENTS.PURCHASE_ID = PURCHASES.ID ") .append("INNER JOIN INSTALLMENTS ALL_INSTALLMENTS ") .append("ON ALL_INSTALLMENTS.PURCHASE_ID = PURCHASES.ID ") .append("INNER JOIN ESTABLISHMENTS ") .append("ON ESTABLISHMENTS.ID = PURCHASES.ESTABLISHMENT_ID ") .append("INNER JOIN CATEGORIES ") .append("ON CATEGORIES.ID = ESTABLISHMENTS.CATEGORY_ID ") .append("INNER JOIN BILLS ") .append("ON BILLS.ID = INSTALLMENTS.BILL_ID ") .append("WHERE INSTALLMENTS.BILL_ID = ? ") .append("AND BILLS.CLIENT_ID = ? ") .append("GROUP BY INSTALLMENTS.ID, INSTALLMENTS.INSTALLMENT_VALUE, PURCHASES.ID, PURCHASES.PURCHASE_VALUE, ") .append("ESTABLISHMENTS.NAME, CATEGORIES.NAME, INSTALLMENTS.SEQUENTIAL "); try { PreparedStatement ps = this.conn.prepareStatement(sqlSelect.toString()); ps.setLong(1, this.billId); ps.setLong(2, this.client.getId()); ResultSet rs = ps.executeQuery(); Purchase currentPurchase; while(rs.next()) { currentPurchase = new Purchase(); currentPurchase.setId(rs.getLong("ID")); currentPurchase.setPurchaseValue(rs.getBigDecimal("PURCHASE_VALUE")); currentPurchase.setEstablishmentName(rs.getString("ESTABLISHMENT_NAME")); currentPurchase.setCategoryName(rs.getString("CATEGORY")); currentPurchase.setInstallmentValue(rs.getBigDecimal("INSTALLMENT_VALUE")); currentPurchase.setInstallmentSequential(rs.getInt("SEQUENTIAL")); currentPurchase.setInstallmentsAmount(rs.getInt("AMOUNT_INSTALLMENTS")); currentPurchase.setProcessDate(rs.getDate("PROCESS_DATE")); purchases.add(currentPurchase); } } catch (SQLException e) { e.printStackTrace(); } return purchases; } public ArrayList<Payment> getPayments() { ArrayList<Payment> payments = new ArrayList<Payment>(); StringBuilder sqlPayments = new StringBuilder(); sqlPayments.append("SELECT PAYMENTS.ID, PAYMENTS.PAYMENT_VALUE, FINANTIAL_STATEMENTS.PROCESS_DATE ") .append("FROM PAYMENTS ") .append("INNER JOIN FINANTIAL_STATEMENTS ") .append("ON FINANTIAL_STATEMENTS.ID = PAYMENTS.ID ") .append("INNER JOIN BILLS ") .append("ON BILLS.ID = PAYMENTS.BILL_ID ") .append("WHERE BILL_ID = ? ") .append("AND BILLS.CLIENT_ID = ? ") .append("ORDER BY FINANTIAL_STATEMENTS.PROCESS_DATE DESC "); try { PreparedStatement ps = this.conn.prepareStatement(sqlPayments.toString()); ps.setLong(1, this.billId); ps.setLong(2, this.client.getId()); ResultSet rs = ps.executeQuery(); Payment currentPayment; while(rs.next()) { currentPayment = new Payment(); currentPayment.setId(rs.getLong("ID")); currentPayment.setPaymentValue(rs.getBigDecimal("PAYMENT_VALUE")); currentPayment.setProcessDate(rs.getDate("PROCESS_DATE")); payments.add(currentPayment); } } catch(SQLException e) { e.printStackTrace(); } return payments; } public ArrayList<Reversal> getReversals() { ArrayList<Reversal> reversals = new ArrayList<Reversal>(); StringBuilder sqlReversals = new StringBuilder(); sqlReversals.append("SELECT REVERSALS.ID, REVERSALS.REVERSAL_VALUE, FINANTIAL_STATEMENTS.PROCESS_DATE ") .append("FROM REVERSALS ") .append("INNER JOIN FINANTIAL_STATEMENTS ") .append("ON FINANTIAL_STATEMENTS.ID = REVERSALS.ID ") .append("INNER JOIN BILLS ") .append("ON BILLS.ID = REVERSALS.BILL_ID ") .append("WHERE BILL_ID = ? ") .append("AND BILLS.CLIENT_ID = ? ") .append("ORDER BY FINANTIAL_STATEMENTS.PROCESS_DATE DESC "); try { PreparedStatement ps = this.conn.prepareStatement(sqlReversals.toString()); ps.setLong(1, this.billId); ps.setLong(2, this.client.getId()); ResultSet rs = ps.executeQuery(); Reversal currentReversal; while(rs.next()) { currentReversal = new Reversal(); currentReversal.setId(rs.getLong("ID")); currentReversal.setReversalValue(rs.getBigDecimal("REVERSAL_VALUE")); currentReversal.setProcessDate(rs.getDate("PROCESS_DATE")); reversals.add(currentReversal); } } catch(SQLException e) { e.printStackTrace(); } return reversals; } public ArrayList<InterestRate> getInterestRates() { ArrayList<InterestRate> interestRates = new ArrayList<InterestRate>(); StringBuilder sqlInterestRates = new StringBuilder(); sqlInterestRates.append("SELECT INTEREST_RATES.ID, INTEREST_RATES.INTEREST_RATE_VALUE, FINANTIAL_STATEMENTS.PROCESS_DATE ") .append("FROM INTEREST_RATES ") .append("INNER JOIN FINANTIAL_STATEMENTS ") .append("ON FINANTIAL_STATEMENTS.ID = INTEREST_RATES.ID ") .append("INNER JOIN BILLS ") .append("ON BILLS.ID = INTEREST_RATES.BILL_ID ") .append("WHERE BILL_ID = ? ") .append("AND BILLS.CLIENT_ID = ? ") .append("ORDER BY FINANTIAL_STATEMENTS.PROCESS_DATE DESC "); try { PreparedStatement ps = this.conn.prepareStatement(sqlInterestRates.toString()); ps.setLong(1, this.billId); ps.setLong(2, this.client.getId()); ResultSet rs = ps.executeQuery(); InterestRate currentInterestRate; while(rs.next()) { currentInterestRate = new InterestRate(); currentInterestRate.setId(rs.getLong("ID")); currentInterestRate.setInterestRateValue(rs.getBigDecimal("INTEREST_RATE_VALUE")); currentInterestRate.setProcessDate(rs.getDate("PROCESS_DATE")); interestRates.add(currentInterestRate); } } catch(SQLException e) { e.printStackTrace(); } return interestRates; } }
package restapi.weatherinfo; import entities.sub_entity.WeatherInfo; import entities.sub_entity.WeatherStation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import repository.WeatherInfoRepository; import java.util.ArrayList; import java.util.List; @RestController public class WeatherInfoController { @Autowired private WeatherInfoRepository repository; /** Get weather info by station id **/ @CrossOrigin @RequestMapping(path = "/weather-station/{id}/weather-info" , method = RequestMethod.GET , produces = "application/json") public ArrayList<WeatherInfo> getWeatherInfos(@PathVariable long id){ return repository.findByWeatherStationId(id); } /** Create weather info **/ @CrossOrigin @RequestMapping(method = RequestMethod.POST , value = "/weather-station/{stationId}/weather-info/") public void addWeatherInfo(@RequestBody WeatherInfo weatherInfo , @PathVariable long stationId){ WeatherStation weatherStation = new WeatherStation(""); weatherStation.setID(stationId); weatherInfo.setWeatherStation(weatherStation); repository.save(weatherInfo); } /** Update weather info **/ @CrossOrigin @RequestMapping(method = RequestMethod.PUT , value = "/weather-info/") public void updateWeatherInfo(@RequestBody WeatherInfo weatherInfo){ repository.save(weatherInfo); } /** Find weather info by id **/ @CrossOrigin @RequestMapping(value = "/weather-info/{id}" , method = RequestMethod.GET) public ArrayList<WeatherInfo> findById(@PathVariable long id){ return repository.findById(id); } /** Delete weather info by id **/ @CrossOrigin @RequestMapping(value = "/weather-info/{id}" , method = RequestMethod.DELETE) public void delete(@PathVariable long id){ repository.delete(id); } }
package org.orbeon.oxf.xforms; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.externalcontext.ForwardExternalContextRequestWrapper; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.ProcessorUtils; import org.orbeon.oxf.resources.URLFactory; import org.orbeon.oxf.resources.handler.HTTPURLConnection; import org.orbeon.oxf.util.NetUtils; import org.orbeon.oxf.xforms.event.events.XFormsSubmitDoneEvent; import org.orbeon.oxf.xforms.processor.XFormsServer; import org.orbeon.oxf.xml.XMLUtils; import org.orbeon.oxf.xml.dom4j.LocationData; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; /** * Utilities for XForms submission processing. */ public class XFormsSubmissionUtils { /** * Perform an optimized local connection using the Servlet API instead of using a URLConnection. */ public static XFormsModelSubmission.ConnectionResult doOptimized(PipelineContext pipelineContext, ExternalContext externalContext, XFormsModelSubmission xformsModelSubmission, String method, final String action, String mediatype, boolean doReplace, byte[] serializedInstance, String queryString) { try { if (isPost(method) || isPut(method) || isGet(method) || isDelete(method)) { // Create requestAdapter depending on method final ForwardExternalContextRequestWrapper requestAdapter; final String effectiveResourceURI; { if (isPost(method) || isPut(method)) { // Simulate a POST or PUT effectiveResourceURI = action; if (XFormsServer.logger.isDebugEnabled()) XFormsServer.logger.debug("XForms - setting request body: " + new String(serializedInstance, "UTF-8")); requestAdapter = new ForwardExternalContextRequestWrapper(externalContext.getRequest(), effectiveResourceURI, method.toUpperCase(), (mediatype != null) ? mediatype : "application/xml", serializedInstance); } else { // Simulate a GET { final StringBuffer updatedActionStringBuffer = new StringBuffer(action); if (queryString != null) { if (action.indexOf('?') == -1) updatedActionStringBuffer.append('?'); else updatedActionStringBuffer.append('&'); updatedActionStringBuffer.append(queryString); } effectiveResourceURI = updatedActionStringBuffer.toString(); } requestAdapter = new ForwardExternalContextRequestWrapper(externalContext.getRequest(), effectiveResourceURI, method.toUpperCase()); } } if (XFormsServer.logger.isDebugEnabled()) XFormsServer.logger.debug("XForms - dispatching to effective resource URI: " + effectiveResourceURI); final ExternalContext.RequestDispatcher requestDispatcher = externalContext.getRequestDispatcher(action); final XFormsModelSubmission.ConnectionResult connectionResult = new XFormsModelSubmission.ConnectionResult(effectiveResourceURI) { public void close() { if (getResultInputStream() != null) { try { getResultInputStream().close(); } catch (IOException e) { throw new OXFException("Exception while closing input stream for action: " + action); } } } }; if (doReplace) { // "the event xforms-submit-done is dispatched" if (xformsModelSubmission != null) xformsModelSubmission.getContainingDocument().dispatchEvent(pipelineContext, new XFormsSubmitDoneEvent(xformsModelSubmission)); // Just forward the reply requestDispatcher.forward(requestAdapter, externalContext.getResponse()); connectionResult.dontHandleResponse = true; } else { // We must intercept the reply final ResponseAdapter responseAdapter = new ResponseAdapter(externalContext.getNativeResponse()); requestDispatcher.include(requestAdapter, responseAdapter); // Get response information that needs to be forwarded // NOTE: Here, the resultCode is not propagated from the included resource // when including Servlets. Similarly, it is not possible to obtain the // included resource's content type or headers. Because of this we should not // use an optimized submission from within a servlet. connectionResult.resultCode = responseAdapter.getResponseCode(); connectionResult.resultMediaType = ProcessorUtils.XML_CONTENT_TYPE; connectionResult.setResultInputStream(responseAdapter.getInputStream()); connectionResult.resultHeaders = new HashMap(); connectionResult.lastModified = 0; } return connectionResult; } else if (method.equals("multipart-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else if (method.equals("form-data-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else { throw new OXFException("xforms:submission: invalid submission method requested: " + method); } } catch (IOException e) { throw new OXFException(e); } } /** * Perform a connection using an URLConnection. * * @param action absolute URL or absolute path (which must include the context path) */ public static XFormsModelSubmission.ConnectionResult doRegular(ExternalContext externalContext, String method, final String action, String username, String password, String mediatype, byte[] serializedInstance, String queryString) { // Compute absolute submission URL final URL submissionURL = createAbsoluteURL(action, queryString, externalContext); return doRegular(externalContext, method, submissionURL, username, password, mediatype, serializedInstance); } public static XFormsModelSubmission.ConnectionResult doRegular(ExternalContext externalContext, String method, final URL submissionURL, String username, String password, String mediatype, byte[] serializedInstance) { // Perform submission final String scheme = submissionURL.getProtocol(); if (scheme.equals("http") || scheme.equals("https") || (isGet(method) && (scheme.equals("file") || scheme.equals("oxf")))) { // http MUST be supported // https SHOULD be supported // file SHOULD be supported try { if (XFormsServer.logger.isDebugEnabled()) XFormsServer.logger.debug("XForms - opening URL connection for: " + submissionURL.toExternalForm()); final URLConnection urlConnection = submissionURL.openConnection(); final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection) ? (HTTPURLConnection) urlConnection : null; if (isPost(method) || isPut(method) || isGet(method) || isDelete(method)) { final boolean hasRequestBody = isPost(method) || isPut(method); urlConnection.setDoInput(true); urlConnection.setDoOutput(hasRequestBody); if (httpURLConnection != null) { httpURLConnection.setRequestMethod(getHttpMethod(method)); if (username != null) { httpURLConnection.setUsername(username); if (password != null) httpURLConnection.setPassword(password); } } if (hasRequestBody) { urlConnection.setRequestProperty("Content-type", (mediatype != null) ? mediatype : "application/xml"); } // Forward cookies for session handling // TODO: The Servlet spec mandates JSESSIONID as cookie name; we should only forward this cookie if (username == null) { final String[] cookies = (String[]) externalContext.getRequest().getHeaderValuesMap().get("cookie"); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { final String cookie = cookies[i]; XFormsServer.logger.debug("XForms - forwarding cookie: " + cookie); urlConnection.setRequestProperty("Cookie", cookie); } } } // Forward authorization header // TODO: This should probably not be done automatically if (username == null) { final String authorizationHeader = (String) externalContext.getRequest().getHeaderMap().get("authorization"); if (authorizationHeader != null) { XFormsServer.logger.debug("XForms - forwarding authorization header: " + authorizationHeader); urlConnection.setRequestProperty("Authorization", authorizationHeader); } } // Write request body if needed if (hasRequestBody) { if (XFormsServer.logger.isDebugEnabled()) XFormsServer.logger.debug("XForms - setting request body: " + new String(serializedInstance, "UTF-8")); httpURLConnection.setRequestBody(serializedInstance); } urlConnection.connect(); // Create result final XFormsModelSubmission.ConnectionResult connectionResult = new XFormsModelSubmission.ConnectionResult(submissionURL.toExternalForm()) { public void close() { if (getResultInputStream() != null) { try { getResultInputStream().close(); } catch (IOException e) { throw new OXFException("Exception while closing input stream for action: " + submissionURL); } } if (httpURLConnection != null) httpURLConnection.disconnect(); } }; // Get response information that needs to be forwarded connectionResult.resultCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode() : 200; final String contentType = urlConnection.getContentType(); connectionResult.resultMediaType = (contentType != null) ? NetUtils.getContentTypeMediaType(contentType) : "application/xml"; connectionResult.resultHeaders = urlConnection.getHeaderFields(); connectionResult.lastModified = urlConnection.getLastModified(); connectionResult.setResultInputStream(urlConnection.getInputStream()); return connectionResult; } else if (method.equals("multipart-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else if (method.equals("form-data-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else { throw new OXFException("xforms:submission: invalid submission method requested: " + method); } } catch (IOException e) { throw new ValidationException(e, new LocationData(submissionURL.toExternalForm(), -1, -1)); } } else if (!isGet(method) && (scheme.equals("file") || scheme.equals("oxf"))) { // TODO: implement writing to file: and oxf: // SHOULD be supported (should probably support oxf: as well) throw new OXFException("xforms:submission: submission URL scheme not yet implemented: " + scheme); } else if (scheme.equals("mailto")) { // TODO: implement sending mail // MAY be supported throw new OXFException("xforms:submission: submission URL scheme not yet implemented: " + scheme); } else { throw new OXFException("xforms:submission: submission URL scheme not supported: " + scheme); } } /** * Create an absolute URL from an action string and a search string. * * @param action absolute URL or absolute path * @param queryString optional query string to append to the action URL * @param externalContext current ExternalContext * @return an absolute URL */ public static URL createAbsoluteURL(String action, String queryString, ExternalContext externalContext) { URL resultURL; try { final String actionString; { final StringBuffer updatedActionStringBuffer = new StringBuffer(action); if (queryString != null && queryString.length() > 0) { if (action.indexOf('?') == -1) updatedActionStringBuffer.append('?'); else updatedActionStringBuffer.append('&'); updatedActionStringBuffer.append(queryString); } actionString = updatedActionStringBuffer.toString(); } if (actionString.startsWith("/")) { // Case of path absolute final String requestURL = externalContext.getRequest().getRequestURL(); resultURL = URLFactory.createURL(requestURL, actionString); } else if (NetUtils.urlHasProtocol(actionString)) { // Case of absolute URL resultURL = URLFactory.createURL(actionString); } else { throw new OXFException("Invalid URL: " + actionString); } } catch (MalformedURLException e) { throw new OXFException("Invalid URL: " + action, e); } return resultURL; } public static boolean isGet(String method) { return method.equals("get") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "get")); } public static boolean isPost(String method) { return method.equals("post") || method.equals("urlencoded-post") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "post")); } public static boolean isPut(String method) { return method.equals("put") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "put")); } public static boolean isDelete(String method) { return method.equals("delete") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "delete")); } public static String getHttpMethod(String method) { return isGet(method) ? "GET" : isPost(method) ? "POST" : isPut(method) ? "PUT" : isDelete(method) ? "DELETE" : null; } }
package com.crossbowffs.soundcloudadaway; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Build; import de.robv.android.xposed.*; import de.robv.android.xposed.callbacks.XC_LoadPackage; import java.io.File; import java.lang.reflect.Method; public class Hook implements IXposedHookLoadPackage { private static String getPackageVersion(XC_LoadPackage.LoadPackageParam lpparam) { try { Class<?> parserCls = XposedHelpers.findClass("android.content.pm.PackageParser", lpparam.classLoader); Object parser = parserCls.newInstance(); File apkPath = new File(lpparam.appInfo.sourceDir); Object pkg = XposedHelpers.callMethod(parser, "parsePackage", apkPath, 0); String versionName = (String)XposedHelpers.getObjectField(pkg, "mVersionName"); int versionCode = XposedHelpers.getIntField(pkg, "mVersionCode"); return String.format("%s (%d)", versionName, versionCode); } catch (Throwable e) { return null; } } private static void printInitInfo(XC_LoadPackage.LoadPackageParam lpparam) { Xlog.i("SoundCloud AdAway initializing..."); Xlog.i("Phone manufacturer: %s", Build.MANUFACTURER); Xlog.i("Phone model: %s", Build.MODEL); Xlog.i("Android version: %s", Build.VERSION.RELEASE); Xlog.i("Xposed bridge version: %d", XposedBridge.XPOSED_BRIDGE_VERSION); Xlog.i("SoundCloud APK version: %s", getPackageVersion(lpparam)); Xlog.i("SoundCloud AdAway version: %s (%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); } private static void findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) { Xlog.i("Hooking %s#%s()", className, methodName); try { XposedHelpers.findAndHookMethod(className, classLoader, methodName, parameterTypesAndCallback); } catch (Throwable e) { Xlog.e("Failed to hook %s#%s()", className, methodName, e); } } private static boolean isStreamAd(Object streamItem) { return (Boolean)XposedHelpers.callMethod(streamItem, "isAd") || (Boolean)XposedHelpers.callMethod(streamItem, "isPromoted") || (Boolean)XposedHelpers.callMethod(streamItem, "isUpsell"); } private static void blockPlayQueueAds(XC_LoadPackage.LoadPackageParam lpparam) { // Block audio and video ads during playback findAndHookMethod( "com.soundcloud.android.ads.AdsOperations", lpparam.classLoader, "insertAudioAd", "com.soundcloud.android.playback.TrackQueueItem", "com.soundcloud.android.ads.ApiAudioAd", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { Xlog.i("Blocked audio ad"); param.setResult(null); } }); findAndHookMethod( "com.soundcloud.android.ads.AdsOperations", lpparam.classLoader, "insertVideoAd", "com.soundcloud.android.playback.TrackQueueItem", "com.soundcloud.android.ads.ApiVideoAd", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { Xlog.i("Blocked video ad"); param.setResult(null); } }); } private static void blockStreamAds(XC_LoadPackage.LoadPackageParam lpparam) { // Block stream ads (e.g. promoted tracks, "install this app") findAndHookMethod( "com.soundcloud.android.stream.StreamAdapter", lpparam.classLoader, "addItem", int.class, "com.soundcloud.android.stream.StreamItem", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (isStreamAd(param.args[1])) { Xlog.i("Blocked stream ad"); param.setResult(null); } } }); findAndHookMethod( "com.soundcloud.android.stream.StreamAdapter", lpparam.classLoader, "addItem", "com.soundcloud.android.stream.StreamItem", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (isStreamAd(param.args[0])) { Xlog.i("Blocked stream ad"); param.setResult(null); } } }); } private static void blockAppboyPushNotifications(XC_LoadPackage.LoadPackageParam lpparam) { // Block Appboy push notifications (no, the notification settings // aren't enough) findAndHookMethod( "com.appboy.AppboyGcmReceiver", lpparam.classLoader, "onReceive", Context.class, Intent.class, XC_MethodReplacement.DO_NOTHING); } private static void blockAppboyInAppMessages(XC_LoadPackage.LoadPackageParam lpparam) { // Block Appboy in-app messages. An example is the "upgrade to // SoundCloud Go" popup that gets displayed when the app starts. findAndHookMethod( "com.soundcloud.android.analytics.appboy.RealAppboyWrapper", lpparam.classLoader, "registerInAppMessageManager", Activity.class, XC_MethodReplacement.DO_NOTHING); findAndHookMethod( "com.soundcloud.android.analytics.appboy.RealAppboyWrapper", lpparam.classLoader, "unregisterInAppMessageManager", Activity.class, XC_MethodReplacement.DO_NOTHING); } private static void enableOfflineContent(XC_LoadPackage.LoadPackageParam lpparam) { // Enables downloading music for offline listening findAndHookMethod( "com.soundcloud.android.configuration.FeatureOperations", lpparam.classLoader, "isOfflineContentEnabled", XC_MethodReplacement.returnConstant(true)); } private static void enableDeveloperMode(XC_LoadPackage.LoadPackageParam lpparam) { // This gives you a cool developer menu if you slide from the right edge. // It's not actually useful for anything though (no, you can't upgrade // to Go for free, I've tried) // The return type is RxJava Observable<Boolean>, which is ProGuarded. // We can reliably find the return type from the method itself. Object observableTrue; try { Class<?> featureOpsCls = XposedHelpers.findClass("com.soundcloud.android.configuration.FeatureOperations", lpparam.classLoader); Method devMenuEnabledMethod = XposedHelpers.findMethodExact(featureOpsCls, "developmentMenuEnabled"); Class<?> observableCls = devMenuEnabledMethod.getReturnType(); observableTrue = XposedHelpers.callStaticMethod(observableCls, "just", new Class<?>[] {Object.class}, true); } catch (Throwable e) { Xlog.e("Failed to create Observable<Boolean>(true) object", e); return; } findAndHookMethod( "com.soundcloud.android.configuration.FeatureOperations", lpparam.classLoader, "developmentMenuEnabled", XC_MethodReplacement.returnConstant(observableTrue)); findAndHookMethod( "com.soundcloud.android.configuration.FeatureOperations", lpparam.classLoader, "isDevelopmentMenuEnabled", XC_MethodReplacement.returnConstant(true)); } @Override public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable { if (!"com.soundcloud.android".equals(lpparam.packageName)) { return; } printInitInfo(lpparam); blockPlayQueueAds(lpparam); blockStreamAds(lpparam); blockAppboyPushNotifications(lpparam); blockAppboyInAppMessages(lpparam); enableOfflineContent(lpparam); // enableDeveloperMode(lpparam); Xlog.i("SoundCloud AdAway initialization complete!"); } }
package stream.flarebot.flarebot.util; import net.dv8tion.jda.core.EmbedBuilder; import okhttp3.Response; import okhttp3.ResponseBody; import org.json.JSONObject; import stream.flarebot.flarebot.FlareBot; import java.io.IOException; import java.util.Arrays; public class GitHubUtils { public static EmbedBuilder getEmbedForPR(String prNum) { JSONObject obj; try { Response res = WebUtils.get("https://api.github.com/repos/FlareBot/FlareBot/pulls/" + prNum); ResponseBody body = res.body(); if (body != null) { obj = new JSONObject(body.string()); body.close(); } else { res.close(); FlareBot.LOGGER.error("GitHub returned an empty response - Code " + res.code()); return null; } res.close(); } catch (IOException e) { FlareBot.LOGGER.error("Error getting the PR info! " + e.getMessage(), e); return null; } String body = obj.getString("body"); String[] array = body.split("\r\n\r\n"); String title = array[0].split("\r\n")[0].replace(" String description = array[0].split("\r\n")[1]; EmbedBuilder embed = new EmbedBuilder(); embed.setTitle(title, null); embed.setDescription(description); array = Arrays.copyOfRange(array, 1, array.length); for (String anArray : array) { String value = anArray.replaceAll("\n\\* ", "\n\u2022 "); String header = value.replace("## ", "").substring(0, value.indexOf("\n") - 4).replace("\n", ""); value = value.replace("## " + header, ""); if (value.length() > 1024) { embed.addField(header, value.substring(0, value.substring(0, 1024).lastIndexOf("\n")), false); value = value.substring(value.substring(0, 1024).lastIndexOf("\n") + 1); header += " - Continued"; } embed.addField(header, value, false); } return embed; } }
package uk.co.qmunity.lib.part.compat.fmp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import uk.co.qmunity.lib.QLModInfo; import uk.co.qmunity.lib.QmunityLib; import uk.co.qmunity.lib.client.render.RenderHelper; import uk.co.qmunity.lib.client.render.RenderMultipart; import uk.co.qmunity.lib.part.IMicroblock; import uk.co.qmunity.lib.part.IPart; import uk.co.qmunity.lib.part.IPartCollidable; import uk.co.qmunity.lib.part.IPartFace; import uk.co.qmunity.lib.part.IPartInteractable; import uk.co.qmunity.lib.part.IPartOccluding; import uk.co.qmunity.lib.part.IPartRedstone; import uk.co.qmunity.lib.part.IPartRenderable; import uk.co.qmunity.lib.part.IPartSelectable; import uk.co.qmunity.lib.part.IPartSolid; import uk.co.qmunity.lib.part.IPartTicking; import uk.co.qmunity.lib.part.IPartUpdateListener; import uk.co.qmunity.lib.part.ITilePartHolder; import uk.co.qmunity.lib.part.PartRegistry; import uk.co.qmunity.lib.raytrace.QMovingObjectPosition; import uk.co.qmunity.lib.raytrace.RayTracer; import uk.co.qmunity.lib.vec.Vec3d; import uk.co.qmunity.lib.vec.Vec3dCube; import uk.co.qmunity.lib.vec.Vec3i; import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; import codechicken.lib.raytracer.ExtendedMOP; import codechicken.lib.raytracer.IndexedCuboid6; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import codechicken.microblock.CommonMicroblock; import codechicken.multipart.INeighborTileChange; import codechicken.multipart.IRedstonePart; import codechicken.multipart.NormalOcclusionTest; import codechicken.multipart.NormallyOccludedPart; import codechicken.multipart.TMultiPart; import codechicken.multipart.TNormalOcclusion; public class FMPPart extends TMultiPart implements ITilePartHolder, TNormalOcclusion, IRedstonePart, INeighborTileChange, IFMPPart { private Map<String, IPart> parts = new HashMap<String, IPart>(); private List<String> removed = new ArrayList<String>(); private List<IPart> added = new ArrayList<IPart>(); public FMPPart() { } public FMPPart(Map<String, IPart> parts) { this.parts = parts; for (String s : parts.keySet()) parts.get(s).setParent(this); } @Override public String getType() { return QLModInfo.MODID + "_multipart"; } @Override public List<IPart> getParts() { List<IPart> parts = new ArrayList<IPart>(); for (String s : this.parts.keySet()) { IPart p = this.parts.get(s); if (p.getParent() != null && !removed.contains(s)) parts.add(p); } return parts; } @Override public Iterable<IndexedCuboid6> getSubParts() { List<IndexedCuboid6> cubes = new ArrayList<IndexedCuboid6>(); for (IPart p : getParts()) if (p instanceof IPartSelectable) for (Vec3dCube c : ((IPartSelectable) p).getSelectionBoxes()) cubes.add(new IndexedCuboid6(0, new Cuboid6(c.toAABB()))); if (cubes.size() == 0) cubes.add(new IndexedCuboid6(0, new Cuboid6(0, 0, 0, 1, 1, 1))); return cubes; } @Override public ExtendedMOP collisionRayTrace(Vec3 start, Vec3 end) { QMovingObjectPosition qmop = rayTrace(new Vec3d(start), new Vec3d(end)); if (qmop == null) return null; new Cuboid6(qmop.getCube().toAABB()).setBlockBounds(tile().getBlockType()); Vec3 v = qmop.hitVec.subtract(start); return new ExtendedMOP(qmop, 0, v.xCoord * v.xCoord + v.yCoord * v.yCoord + v.zCoord * v.zCoord); } private boolean firstTick = true; @Override public void update() { for (IPart p : getParts()) { if (firstTick) { for (IPart p_ : added) if (p_ == p) ((IPartUpdateListener) p).onAdded(); if (p instanceof IPartUpdateListener) { ((IPartUpdateListener) p).onLoaded(); } firstTick = false; } if (p instanceof IPartTicking) ((IPartTicking) p).update(); } if (!world().isRemote) sendDescUpdate(); } @Override public void save(NBTTagCompound tag) { super.save(tag); NBTTagList l = new NBTTagList(); writeParts(l, false); tag.setTag("parts", l); } @Override public void load(NBTTagCompound tag) { super.load(tag); NBTTagList l = tag.getTagList("parts", new NBTTagCompound().getId()); readParts(l, true, false); } @Override public void writeDesc(MCDataOutput packet) { super.writeDesc(packet); NBTTagCompound tag = new NBTTagCompound(); NBTTagList l = new NBTTagList(); writeParts(l, true); tag.setTag("parts", l); packet.writeNBTTagCompound(tag); } @Override public void readDesc(MCDataInput packet) { super.readDesc(packet); NBTTagList l = packet.readNBTTagCompound().getTagList("parts", new NBTTagCompound().getId()); readParts(l, true, true); } private void writeParts(NBTTagList l, boolean update) { for (IPart p : getParts()) { String id = getIdentifier(p); NBTTagCompound tag = new NBTTagCompound(); tag.setString("id", id); tag.setString("type", p.getType()); NBTTagCompound data = new NBTTagCompound(); if (update) p.writeUpdateToNBT(data); else p.writeToNBT(data); tag.setTag("data", data); l.appendTag(tag); } } private void readParts(NBTTagList l, boolean update, boolean client) { for (int i = 0; i < l.tagCount(); i++) { NBTTagCompound tag = l.getCompoundTagAt(i); String id = tag.getString("id"); IPart p = getPart(id); if (p == null) { p = PartRegistry.createPart(tag.getString("type"), client); p.setParent(this); parts.put(id, p); } NBTTagCompound data = tag.getCompoundTag("data"); if (update) p.readUpdateFromNBT(data); else p.readFromNBT(data); } } // Part holder methods @Override public World getWorld() { return world(); } @Override public int getX() { return x(); } @Override public int getY() { return y(); } @Override public int getZ() { return z(); } @Override public void addPart(IPart part) { parts.put(genIdentifier(), part); part.setParent(this); if (part instanceof IPartUpdateListener) if (tile() != null) ((IPartUpdateListener) part).onAdded(); else added.add(part); for (IPart p : getParts()) if (p != part && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onPartChanged(part); } @Override public boolean removePart(IPart part) { if (part == null) return false; if (!parts.containsValue(part)) return false; if (removed.contains(part)) return false; if (part instanceof IPartUpdateListener) ((IPartUpdateListener) part).onRemoved(); for (IPart p : getParts()) if (p != part && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onPartChanged(part); String id = getIdentifier(part); removed.add(id); parts.remove(id); part.setParent(null); return true; } private String genIdentifier() { String s = null; do { s = UUID.randomUUID().toString(); } while (parts.containsKey(s)); return s; } private String getIdentifier(IPart part) { for (String s : parts.keySet()) if (parts.get(s).equals(part)) return s; return null; } private IPart getPart(String id) { for (String s : parts.keySet()) if (s.equals(id)) return parts.get(s); return null; } @Override public boolean canAddPart(IPart part) { if (tile() == null) return true; if (part instanceof IPartCollidable) { List<Vec3dCube> cubes = new ArrayList<Vec3dCube>(); ((IPartCollidable) part).addCollisionBoxesToList(cubes, null); for (Vec3dCube c : cubes) if (!getWorld().checkNoEntityCollision(c.clone().add(getX(), getY(), getZ()).toAABB())) return false; } if (part instanceof IPartOccluding) { for (Vec3dCube b : ((IPartOccluding) part).getOcclusionBoxes()) { NormallyOccludedPart nop = new NormallyOccludedPart(new Cuboid6(b.toAABB())); for (TMultiPart p : tile().jPartList()) if (!p.occlusionTest(nop)) return false; } } return true; } @Override public QMovingObjectPosition rayTrace(Vec3d start, Vec3d end) { QMovingObjectPosition closest = null; double dist = Double.MAX_VALUE; for (IPart p : getParts()) { if (p instanceof IPartSelectable) { QMovingObjectPosition mop = ((IPartSelectable) p).rayTrace(start, end); if (mop == null) continue; double d = start.distanceTo(new Vec3d(mop.hitVec)); if (d < dist) { closest = mop; dist = d; } } } return closest; } @Override public boolean renderStatic(Vector3 pos, int pass) { boolean did = false; RenderBlocks renderer = RenderBlocks.getInstance(); RenderHelper.instance.setRenderCoords(getWorld(), (int) pos.x, (int) pos.y, (int) pos.z); renderer.blockAccess = getWorld(); for (IPart p : getParts()) if (p.getParent() != null && p instanceof IPartRenderable) if (((IPartRenderable) p).shouldRenderOnPass(pass)) if (((IPartRenderable) p).renderStatic(new Vec3i((int) pos.x, (int) pos.y, (int) pos.z), RenderHelper.instance, renderer, pass)) did = true; renderer.blockAccess = null; RenderHelper.instance.reset(); return did; } @Override public void renderDynamic(Vector3 pos, float frame, int pass) { GL11.glPushMatrix(); { GL11.glTranslated(pos.x, pos.y, pos.z); for (IPart p : getParts()) { if (p.getParent() != null && p instanceof IPartRenderable) { GL11.glPushMatrix(); if (((IPartRenderable) p).shouldRenderOnPass(pass)) ((IPartRenderable) p).renderDynamic(new Vec3d(0, 0, 0), frame, pass); GL11.glPopMatrix(); } } } GL11.glPopMatrix(); } @Override public void drawBreaking(RenderBlocks renderBlocks) { QMovingObjectPosition mop = rayTrace(RayTracer.instance().getStartVector(Minecraft.getMinecraft().thePlayer), RayTracer.instance() .getEndVector(Minecraft.getMinecraft().thePlayer)); if (mop == null || mop.getPart() == null) return; RenderHelper.instance.setRenderCoords(getWorld(), getX(), getY(), getZ()); RenderMultipart.renderBreaking(getWorld(), getX(), getY(), getZ(), renderBlocks, mop); RenderHelper.instance.reset(); } @Override public void addCollisionBoxesToList(List<Vec3dCube> l, AxisAlignedBB bounds, Entity entity) { List<Vec3dCube> boxes = new ArrayList<Vec3dCube>(); for (IPart p : getParts()) { if (p instanceof IPartCollidable) { List<Vec3dCube> boxes_ = new ArrayList<Vec3dCube>(); ((IPartCollidable) p).addCollisionBoxesToList(boxes_, entity); for (Vec3dCube c : boxes_) { Vec3dCube cube = c.clone(); cube.add(getX(), getY(), getZ()); cube.setPart(p); boxes.add(cube); } boxes_.clear(); } } for (Vec3dCube c : boxes) { if (c.toAABB().intersectsWith(bounds)) l.add(c); } } @Override public Iterable<Cuboid6> getCollisionBoxes() { List<Cuboid6> cubes = new ArrayList<Cuboid6>(); List<Vec3dCube> boxes = new ArrayList<Vec3dCube>(); addCollisionBoxesToList(boxes, AxisAlignedBB.getBoundingBox(x(), y(), z(), x() + 1, y() + 1, z() + 1), null); for (Vec3dCube c : boxes) cubes.add(new Cuboid6(c.clone().add(-x(), -y(), -z()).toAABB())); return cubes; } @Override public void onNeighborChanged() { super.onNeighborChanged(); onUpdate(); for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onNeighborBlockChange(); } @Override public void onPartChanged(TMultiPart part) { super.onPartChanged(part); onUpdate(); for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onPartChanged(null); } private void onUpdate() { for (IPart p : getParts()) if (p != null && p instanceof IPartFace) if (!((IPartFace) p).canStay()) p.breakAndDrop(false); } @Override public Iterable<ItemStack> getDrops() { List<ItemStack> l = new ArrayList<ItemStack>(); for (IPart p : getParts()) { List<ItemStack> d = p.getDrops(); if (d != null) l.addAll(d); } return l; } @Override public Iterable<Cuboid6> getOcclusionBoxes() { List<Cuboid6> cubes = new ArrayList<Cuboid6>(); for (IPart p : getParts()) if (p != null && p instanceof IPartOccluding) for (Vec3dCube c : ((IPartOccluding) p).getOcclusionBoxes()) cubes.add(new IndexedCuboid6(0, new Cuboid6(c.toAABB()))); return cubes; } @Override public boolean occlusionTest(TMultiPart npart) { return NormalOcclusionTest.apply(this, npart); } @Override public boolean canConnectRedstone(int side) { for (IPart p : getParts()) if (p instanceof IPartRedstone) if (((IPartRedstone) p).canConnectRedstone(ForgeDirection.getOrientation(side))) return true; return false; } @Override public int strongPowerLevel(int side) { int max = 0; for (IPart p : getParts()) if (p instanceof IPartRedstone) max = Math.max(max, ((IPartRedstone) p).getStrongPower(ForgeDirection.getOrientation(side))); return max; } @Override public int weakPowerLevel(int side) { int max = 0; for (IPart p : getParts()) { if (p instanceof IPartRedstone) { max = Math.max(max, ((IPartRedstone) p).getWeakPower(ForgeDirection.getOrientation(side))); } } return max; } @Override public void onNeighborTileChanged(int arg0, boolean arg1) { for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onNeighborTileChange(); } @Override public boolean weakTileChanges() { return true; } @Override public void onAdded() { for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onAdded(); } @Override public void onRemoved() { for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onRemoved(); } @Override public void onChunkLoad() { super.onChunkLoad(); for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onLoaded(); } @Override public void onChunkUnload() { super.onChunkUnload(); for (IPart p : getParts()) if (p != null && p instanceof IPartUpdateListener) ((IPartUpdateListener) p).onUnloaded(); } @Override public ItemStack pickItem(MovingObjectPosition hit) { QMovingObjectPosition mop = rayTrace(RayTracer.instance().getStartVector(QmunityLib.proxy.getPlayer()), RayTracer.instance() .getEndVector(QmunityLib.proxy.getPlayer())); if (mop == null) return null; return mop.getPart().getItem(); } @Override public void harvest(MovingObjectPosition hit, EntityPlayer player) { if (world().isRemote) { return; } QMovingObjectPosition mop = rayTrace(RayTracer.instance().getStartVector(player), RayTracer.instance().getEndVector(player)); if (mop != null) { mop.getPart().breakAndDrop(player.capabilities.isCreativeMode); if (getParts().size() == 0) super.harvest(hit, player); } } @Override public void click(EntityPlayer player, MovingObjectPosition hit, ItemStack item) { QMovingObjectPosition mop = rayTrace(RayTracer.instance().getStartVector(player), RayTracer.instance().getEndVector(player)); if (mop != null) if (mop.getPart() instanceof IPartInteractable) ((IPartInteractable) mop.getPart()).onClicked(player, mop, item); } @Override public boolean activate(EntityPlayer player, MovingObjectPosition hit, ItemStack item) { QMovingObjectPosition mop = rayTrace(RayTracer.instance().getStartVector(player), RayTracer.instance().getEndVector(player)); if (mop != null) if (mop.getPart() instanceof IPartInteractable) return ((IPartInteractable) mop.getPart()).onActivated(player, mop, item); return false; } @Override public Map<String, IPart> getPartMap() { return parts; } @Override public List<IMicroblock> getMicroblocks() { List<IMicroblock> microblocks = new ArrayList<IMicroblock>(); for (TMultiPart p : tile().jPartList()) if (p instanceof CommonMicroblock) microblocks.add(new FMPMicroblock((CommonMicroblock) p)); return microblocks; } public boolean isSolid(ForgeDirection face) { for (IPart p : getParts()) if (p instanceof IPartSolid && ((IPartSolid) p).isSideSolid(face)) return true; return true; } @Override public boolean isSolid(int side) { return isSolid(ForgeDirection.getOrientation(side)); } @Override public float getStrength(MovingObjectPosition hit, EntityPlayer player) { QMovingObjectPosition mop = rayTrace(RayTracer.instance().getStartVector(player), RayTracer.instance().getEndVector(player)); if (mop != null && mop.getPart() != null) return (float) (30 * mop.getPart().getHardness(player, mop)); return 30; } } interface IFMPPart { public boolean isSolid(int side); }
package vg.civcraft.mc.citadel; import java.util.Objects; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.type.Bed; import org.bukkit.block.data.type.Chest; import org.bukkit.block.data.type.CoralWallFan; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import vg.civcraft.mc.citadel.events.ReinforcementCreationEvent; import vg.civcraft.mc.citadel.events.ReinforcementDestructionEvent; import vg.civcraft.mc.citadel.model.Reinforcement; import vg.civcraft.mc.citadel.reinforcementtypes.ReinforcementType; import vg.civcraft.mc.civmodcore.api.BlockAPI; import vg.civcraft.mc.namelayer.group.Group; public final class ReinforcementLogic { private ReinforcementLogic() { } /** * Inserts a new reinforcements into the cache, queues it for persistence and * plays particle effects for creation * * @param rein Reinforcement just created */ public static void createReinforcement(Reinforcement rein) { Citadel.getInstance().getReinforcementManager().putReinforcement(rein); if (rein.getType().getCreationEffect() != null) { rein.getType().getCreationEffect().playEffect(rein); } } public static Reinforcement callReinforcementCreationEvent(Player player, Block block, ReinforcementType type, Group group) { Reinforcement rein = new Reinforcement(block.getLocation(), type, group); ReinforcementCreationEvent event = new ReinforcementCreationEvent(player, rein); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return null; } return rein; } public static void damageReinforcement(Reinforcement rein, float damage, Entity source) { float futureHealth = rein.getHealth() - damage; if (futureHealth <= 0) { ReinforcementDestructionEvent event = new ReinforcementDestructionEvent(rein, damage, source); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } } futureHealth = Math.min(futureHealth, rein.getType().getHealth()); rein.setHealth(futureHealth); if (rein.isBroken()) { if (rein.getType().getDestructionEffect() != null) { rein.getType().getDestructionEffect().playEffect(rein); } } else { if (rein.getType().getDamageEffect() != null) { rein.getType().getDamageEffect().playEffect(rein); } } } public static float getDamageApplied(Reinforcement reinforcement) { float damageAmount = 1.0F; if (!reinforcement.isMature()) { double timeExisted = System.currentTimeMillis() - reinforcement.getCreationTime(); double progress = timeExisted / reinforcement.getType().getMaturationTime(); damageAmount /= progress; damageAmount *= reinforcement.getType().getMaturationScale(); } damageAmount *= getDecayDamage(reinforcement); return damageAmount; } public static double getDecayDamage(Reinforcement reinforcement) { if (reinforcement.getGroup() != null) { long lastRefresh = reinforcement.getGroup().getActivityTimeStamp(); return reinforcement.getType().getDecayDamageMultipler(lastRefresh); } else { return reinforcement.getType().getDeletedGroupMultiplier(); } } public static Reinforcement getReinforcementAt(Location location) { return Citadel.getInstance().getReinforcementManager().getReinforcement(location); } public static Reinforcement getReinforcementProtecting(Block block) { if (!BlockAPI.isValidBlock(block)) { return null; } Reinforcement reinforcement = getReinforcementAt(block.getLocation()); if (reinforcement != null) { return reinforcement; } switch (block.getType()) { // Chests are awkward since you can place both sides of a double chest // independently, which isn't true for // beds, plants, or doors, so this needs to be accounted for and // "getResponsibleBlock()" isn't appropriate // for the following logic: that both sides protect each other; that if either // block is reinforced, then // the chest as a whole remains protected. case CHEST: case TRAPPED_CHEST: { Chest chest = (Chest) block.getBlockData(); BlockFace facing = chest.getFacing(); switch (chest.getType()) { case LEFT: { BlockFace face = BlockAPI.turnClockwise(facing); return getReinforcementAt(block.getLocation().add(face.getDirection())); } case RIGHT: { BlockFace face = BlockAPI.turnAntiClockwise(facing); return getReinforcementAt(block.getLocation().add(face.getDirection())); } default: { return null; } } } default: { Block responsible = getResponsibleBlock(block); if (Objects.equals(block, responsible)) { return null; } return getReinforcementAt(responsible.getLocation()); } } } /** * Some blocks, crops in particular, can not be reinforced but instead have * their reinforcement behavior tied to a source block. This method will get * that source block, which may be the given block itself. It does not look at * reinforcement data at all, it merely applies logic based on block type and * physics checks * * @param block Block to get responsible block for * @return Block which reinforcement would protect the given block */ public static Block getResponsibleBlock(Block block) { // Do not put [double] chests in here. switch (block.getType()) { case DANDELION: case POPPY: case BLUE_ORCHID: case ALLIUM: case AZURE_BLUET: case ORANGE_TULIP: case RED_TULIP: case PINK_TULIP: case WHITE_TULIP: case OXEYE_DAISY: case ACACIA_SAPLING: case BIRCH_SAPLING: case DARK_OAK_SAPLING: case JUNGLE_SAPLING: case OAK_SAPLING: case SPRUCE_SAPLING: case WARPED_FUNGUS: case CRIMSON_FUNGUS: case BAMBOO_SAPLING: case TWISTING_VINES: case WHEAT: case CARROTS: case POTATOES: case BEETROOTS: case SWEET_BERRY_BUSH: case MELON_STEM: case PUMPKIN_STEM: case ATTACHED_MELON_STEM: case ATTACHED_PUMPKIN_STEM: case WARPED_ROOTS: case CRIMSON_ROOTS: case NETHER_SPROUTS: case WITHER_ROSE: case LILY_OF_THE_VALLEY: case CORNFLOWER: case SEA_PICKLE: case FERN: case KELP: case GRASS: case SEAGRASS: case TUBE_CORAL: case TUBE_CORAL_FAN: case BRAIN_CORAL: case BRAIN_CORAL_FAN: case BUBBLE_CORAL: case BUBBLE_CORAL_FAN: case FIRE_CORAL: case FIRE_CORAL_FAN: case HORN_CORAL: case HORN_CORAL_FAN: case DEAD_TUBE_CORAL: case DEAD_TUBE_CORAL_FAN: case DEAD_BRAIN_CORAL: case DEAD_BRAIN_CORAL_FAN: case DEAD_BUBBLE_CORAL: case DEAD_BUBBLE_CORAL_FAN: case DEAD_FIRE_CORAL: case DEAD_FIRE_CORAL_FAN: case DEAD_HORN_CORAL: case DEAD_HORN_CORAL_FAN: case NETHER_WART_BLOCK: { return block.getRelative(BlockFace.DOWN); } case SUGAR_CANE: case BAMBOO: case ROSE_BUSH: case TWISTING_VINES_PLANT: case CACTUS: case SUNFLOWER: case LILAC: case TALL_GRASS: case LARGE_FERN: case TALL_SEAGRASS: case KELP_PLANT: case PEONY: { // scan downwards for first different block Block below = block.getRelative(BlockFace.DOWN); while (below.getType() == block.getType()) { below = below.getRelative(BlockFace.DOWN); } return below; } case ACACIA_DOOR: case BIRCH_DOOR: case DARK_OAK_DOOR: case IRON_DOOR: case SPRUCE_DOOR: case JUNGLE_DOOR: case WARPED_DOOR: case CRIMSON_DOOR: case OAK_DOOR: { if (block.getRelative(BlockFace.UP).getType() != block.getType()) { // block is upper half of a door return block.getRelative(BlockFace.DOWN); } return block; } case BLACK_BED: case BLUE_BED: case BROWN_BED: case CYAN_BED: case GRAY_BED: case GREEN_BED: case MAGENTA_BED: case LIME_BED: case ORANGE_BED: case PURPLE_BED: case PINK_BED: case WHITE_BED: case LIGHT_GRAY_BED: case LIGHT_BLUE_BED: case RED_BED: case YELLOW_BED: { Bed bed = (Bed) block.getBlockData(); if (bed.getPart() == Bed.Part.HEAD) { return block.getRelative(bed.getFacing().getOppositeFace()); } return block; } case TUBE_CORAL_WALL_FAN: case BRAIN_CORAL_WALL_FAN: case BUBBLE_CORAL_WALL_FAN: case FIRE_CORAL_WALL_FAN: case HORN_CORAL_WALL_FAN: case DEAD_TUBE_CORAL_WALL_FAN: case DEAD_BRAIN_CORAL_WALL_FAN: case DEAD_BUBBLE_CORAL_WALL_FAN: case DEAD_FIRE_CORAL_WALL_FAN: case DEAD_HORN_CORAL_WALL_FAN: { CoralWallFan cwf = (CoralWallFan) block.getBlockData(); return block.getRelative(cwf.getFacing().getOppositeFace()); } case WEEPING_VINES: { block.getRelative(BlockFace.UP); } case WEEPING_VINES_PLANT: { // scan upwards Block above = block.getRelative(BlockFace.UP); while (above.getType() == block.getType()) { above = above.getRelative(BlockFace.UP); } return above; } default: { return block; } } } /** * Checks if at the given block is a container, which is not insecure and which * the player can not access due to missing perms * * @param player the player attempting to access stuff * @param block Block to check for * @return True if the player can not do something like placing an adjacent * chest or comparator, false otherwise */ public static boolean isPreventingBlockAccess(Player player, Block block) { if (block == null) { return false; } if (block.getState() instanceof InventoryHolder) { Reinforcement rein = getReinforcementProtecting(block); if (rein == null || rein.isInsecure()) { return false; } return !rein.hasPermission(player, CitadelPermissionHandler.getChests()); } return false; } }
package com.haxademic.app.timelapse; import java.util.ArrayList; import processing.core.PApplet; import processing.core.PImage; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.util.DrawUtil; import com.haxademic.core.system.FileUtil; import com.lowagie.text.pdf.draw.DrawInterface; public class TimeLapse extends PAppletHax { private static final long serialVersionUID = 1L; /** * Auto-initialization of the main class. * @param args */ public static void main(String args[]) { PApplet.main(new String[] { "--hide-stop", "--bgcolor=000000", "com.haxademic.app.timelapse.TimeLapse" }); } /** * Image sequence */ protected ArrayList<String> _images; /** * Image path */ protected String _imageDir; /** * Image type */ protected String _imageType; /** * Image sequence index */ protected int _imageIndex; /** * Frames per image */ protected int _fpi; public void setup() { _customPropsFile = FileUtil.getHaxademicDataPath() + "properties/timelapse.properties"; super.setup(); initRender(); } public void initRender() { _imageDir = _appConfig.getString( "image_dir", "" ); _imageType = _appConfig.getString( "image_type", ".jpg" ); _images = FileUtil.getFilesInDirOfType( FileUtil.getHaxademicDataPath() + _imageDir, _imageType ); _imageIndex = 0; _fpi = _appConfig.getInt( "frames_per_image", 2 ); } public void drawApp() { p.background(0); DrawUtil.setColorForPImage(p); DrawUtil.setPImageAlpha(p, (p.frameCount % 2 == 1) ? 0.999f : 1 ); // stupid hack b/c UMovieMaker doesn't save the exact same frame twice in a row. // load and display current image if( _imageIndex < _images.size() ) { PImage img = p.loadImage( _imageDir + _images.get( _imageIndex ) ); p.image( img, 0, 0 ); } // step to next image if( p.frameCount > 0 && p.frameCount % _fpi == 0 ) _imageIndex++; // stop when done if( _imageIndex == _images.size() ) { _renderer.stop(); } else if( _imageIndex == _images.size() + 1 ) { p.exit(); } } }
package za.redbridge.experiment.MMNEAT; import org.encog.ml.CalculateScore; import org.encog.ml.ea.opp.CompoundOperator; import org.encog.ml.ea.opp.selection.TruncationSelection; import org.encog.ml.ea.train.basic.TrainEA; import org.encog.neural.neat.NEATPopulation; import org.encog.neural.neat.training.opp.NEATMutateAddLink; import org.encog.neural.neat.training.opp.NEATMutateRemoveLink; import org.encog.neural.neat.training.opp.NEATMutateWeights; import org.encog.neural.neat.training.opp.links.MutatePerturbLinkWeight; import org.encog.neural.neat.training.opp.links.MutateResetLinkWeight; import org.encog.neural.neat.training.opp.links.SelectFixed; import org.encog.neural.neat.training.opp.links.SelectProportion; import org.encog.neural.neat.training.species.OriginalNEATSpeciation; import za.redbridge.experiment.MMNEAT.training.opp.MMNEATCrossover; import za.redbridge.experiment.MMNEAT.training.opp.MMNEATMutateAddNode; import za.redbridge.experiment.MMNEAT.training.opp.MMNEATMutateAddSensor; import za.redbridge.experiment.MMNEAT.training.opp.MMNEATMutatePositions; import za.redbridge.experiment.MMNEAT.training.opp.sensors.MutatePerturbSensorPosition; import za.redbridge.experiment.MMNEAT.training.opp.sensors.SelectSensorsFixed; public final class MMNEATUtil { public static TrainEA constructNEATTrainer(CalculateScore calculateScore, int outputCount, int populationSize) { final MMNEATPopulation pop = new MMNEATPopulation(outputCount, populationSize); pop.reset(); return constructNEATTrainer(pop, calculateScore); } /** * Construct a NEAT trainer. * @param population The population. * @param calculateScore The score function. * @return The NEAT EA trainer. */ public static TrainEA constructNEATTrainer(NEATPopulation population, CalculateScore calculateScore) { final TrainEA result = new TrainEA(population, calculateScore); // Speciation result.setSpeciation(new OriginalNEATSpeciation()); // Selection result.setSelection(new TruncationSelection(result, 0.3)); // Create compound operator for weight mutation CompoundOperator weightMutation = new CompoundOperator(); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectFixed(1), new MutatePerturbLinkWeight(0.02))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectFixed(2), new MutatePerturbLinkWeight(0.02))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectFixed(3), new MutatePerturbLinkWeight(0.02))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectProportion(0.02), new MutatePerturbLinkWeight(0.02))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectFixed(1), new MutatePerturbLinkWeight(1))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectFixed(2), new MutatePerturbLinkWeight(1))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectFixed(3), new MutatePerturbLinkWeight(1))); weightMutation.getComponents().add(0.1125, new NEATMutateWeights(new SelectProportion(0.02), new MutatePerturbLinkWeight(1))); weightMutation.getComponents().add(0.03, new NEATMutateWeights(new SelectFixed(1), new MutateResetLinkWeight())); weightMutation.getComponents().add(0.03, new NEATMutateWeights(new SelectFixed(2), new MutateResetLinkWeight())); weightMutation.getComponents().add(0.03, new NEATMutateWeights(new SelectFixed(3), new MutateResetLinkWeight())); weightMutation.getComponents().add(0.01, new NEATMutateWeights(new SelectProportion(0.02), new MutateResetLinkWeight())); weightMutation.getComponents().finalizeStructure(); // Champ operator limits mutation operator on best genome (seems unused for now) result.setChampMutation(weightMutation); // Add all the operators, probability should sum to 1 result.addOperation(0.5, new MMNEATCrossover()); result.addOperation(0.444, weightMutation); result.addOperation(0.0005, new MMNEATMutateAddNode()); result.addOperation(0.005, new NEATMutateAddLink()); result.addOperation(0.0005, new NEATMutateRemoveLink()); // Add the sensor position mutator result.addOperation(0.045, new MMNEATMutatePositions( new SelectSensorsFixed(1), new MutatePerturbSensorPosition(1, 1))); // Add sensor mutation - use the smallest link perturb operation result.addOperation(0.005, new MMNEATMutateAddSensor( population.getInitialConnectionDensity(), new MutatePerturbLinkWeight(0.02))); result.getOperators().finalizeStructure(); result.setCODEC(new MMNEATCODEC()); return result; } }
package com.kevlindev.karnaugh; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class QuineMcCluskey { /** * @param args */ public static void main(String[] args) { if (args != null && args.length > 0) { QuineMcCluskey minimizer = new QuineMcCluskey(); for (String arg : args) { minimizer.minimize(arg); } } } private Comparator<String> implicantComparator = new Comparator<String>() { @Override public int compare(String arg0, String arg1) { int result = 0; for (int i = 0; i < arg0.length(); i++) { char c1 = arg0.charAt(i); char c2 = arg1.charAt(i); if (c1 != c2) { // do nothing if (c1 == '-') { result = 1; } else if (c2 == '-') { result = -1; } else if (c1 == '0') { result = -1; } else if (c2 == '1') { result = 1; } break; } } return result; } }; private Set<MinTerm> flattenPartitions(List<List<MinTerm>> partitions) { Set<MinTerm> result = new HashSet<MinTerm>(); for (List<MinTerm> partition : partitions) { result.addAll(partition); } return result; } private List<List<MinTerm>> getEssentialPrimeImplicants(Function f, List<List<MinTerm>> partitions) { Set<Integer> indexes = new HashSet<Integer>(f.getMinTermIndexes()); List<List<MinTerm>> solutions = new ArrayList<List<MinTerm>>(); // collect all terms List<MinTerm> allTerms = new ArrayList<MinTerm>(); for (List<MinTerm> terms : partitions) { allTerms.addAll(terms); } boolean[] selectors = new boolean[allTerms.size()]; while (true) { Set<Integer> candidate = new HashSet<Integer>(); List<MinTerm> terms = new ArrayList<MinTerm>(); for (int i = 0; i < selectors.length; i++) { if (selectors[i]) { terms.add(allTerms.get(i)); candidate.addAll(allTerms.get(i).getIndexes()); } } if (candidate.equals(indexes)) { // TODO: keep track of best solution instead of collecting all // solutions solutions.add(terms); } // advance int i; for (i = 0; i < selectors.length; i++) { if (selectors[i] == false) { selectors[i] = true; break; } else { selectors[i] = false; } } if (i == selectors.length) { break; } } Collections.sort(solutions, new Comparator<List<MinTerm>>() { @Override public int compare(List<MinTerm> arg0, List<MinTerm> arg1) { int result = arg0.size() - arg1.size(); if (result == 0) { int indexCount0 = 0; int indexCount1 = 0; for (MinTerm term : arg0) { indexCount0 += term.getIndexes().size(); } for (MinTerm term : arg1) { indexCount1 += term.getIndexes().size(); } result = indexCount0 - indexCount1; } return result; } }); return solutions; } /** * getMinimizedFunction * * @param f * @param primeImplicants * @return */ private String getMinimizedFunction(Function f, List<String> primeImplicants) { List<String> products = new ArrayList<String>(); List<String> arguments = f.getArguments(); for (String primeImplicant : primeImplicants) { List<String> sums = new ArrayList<String>(); for (int i = 0; i < arguments.size(); i++) { char c = primeImplicant.charAt(i); switch (c) { case '0': sums.add("~" + arguments.get(i)); break; case '1': sums.add(arguments.get(i)); break; } } products.add(Util.join(" & ", sums)); } return f.getName() + " = " + Util.join(" | ", products); } /** * getPrimeImplicants * * @param partitions * @return */ private List<String> getPrimeImplicants(List<List<MinTerm>> partitions) { Set<String> primeImplicantSet = new HashSet<String>(); for (List<MinTerm> partition : partitions) { for (MinTerm term : partition) { primeImplicantSet.add(Util.join("", term.getBits())); } } ArrayList<String> primeImplicants = new ArrayList<String>(primeImplicantSet); Collections.sort(primeImplicants, implicantComparator); return primeImplicants; } /** * minimize * * @param file */ public void minimize(String file) { Function f = readFile(file); List<List<MinTerm>> partitions = Util.partitionMinTerms(f.getBits(), f.getMinTerms()); System.out.println("Initial Partitions"); System.out.println("=================="); printPartitions(partitions); // TODO: loop until no change for (int i = 0; i < 2; i++) { System.out.println(); System.out.println("Pass " + (i + 1)); System.out.println("======"); partitions = reducePartitions(partitions); printPartitions(partitions); } List<String> primeImplicants = getPrimeImplicants(partitions); List<List<MinTerm>> solutions = getEssentialPrimeImplicants(f, partitions); printSection("Function", f.toString()); printSection("Prime Implicants", Util.join(", ", primeImplicants)); System.out.println(); System.out.println("Essential Prime Implicants"); System.out.println("=========================="); printPartitions(solutions); if (solutions != null && solutions.size() > 0) { List<MinTerm> solution = solutions.get(0); List<String> essentialPrimeImplicants = new ArrayList<String>(); for (MinTerm term : solution) { essentialPrimeImplicants.add(Util.join("", term.getBits())); } Collections.sort(essentialPrimeImplicants, implicantComparator); printSection("Minimized Function", getMinimizedFunction(f, essentialPrimeImplicants)); } else { System.out.println("No solution found. This most likely indicates an error condition in this application."); } } /** * printPartitions * * @param partitions */ private void printPartitions(List<List<MinTerm>> partitions) { for (int i = 0; i < partitions.size(); i++) { List<MinTerm> partition = partitions.get(i); List<String> v = new ArrayList<String>(); for (MinTerm minterm : partition) { String indexes = "[" + minterm.toString() + "]"; v.add(indexes); } System.out.println(i + " : " + Util.join(", ", v)); } } /** * printSection * * @param header * @param content */ private void printSection(String header, String content) { System.out.println(); System.out.println(header); System.out.println(Util.repeat("=", header.length())); System.out.println(content); } /** * readFile * * @param file * @return */ public Function readFile(String file) { Scanner scanner = null; Function f = null; try { scanner = new Scanner(new FileInputStream(file), "utf-8"); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] parts = line.split("\\s*=\\s*"); boolean valid = false; if (parts.length == 2) { String function = parts[0]; int lparen = function.indexOf('('); int rparen = function.indexOf(')'); if (lparen != -1 && rparen != -1) { String name = function.substring(0, lparen).trim(); String[] args = function.substring(lparen + 1, rparen).split("\\s*,\\s*"); List<TruthValue> values = new ArrayList<TruthValue>(); for (String valueString : parts[1].split("\\s*,\\s*")) { values.add("1".equals(valueString) ? TruthValue.TRUE : TruthValue.FALSE); } int bits = (int) Math.ceil(Math.log(values.size()) / Math.log(2)); f = new Function(name, bits); f.setArguments(Arrays.asList(args)); f.setValues(values); valid = true; } } if (valid == false) { System.err.println("Invalid content: " + line); } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { scanner.close(); } return f; } /** * reducePartitions * * @param partitions * @return */ private List<List<MinTerm>> reducePartitions(List<List<MinTerm>> partitions) { Set<MinTerm> result = new HashSet<MinTerm>(); Set<MinTerm> remainingMinTerms = flattenPartitions(partitions); for (int i = 0; i < partitions.size() - 1; i++) { List<MinTerm> currentPartition = partitions.get(i); List<MinTerm> nextPartition = partitions.get(i + 1); for (MinTerm term1 : currentPartition) { for (MinTerm term2 : nextPartition) { MinTerm merged = term1.merge(term2); if (merged != null) { result.add(merged); remainingMinTerms.remove(term1); remainingMinTerms.remove(term2); } } } } result.addAll(remainingMinTerms); return Util.partitionMinTerms(partitions.size() - 1, result); } }
package com.mpu.spinv.engine; import com.mpu.spinv.engine.model.GameObject; /** * CollisionHandler.java * * @author Brendon Pagano * @date 2017-09-20 */ public class CollisionHandler { public static boolean hasCollided(GameObject obj0, GameObject obj1) { return CollisionHandler.hasCollided(obj0.getX(), obj0.getY(), obj0.getX() + obj0.getWidth(), obj0.getY() + obj0.getHeight(), obj1.getX(), obj1.getY(), obj1.getX() + obj1.getWidth(), obj1.getY() + obj1.getHeight()); } public static boolean hasCollided(int x0, int y0, int xw0, int yh0, int x1, int y1, int xw1, int yh1) { if (x0 < xw1 && xw0 > x1 && yh0 > y1 && y0 < yh1) return true; return false; } }
package com.mpu.spinv.engine.model; import java.awt.Graphics; import java.util.HashMap; import java.util.Map; /** * GameObject.java * * @author Brendon Pagano * @date 2017-08-08 */ public class GameObject { /** * The x and y position of the object in the screen. */ protected int x, y; /** * The direction to update x and y axis. */ protected int dx, dy; /** * A list of the object's animations. */ private final Map<String, Animation> animations; /** * The key identifier of the active animation. */ private String actAnimation; /** * The active animation. Currently playing if {@link GameObject#visible} is * true. */ private Animation animation; /** * GameObject's size. */ private int width, height; /** * Attribute used for checking. Mainly for drawing or not the object * accordingly to it's visibility status. */ private boolean visible; /** * GameObject's constructor. * * @param x * The x position of the object in the screen. * @param y * The y position of the object in the screen. * @param visible * Flag to determine if the object will begin visible or not. */ public GameObject(int x, int y, boolean visible) { this.x = x; this.y = y; this.visible = visible; // Default params this.dx = 0; this.dy = 0; this.animations = new HashMap<String, Animation>(); this.animation = null; this.actAnimation = ""; } public GameObject(int x, int y, Animation animation, boolean visible) { this.x = x; this.y = y; this.visible = visible; // Default params this.dx = 0; this.dy = 0; this.animations = new HashMap<String, Animation>(); // Setting the default animation this.actAnimation = "default"; addAnimation(this.actAnimation, animation); } public void init() { } public void update() { x += dx; y += dy; if (animation != null) animation.update(); } public void draw(Graphics g) { if (visible && animation != null) g.drawImage(animation.getSprite(), x, y, null); } /** * Adds an animation into the GameObject's animations list. * * @param key * the identifier of the animation to add. * @param animation * the animation object to be added. */ public void addAnimation(String key, Animation animation) { animations.put(key, animation); if (this.animation == null) this.animation = animation; } /** * Set the active and playing animation to a new one. * * @param key * the identifier of the animation to be set. */ public void setAnimation(String key) { if (animations.containsKey(key)) { actAnimation = key; animation = animations.get(key); } } /** * Removes an animation from the GameObject's animation list and returns the * removed animation object. * * @param key * the key identifier of the animation to be removed. * @return the removed animation object. */ public Animation removeAnimation(String key) { Animation animation = null; if (animations.containsKey(key)) { animation = animations.get(key); animations.remove(key); if (actAnimation.equals(key)) { this.animation = null; this.actAnimation = ""; } } return animation; } // Getters and Setters public String getAnimationKey() { return actAnimation; } public int getWidth() { return width; } public int getHeight() { return height; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } }
package com.redhat.ceylon.common; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; public class ConfigParser { private File configFile; private File currentDir; private CeylonConfig config; private InputStream in; public static final String PROP_CEYLON_CONFIG_FILE = "ceylon.config"; public static CeylonConfig loadDefaultConfig() throws IOException { File configFile; String configFilename = System.getProperty(PROP_CEYLON_CONFIG_FILE); if (configFilename != null) { configFile = new File(configFilename); } else { configFile = new File(new File(System.getProperty("user.home"), ".ceylon"), "config"); } return (new ConfigParser(configFile)).parse(); } public static CeylonConfig loadLocalConfig(File dir) throws IOException { File userConfig1 = (new File(CeylonConfig.getDefaultUserDir(), "config")).getCanonicalFile().getAbsoluteFile(); File userConfig2 = (new File(CeylonConfig.getUserDir(), "config")).getCanonicalFile().getAbsoluteFile(); dir = dir.getCanonicalFile().getAbsoluteFile(); while (dir != null) { File configFile = new File(dir, ".ceylon/config"); if (configFile.equals(userConfig1) || configFile.equals(userConfig2)) { // We stop if we reach $HOME/.ceylon/config or whatever is defined by -Dceylon.config break; } if (configFile.isFile()) { return (new ConfigParser(configFile)).parse(); } dir = dir.getParentFile(); } // We didn't find any local config file, just return an empty CeylonConfig return new CeylonConfig(); } public static CeylonConfig loadConfigFromFile(File configFile) throws IOException { return (new ConfigParser(configFile)).parse(); } public static CeylonConfig loadConfigFromStream(InputStream stream, File currentDir) throws IOException { return (new ConfigParser(stream, currentDir)).parse(); } private ConfigParser(File configFile) { this.configFile = configFile; this.currentDir = configFile.getParentFile(); } private ConfigParser(InputStream in, File currentDir) { this.in = in; this.currentDir = currentDir; } private CeylonConfig parse() throws IOException { config = new CeylonConfig(); if (configFile == null || configFile.isFile()) { if (configFile != null) { in = new FileInputStream(configFile); } ConfigReader reader = new ConfigReader(in, new ConfigReaderListener() { @Override public void setup() throws IOException { // We ignore the setup } @Override public void onSection(String section, String text) { // We ignore sections } @Override public void onOption(String name, String value, String text) { // Special "variable" to get the current directory for this config file if (value.startsWith("${DIR}")) { try { value = currentDir.getCanonicalPath() + value.substring(6); } catch (IOException e) { } } String[] oldval = config.getOptionValues(name); if (oldval == null) { config.setOption(name, value); } else { String[] newVal = Arrays.copyOf(oldval, oldval.length + 1); newVal[oldval.length] = value; config.setOptionValues(name, newVal); } } @Override public void onComment(String text) { // We ignore comments } @Override public void onWhitespace(String text) { // We ignore white space } @Override public void cleanup() throws IOException { // We ignore the cleanup } }); reader.process(); } else { throw new FileNotFoundException("Couldn't open configuration file"); } return config; } }
package com.sudoku.comm; import com.sudoku.comm.generated.Message; import com.sudoku.comm.generated.NodeExplorer; import com.sudoku.data.manager.UserManager; import com.sudoku.data.model.User; import org.apache.avro.AvroRemoteException; import org.apache.avro.ipc.NettyTransceiver; import org.apache.avro.ipc.specific.SpecificRequestor; import java.io.IOException; import java.lang.Long; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; // Class representing a connection to a remote user public class AvroConnectionManager extends ConnectionManager { private final static Long CONNECTION_TIME_OUT = new Long(1000); private NettyTransceiver client; private NodeExplorer explorer; public AvroConnectionManager(String ip) { super(ip); } public void openConnection() throws OfflineUserException { try { client = new NettyTransceiver(new InetSocketAddress(ipAddress, NODE_PORT), CONNECTION_TIME_OUT); explorer = (NodeExplorer) SpecificRequestor.getClient(NodeExplorer.class, client); } catch(IOException exc) {throw new OfflineUserException();} isConnected = true; } public List<String> getConnectedIps(ArrayList<String> newConnectedIps) throws ConnectionClosedException, OfflineUserException { super.getConnectedIps(newConnectedIps); CommunicationManager cm = CommunicationManager.getInstance(); Message userCredentials = new Message(cm.getUuid(), cm.getLogin(), newConnectedIps); List<String> res; try { Message receivedMessage = explorer.discoverNode(userCredentials); res = receivedMessage.getListIps(); } catch (AvroRemoteException exc) {throw new OfflineUserException();} return res; } public void closeConnection() throws OfflineUserException { try { explorer.disconnect(CommunicationManager.getInstance().getLocalIp()); } catch (AvroRemoteException exc) {throw new OfflineUserException();} client.close(); client = null; isConnected = false; } /*public ArrayList<Grid> getGrids() throws ConnectionClosedException { } public User getProfile() throws ConnectionClosedException { } public void pushComment(Comment c, Grid g) throws ConnectionClosedException { } public void publishComment(Comment c, Grid g) throws ConnectionClosedException { } */ }
package com.lensflare.svh; import java.util.Map; /** * The {@code Authenticator} class is used to authenticate users for services. * Classes that implement this interface are expected to implement a public * constructor with the same signature as * {@link com.lensflare.svh.impl.Authenticator#Authenticator(Server, String, Map)}. * <hr /><span style="font-weight:bold">YAML</span><br /> * The only required parameter is {@code class}. The authenticator will be * instantiated as the specified class. Implementations may require more * parameters. * <hr /> * @author firelizzard * */ public interface Authenticator { /** * @return the name of this authenticator */ public String getName(); /** * Determines whether or not a user is authorized to connect to a service. * @param user the user * @param service the service * @return true if the user should be allowed to connect */ public boolean userIsAuthorizedForService(String user, Service service); }
package com.thaiopensource.relaxng; import com.thaiopensource.datatype.Datatype; import com.thaiopensource.datatype.DatatypeContext; import org.xml.sax.SAXException; class StringAtom extends Atom { private String str; private DatatypeContext dc; static class Key { String key; String keyRef; Object value; Key(String key, String keyRef, Object value) { this.key = key; this.keyRef = keyRef; this.value = value; } } private Key[] keys; StringAtom(String str, DatatypeContext dc) { this.str = str; this.dc = dc; } boolean matchesString() { return true; } boolean matchesDatatypeValue(Datatype dt, Object obj) { return obj.equals(dt.createValue(str, dc)); } boolean matchesList(PatternBuilder b, Pattern p) { int len = str.length(); int tokenStart = -1; Pattern r = p; for (int i = 0; i < len; i++) { switch (str.charAt(i)) { case '\r': case '\n': case ' ': case '\t': if (tokenStart >= 0) { r = matchToken(b, r, tokenStart, i); tokenStart = -1; } break; default: if (tokenStart < 0) tokenStart = i; break; } } if (tokenStart >= 0) r = matchToken(b, r, tokenStart, len); return r.isNullable(); } private Pattern matchToken(PatternBuilder b, Pattern p, int i, int j) { StringAtom sa = new StringAtom(str.substring(i, j), dc); Pattern r = p.residual(b, sa); if (sa.keys != null) { if (sa.keys.length != 1) throw new Error("more than one key for a token"); if (keys == null) keys = sa.keys; else { Key[] newKeys = new Key[keys.length + 1]; System.arraycopy(keys, 0, newKeys, 0, keys.length); newKeys[keys.length] = sa.keys[0]; keys = newKeys; } } return r; } boolean matchesDatatype(Datatype dt) { return dt.allows(str, dc); } boolean matchesDatatype(Datatype dt, String key, String keyRef) { Object obj = dt.createValue(str, dc); if (obj == null) return false; keys = new Key[]{ new Key(key, keyRef, obj) }; return true; } void checkKeys(KeyChecker kc) throws SAXException { if (keys == null) return; for (int i = 0; i < keys.length; i++) { if (keys[i].key != null) kc.checkKey(keys[i].key, keys[i].value); if (keys[i].keyRef != null) kc.checkKeyRef(keys[i].keyRef, keys[i].value); } } }
package mabbas007.tagsedittext; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.text.InputType; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.ViewTreeObserver; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import mabbas007.tagsedittext.utils.ResourceUtils; public class TagsEditText extends AutoCompleteTextView { private static final String SEPARATOR = " "; public static final String NEW_LINE = "\n"; private static final String LAST_STRING = "lastString"; private static final String TAGS = "tags"; private static final String SUPER_STATE = "superState"; private static final String UNDER_CONSTRUCTION_TAG = "underConstructionTag"; private static final String ALLOW_SPACES_IN_TAGS = "allowSpacesInTags"; private static final String TAGS_BACKGROUND_RESOURCE = "tagsBackground"; private static final String TAGS_TEXT_COLOR = "tagsTextColor"; private static final String TAGS_TEXT_SIZE = "tagsTextSize"; private static final String LEFT_DRAWABLE_RESOURCE = "leftDrawable"; private static final String RIGHT_DRAWABLE_RESOURCE = "rightDrawable"; private static final String DRAWABLE_PADDING = "drawablePadding"; private String mLastString = ""; private boolean mIsAfterTextWatcherEnabled = true; private int mTagsTextColor; private float mTagsTextSize; private Drawable mTagsBackground; private int mTagsBackgroundResource = 0; private Drawable mLeftDrawable; private int mLeftDrawableResouce = 0; private Drawable mRightDrawable; private int mRightDrawableResouce = 0; private int mDrawablePadding; private boolean mIsSpacesAllowedInTags = false; private boolean mIsSetTextDisabled = false; private List<TagSpan> mTagSpans = new ArrayList<>(); private List<Tag> mTags = new ArrayList<>(); private TagsEditListener mListener; private final TextWatcher mTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mIsAfterTextWatcherEnabled) { setTags(); } } }; public TagsEditText(Context context) { super(context); init(null, 0, 0); } public TagsEditText(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0, 0); } public TagsEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr, 0); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public TagsEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs, defStyleAttr, defStyleRes); } @Override protected void onSelectionChanged(int selStart, int selEnd) { if (getText() != null) { setSelection(getText().length()); } else { super.onSelectionChanged(selStart, selEnd); } } /** * do not use this method to set tags */ @Override public void setText(CharSequence text, BufferType type) { if (mIsSetTextDisabled) return; if (!TextUtils.isEmpty(text)) { String source = mIsSpacesAllowedInTags ? text.toString().trim() : text.toString().replaceAll(" ", ""); if (mTags.isEmpty()) { Tag tag = new Tag(); tag.setIndex(0); tag.setPosition(0); tag.setSource(source); tag.setSpan(true); mTags.add(tag); } else { int size = mTags.size(); Tag lastTag = mTags.get(size - 1); if (!lastTag.isSpan()) { lastTag.setSource(source); lastTag.setSpan(true); } else { Tag newTag = new Tag(); newTag.setIndex(size); newTag.setPosition(lastTag.getPosition() + lastTag.getSource().length() + 1); newTag.setSource(source); newTag.setSpan(true); mTags.add(newTag); } } buildStringWithTags(mTags); mTextWatcher.afterTextChanged(getText()); } else { super.setText(text, type); } } /** * use this method to set tags */ public void setTags(CharSequence... tags) { mTagSpans.clear(); mTags.clear(); int length = tags != null ? tags.length : 0; int position = 0; for (int i = 0; i < length; i++) { Tag tag = new Tag(); tag.setIndex(i); tag.setPosition(position); String source = mIsSpacesAllowedInTags ? tags[i].toString().trim() : tags[i].toString().replaceAll(" ", ""); tag.setSource(source); tag.setSpan(true); mTags.add(tag); position += source.length() + 1; } buildStringWithTags(mTags); mTextWatcher.afterTextChanged(getText()); } /** * use this method to set tags */ public void setTags(String[] tags) { mTagSpans.clear(); mTags.clear(); int length = tags != null ? tags.length : 0; int position = 0; for (int i = 0; i < length; i++) { Tag tag = new Tag(); tag.setIndex(i); tag.setPosition(position); String source = mIsSpacesAllowedInTags ? tags[i].trim() : tags[i].replaceAll(" ", ""); tag.setSource(source); tag.setSpan(true); mTags.add(tag); position += source.length() + 1; } buildStringWithTags(mTags); mTextWatcher.afterTextChanged(getText()); } @Override public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable(SUPER_STATE, super.onSaveInstanceState()); Tag[] tags = new Tag[mTags.size()]; mTags.toArray(tags); bundle.putParcelableArray(TAGS, tags); bundle.putString(LAST_STRING, mLastString); bundle.putString(UNDER_CONSTRUCTION_TAG, getNewTag(getText().toString())); bundle.putInt(TAGS_TEXT_COLOR, mTagsTextColor); bundle.putInt(TAGS_BACKGROUND_RESOURCE, mTagsBackgroundResource); bundle.putFloat(TAGS_TEXT_SIZE, mTagsTextSize); bundle.putInt(LEFT_DRAWABLE_RESOURCE, mLeftDrawableResouce); bundle.putInt(RIGHT_DRAWABLE_RESOURCE, mRightDrawableResouce); bundle.putInt(DRAWABLE_PADDING, mDrawablePadding); bundle.putBoolean(ALLOW_SPACES_IN_TAGS, mIsSpacesAllowedInTags); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Context context = getContext(); Bundle bundle = (Bundle) state; mTagsTextColor = bundle.getInt(TAGS_TEXT_COLOR, mTagsTextColor); mTagsBackgroundResource = bundle.getInt(TAGS_BACKGROUND_RESOURCE, mTagsBackgroundResource); if (mTagsBackgroundResource != 0) { mTagsBackground = ContextCompat.getDrawable(context, mTagsBackgroundResource); } mTagsTextSize = bundle.getFloat(TAGS_TEXT_SIZE, mTagsTextSize); mLeftDrawableResouce = bundle.getInt(LEFT_DRAWABLE_RESOURCE, mLeftDrawableResouce); if (mLeftDrawableResouce != 0) { mLeftDrawable = ContextCompat.getDrawable(context, mLeftDrawableResouce); } mRightDrawableResouce = bundle.getInt(RIGHT_DRAWABLE_RESOURCE, mRightDrawableResouce); if (mRightDrawableResouce != 0) { mRightDrawable = ContextCompat.getDrawable(context, mRightDrawableResouce); } mDrawablePadding = bundle.getInt(DRAWABLE_PADDING, mDrawablePadding); mIsSpacesAllowedInTags = bundle.getBoolean(ALLOW_SPACES_IN_TAGS, mIsSpacesAllowedInTags); mLastString = bundle.getString(LAST_STRING); Parcelable[] tagsParcelables = bundle.getParcelableArray(TAGS); if (tagsParcelables != null) { Tag[] tags = new Tag[tagsParcelables.length]; System.arraycopy(tagsParcelables, 0, tags, 0, tagsParcelables.length); mTags = new ArrayList<>(); Collections.addAll(mTags, tags); buildStringWithTags(mTags); mTextWatcher.afterTextChanged(getText()); } state = bundle.getParcelable(SUPER_STATE); mIsSetTextDisabled = true; super.onRestoreInstanceState(state); mIsSetTextDisabled = false; String temp = bundle.getString(UNDER_CONSTRUCTION_TAG); if (!TextUtils.isEmpty(temp)) getText().append(temp); } else { super.onRestoreInstanceState(state); } } private void buildStringWithTags(List<Tag> tags) { mIsAfterTextWatcherEnabled = false; getText().clear(); for (Tag tag : tags) { getText().append(tag.getSource()).append(SEPARATOR); } mLastString = getText().toString(); if (!TextUtils.isEmpty(mLastString)) { getText().append(NEW_LINE); } mIsAfterTextWatcherEnabled = true; } public void setTagsTextColor(@ColorRes int color) { mTagsTextColor = ContextCompat.getColor(getContext(), color); setTags(convertTagSpanToArray(mTagSpans)); } public void setTagsTextSize(@DimenRes int textSize) { mTagsTextSize = ResourceUtils.getDimension(getContext(), textSize); setTags(convertTagSpanToArray(mTagSpans)); } public void setTagsBackground(@DrawableRes int drawable) { mTagsBackground = ContextCompat.getDrawable(getContext(), drawable); mTagsBackgroundResource = drawable; setTags(convertTagSpanToArray(mTagSpans)); } public void setCloseDrawableLeft(@DrawableRes int drawable) { mLeftDrawable = ContextCompat.getDrawable(getContext(), drawable); mLeftDrawableResouce = drawable; setTags(convertTagSpanToArray(mTagSpans)); } public void setCloseDrawableRight(@DrawableRes int drawable) { mRightDrawable = ContextCompat.getDrawable(getContext(), drawable); mRightDrawableResouce = drawable; setTags(convertTagSpanToArray(mTagSpans)); } public void setCloseDrawablePadding(@DimenRes int padding) { mDrawablePadding = ResourceUtils.getDimensionPixelSize(getContext(), padding); setTags(convertTagSpanToArray(mTagSpans)); } public void setTagsWithSpacesEnabled(boolean isSpacesAllowedInTags) { mIsSpacesAllowedInTags = isSpacesAllowedInTags; setTags(convertTagSpanToArray(mTagSpans)); } public void setTagsListener(TagsEditListener listener) { mListener = listener; } private void init(@Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { Context context = getContext(); if (attrs == null) { mIsSpacesAllowedInTags = false; mTagsTextColor = ContextCompat.getColor(context, R.color.defaultTagsTextColor); mTagsTextSize = ResourceUtils.getDimensionPixelSize(context, R.dimen.defaultTagsTextSize); mTagsBackground = ContextCompat.getDrawable(context, R.drawable.oval); mRightDrawable = ContextCompat.getDrawable(context, R.drawable.tag_close); mDrawablePadding = ResourceUtils.getDimensionPixelSize(context, R.dimen.defaultTagsCloseImagePadding); } else { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TagsEditText, defStyleAttr, defStyleRes); try { mIsSpacesAllowedInTags = typedArray.getBoolean(R.styleable.TagsEditText_allowSpaceInTag, false); mTagsTextColor = typedArray.getColor(R.styleable.TagsEditText_tagsTextColor, ContextCompat.getColor(context, R.color.defaultTagsTextColor)); mTagsTextSize = typedArray.getDimensionPixelSize(R.styleable.TagsEditText_tagsTextSize, ResourceUtils.getDimensionPixelSize(context, R.dimen.defaultTagsTextSize)); mTagsBackground = typedArray.getDrawable(R.styleable.TagsEditText_tagsBackground); mRightDrawable = typedArray.getDrawable(R.styleable.TagsEditText_tagsCloseImageRight); mLeftDrawable = typedArray.getDrawable(R.styleable.TagsEditText_tagsCloseImageLeft); mDrawablePadding = ResourceUtils.getDimensionPixelSize(context, R.dimen.defaultTagsCloseImagePadding); } finally { typedArray.recycle(); } } setMovementMethod(LinkMovementMethod.getInstance()); setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); ViewTreeObserver viewTreeObserver = getViewTreeObserver(); if (viewTreeObserver.isAlive()) { viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { getViewTreeObserver().removeGlobalOnLayoutListener(this); } addTextChangedListener(mTextWatcher); mTextWatcher.afterTextChanged(getText()); } }); } } private void setTags() { mIsAfterTextWatcherEnabled = false; boolean isEnterClicked = false; final Editable editable = getText(); String str = editable.toString(); if (str.endsWith(NEW_LINE)) { isEnterClicked = true; } boolean isDeleting = mLastString.length() > str.length(); if (mLastString.endsWith(SEPARATOR) && !str.endsWith(NEW_LINE) && isDeleting && !mTagSpans.isEmpty()) { TagSpan toRemoveSpan = mTagSpans.get(mTagSpans.size() - 1); Tag tag = toRemoveSpan.getTag(); if (tag.getPosition() + tag.getSource().length() == str.length()) { removeTagSpan(editable, toRemoveSpan, false); str = editable.toString(); } } if (getFilter() != null) { performFiltering(getNewTag(str), 0); } if (str.endsWith(NEW_LINE) || (!mIsSpacesAllowedInTags && str.endsWith(SEPARATOR)) && !isDeleting) { buildTags(str); } mLastString = getText().toString(); mIsAfterTextWatcherEnabled = true; if (isEnterClicked && mListener != null) { mListener.onEditingFinished(); } } private void buildTags(String str) { if (str.length() != 0) { updateTags(str); SpannableStringBuilder sb = new SpannableStringBuilder(); for (final TagSpan tagSpan : mTagSpans) { addTagSpan(sb, tagSpan); } int size = mTags.size(); for (int i = mTagSpans.size(); i < size; i++) { Tag tag = mTags.get(i); String source = tag.getSource(); if (tag.isSpan()) { TextView tv = createTextView(source); Drawable bd = convertViewToDrawable(tv); bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight()); final TagSpan span = new TagSpan(bd, source); addTagSpan(sb, span); span.setTag(tag); mTagSpans.add(span); } else { sb.append(source); } } getText().clear(); getText().append(sb); setMovementMethod(LinkMovementMethod.getInstance()); setSelection(sb.length()); if (mListener != null && !str.equals(mLastString)) { mListener.onTagsChanged(convertTagSpanToList(mTagSpans)); } } } private void updateTags(String newString) { String source = getNewTag(newString); if (!TextUtils.isEmpty(source) && !source.equals(NEW_LINE)) { boolean isSpan = source.endsWith(NEW_LINE) || (!mIsSpacesAllowedInTags && source.endsWith(SEPARATOR)); if (isSpan) { source = source.substring(0, source.length() - 1); source = source.trim(); } Tag tag = new Tag(); tag.setSource(source); tag.setSpan(isSpan); int size = mTags.size(); if (size <= 0) { tag.setIndex(0); tag.setPosition(0); } else { Tag lastTag = mTags.get(size - 1); tag.setIndex(size); tag.setPosition(lastTag.getPosition() + lastTag.getSource().length() + 1); } mTags.add(tag); } } private String getNewTag(String newString) { StringBuilder builder = new StringBuilder(); for (Tag tag : mTags) { if (!tag.isSpan()) continue; builder.append(tag.getSource()).append(SEPARATOR); } return newString.replace(builder.toString(), ""); } private void addTagSpan(SpannableStringBuilder sb, final TagSpan tagSpan) { String source = tagSpan.getSource(); sb.append(source).append(SEPARATOR); int length = sb.length(); int startSpan = length - (source.length() + 1); int endSpan = length - 1; sb.setSpan(tagSpan, startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sb.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { Editable editable = ((EditText) widget).getText(); mIsAfterTextWatcherEnabled = false; removeTagSpan(editable, tagSpan, true); mIsAfterTextWatcherEnabled = true; } }, startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } private void removeTagSpan(Editable editable, TagSpan span, boolean includeSpace) { int extraLength = includeSpace ? 1 : 0; // include space Tag tag = span.getTag(); int tagPosition = tag.getPosition(); int tagIndex = tag.getIndex(); int tagLength = span.getSource().length() + extraLength; editable.replace(tagPosition, tagPosition + tagLength, ""); int size = mTags.size(); for (int i = tagIndex + 1; i < size; i++) { Tag newTag = mTags.get(i); newTag.setIndex(i - 1); newTag.setPosition(newTag.getPosition() - tagLength); } mTags.remove(tagIndex); mTagSpans.remove(tagIndex); if (mListener == null) return; mListener.onTagsChanged(convertTagSpanToList(mTagSpans)); } private static List<String> convertTagSpanToList(List<TagSpan> tagSpans) { List<String> tags = new ArrayList<>(tagSpans.size()); for (TagSpan tagSpan : tagSpans) { tags.add(tagSpan.getSource()); } return tags; } private static CharSequence[] convertTagSpanToArray(List<TagSpan> tagSpans) { int size = tagSpans.size(); CharSequence[] values = new CharSequence[size]; for (int i = 0; i < size; i++) { values[i] = tagSpans.get(i).getSource(); } return values; } private Drawable convertViewToDrawable(View view) { int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); view.measure(spec, spec); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); c.translate(-view.getScrollX(), -view.getScrollY()); view.draw(c); view.setDrawingCacheEnabled(true); Bitmap cacheBmp = view.getDrawingCache(); Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true); view.destroyDrawingCache(); return new BitmapDrawable(getResources(), viewBmp); } private TextView createTextView(String text) { TextView textView = new TextView(getContext()); if (getWidth() > 0) { textView.setMaxWidth(getWidth() - 50); } textView.setText(text); textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTagsTextSize); textView.setTextColor(mTagsTextColor); // check Android version for set background if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { textView.setBackground(mTagsBackground); } else { textView.setBackgroundDrawable(mTagsBackground); } textView.setCompoundDrawablesWithIntrinsicBounds(mLeftDrawable, null, mRightDrawable, null); textView.setCompoundDrawablePadding(mDrawablePadding); return textView; } private static final class Tag implements Parcelable { private int mPosition; private int mIndex; private String mSource; private boolean mSpan; public static final Creator<Tag> CREATOR = new Creator<Tag>() { @Override public Tag createFromParcel(Parcel in) { return new Tag(in); } @Override public Tag[] newArray(int size) { return new Tag[size]; } }; private Tag() { } protected Tag(Parcel in) { mPosition = in.readInt(); mIndex = in.readInt(); mSource = in.readString(); mSpan = in.readInt() == 1; } private void setPosition(int pos) { mPosition = pos; } private int getPosition() { return mPosition; } private void setIndex(int index) { mIndex = index; } private int getIndex() { return mIndex; } public void setSource(String source) { mSource = source; } public String getSource() { return mSource; } public void setSpan(boolean span) { mSpan = span; } public boolean isSpan() { return mSpan; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mPosition); dest.writeInt(mIndex); dest.writeString(mSource); dest.writeInt(mSpan ? 1 : 0); } } private static final class TagSpan extends ImageSpan { private Tag mTag; public TagSpan(Drawable d, String source) { super(d, source); } // private constructors private TagSpan(Context context, Bitmap b) { super(context, b); } private TagSpan(Context context, Bitmap b, int verticalAlignment) { super(context, b, verticalAlignment); } private TagSpan(Drawable d) { super(d); } private TagSpan(Drawable d, int verticalAlignment) { super(d, verticalAlignment); } private TagSpan(Drawable d, String source, int verticalAlignment) { super(d, source, verticalAlignment); } private TagSpan(Context context, Uri uri) { super(context, uri); } private TagSpan(Context context, Uri uri, int verticalAlignment) { super(context, uri, verticalAlignment); } private TagSpan(Context context, int resourceId) { super(context, resourceId); } private TagSpan(Context context, int resourceId, int verticalAlignment) { super(context, resourceId, verticalAlignment); } private void setTag(Tag tag) { mTag = tag; } public Tag getTag() { return mTag; } } public interface TagsEditListener { void onTagsChanged(Collection<String> tags); void onEditingFinished(); } public static class TagsEditListenerAdapter implements TagsEditListener { @Override public void onTagsChanged(Collection<String> tags) { } @Override public void onEditingFinished() { } } }
package ai.elimu.util.db; import ai.elimu.dao.AllophoneDao; import ai.elimu.dao.EmojiDao; import ai.elimu.dao.LetterDao; import ai.elimu.dao.NumberDao; import ai.elimu.dao.StoryBookChapterDao; import ai.elimu.dao.StoryBookDao; import ai.elimu.dao.StoryBookParagraphDao; import ai.elimu.dao.WordDao; import ai.elimu.model.content.Allophone; import ai.elimu.model.content.Emoji; import ai.elimu.model.content.Letter; import ai.elimu.model.content.Number; import ai.elimu.model.content.StoryBook; import ai.elimu.model.content.StoryBookChapter; import ai.elimu.model.content.StoryBookParagraph; import ai.elimu.model.content.Word; import ai.elimu.model.enums.Environment; import ai.elimu.model.enums.Language; import ai.elimu.model.gson.content.StoryBookChapterGson; import ai.elimu.model.gson.content.StoryBookGson; import ai.elimu.model.gson.content.StoryBookParagraphGson; import ai.elimu.util.WordExtractionHelper; import ai.elimu.util.csv.CsvContentExtractionHelper; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.web.context.WebApplicationContext; public class DbContentImportHelper { private Logger logger = Logger.getLogger(getClass()); private AllophoneDao allophoneDao; private LetterDao letterDao; private WordDao wordDao; private NumberDao numberDao; private EmojiDao emojiDao; private StoryBookDao storyBookDao; private StoryBookChapterDao storyBookChapterDao; private StoryBookParagraphDao storyBookParagraphDao; /** * Extracts educational content from the CSV files in {@code src/main/resources/db/content_TEST/<Language>/} and * stores it in the database. * * @param environment The environment from which to import the database content. * @param language The language to use during the import. * @param webApplicationContext Context needed to access DAOs. */ public synchronized void performDatabaseContentImport(Environment environment, Language language, WebApplicationContext webApplicationContext) { logger.info("performDatabaseContentImport"); logger.info("environment: " + environment + ", language: " + language); if (!((environment == Environment.TEST) || (environment == Environment.PROD))) { throw new IllegalArgumentException("Database content can only be imported from the TEST environment or from the PROD environment"); } // Extract and import Allophones from CSV file in src/main/resources/ URL allophonesCsvFileUrl = getClass().getClassLoader() .getResource("db/content_" + environment + "/" + language.toString().toLowerCase() + "/allophones.csv"); File allophonesCsvFile = new File(allophonesCsvFileUrl.getFile()); List<Allophone> allophones = CsvContentExtractionHelper.getAllophonesFromCsvBackup(allophonesCsvFile); logger.info("allophones.size(): " + allophones.size()); allophoneDao = (AllophoneDao) webApplicationContext.getBean("allophoneDao"); for (Allophone allophone : allophones) { allophone.setLanguage(language); allophoneDao.create(allophone); } // Extract and import Letters from CSV file in src/main/resources/ URL lettersCsvFileUrl = getClass().getClassLoader() .getResource("db/content_" + environment + "/" + language.toString().toLowerCase() + "/letters.csv"); File lettersCsvFile = new File(lettersCsvFileUrl.getFile()); List<Letter> letters = CsvContentExtractionHelper.getLettersFromCsvBackup(lettersCsvFile, allophoneDao); logger.info("letters.size(): " + letters.size()); letterDao = (LetterDao) webApplicationContext.getBean("letterDao"); for (Letter letter : letters) { letter.setLanguage(language); letterDao.create(letter); } // Extract and import Words from CSV file in src/main/resources/ URL wordsCsvFileUrl = getClass().getClassLoader() .getResource("db/content_" + environment + "/" + language.toString().toLowerCase() + "/words.csv"); File wordsCsvFile = new File(wordsCsvFileUrl.getFile()); List<Word> words = CsvContentExtractionHelper.getWordsFromCsvBackup(wordsCsvFile, allophoneDao); logger.info("words.size(): " + words.size()); wordDao = (WordDao) webApplicationContext.getBean("wordDao"); for (Word word : words) { word.setLanguage(language); wordDao.create(word); } // Extract and import Numbers from CSV file in src/main/resources/ URL numbersCsvFileUrl = getClass().getClassLoader() .getResource("db/content_" + environment + "/" + language.toString().toLowerCase() + "/numbers.csv"); File numbersCsvFile = new File(numbersCsvFileUrl.getFile()); List<Number> numbers = CsvContentExtractionHelper.getNumbersFromCsvBackup(numbersCsvFile, wordDao); logger.info("numbers.size(): " + numbers.size()); numberDao = (NumberDao) webApplicationContext.getBean("numberDao"); for (Number number : numbers) { number.setLanguage(language); numberDao.create(number); } // Extract and import Syllables // TODO // Extract and import Emojis from CSV file in src/main/resources/ URL emojisCsvFileUrl = getClass().getClassLoader() .getResource("db/content_" + environment + "/" + language.toString().toLowerCase() + "/emojis.csv"); File emojisCsvFile = new File(emojisCsvFileUrl.getFile()); List<Emoji> emojis = CsvContentExtractionHelper.getEmojisFromCsvBackup(emojisCsvFile, wordDao); logger.info("emojis.size(): " + emojis.size()); emojiDao = (EmojiDao) webApplicationContext.getBean("emojiDao"); for (Emoji emoji : emojis) { emoji.setLanguage(language); emojiDao.create(emoji); } // Extract and import Images // TODO // Extract and import Audios // TODO // Extract and import StoryBooks from CSV file in src/main/resources/ URL storyBooksCsvFileUrl = getClass().getClassLoader() .getResource("db/content_" + environment + "/" + language.toString().toLowerCase() + "/storybooks.csv"); File storyBooksCsvFile = new File(storyBooksCsvFileUrl.getFile()); List<StoryBookGson> storyBookGsons = CsvContentExtractionHelper.getStoryBooksFromCsvBackup(storyBooksCsvFile); logger.info("storyBookGsons.size(): " + storyBookGsons.size()); storyBookDao = (StoryBookDao) webApplicationContext.getBean("storyBookDao"); storyBookChapterDao = (StoryBookChapterDao) webApplicationContext.getBean("storyBookChapterDao"); storyBookParagraphDao = (StoryBookParagraphDao) webApplicationContext.getBean("storyBookParagraphDao"); for (StoryBookGson storyBookGson : storyBookGsons) { // Convert from GSON to JPA StoryBook storyBook = new StoryBook(); storyBook.setLanguage(language); storyBook.setTitle(storyBookGson.getTitle()); storyBook.setDescription(storyBookGson.getDescription()); // TODO: storyBook.setAttributionUrl(); storyBook.setGradeLevel(storyBookGson.getGradeLevel()); storyBookDao.create(storyBook); for (StoryBookChapterGson storyBookChapterGson : storyBookGson.getStoryBookChapters()) { // Convert from GSON to JPA StoryBookChapter storyBookChapter = new StoryBookChapter(); storyBookChapter.setStoryBook(storyBook); storyBookChapter.setSortOrder(storyBookChapterGson.getSortOrder()); storyBookChapterDao.create(storyBookChapter); for (StoryBookParagraphGson storyBookParagraphGson : storyBookChapterGson.getStoryBookParagraphs()) { // Convert from GSON to JPA StoryBookParagraph storyBookParagraph = new StoryBookParagraph(); storyBookParagraph.setStoryBookChapter(storyBookChapter); storyBookParagraph.setSortOrder(storyBookParagraphGson.getSortOrder()); storyBookParagraph.setOriginalText(storyBookParagraphGson.getOriginalText()); List<String> wordsInOriginalText = WordExtractionHelper.getWords(storyBookParagraph.getOriginalText(), language); logger.info("wordsInOriginalText.size(): " + wordsInOriginalText.size()); List<Word> paragraphWords = new ArrayList<>(); logger.info("paragraphWords.size(): " + paragraphWords.size()); for (String wordInOriginalText : wordsInOriginalText) { logger.info("wordInOriginalText: \"" + wordInOriginalText + "\""); wordInOriginalText = wordInOriginalText.toLowerCase(); logger.info("wordInOriginalText (lower-case): \"" + wordInOriginalText + "\""); Word word = wordDao.readByText(language, wordInOriginalText); logger.info("word: " + word); paragraphWords.add(word); } storyBookParagraph.setWords(paragraphWords); storyBookParagraphDao.create(storyBookParagraph); } } } // Extract and import Videos // TODO logger.info("Content import complete"); } }
package com.valkryst.VTerminal; import com.valkryst.VTerminal.font.Font; import com.valkryst.VRadio.Radio; import com.valkryst.VTerminal.misc.ImageColorReplacer; import lombok.Getter; import lombok.Setter; import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.*; public class AsciiCharacter { private final static ImageColorReplacer COLOR_REPLACER = new ImageColorReplacer(); /** The transparent color. */ public final static Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0); /** The character. */ @Getter @Setter private char character; /** Whether or not the foreground should be drawn using the background color. */ @Getter @Setter private boolean isHidden = false; /** The background color. Defaults to black. */ @Getter private Color backgroundColor = Color.BLACK; /** The foreground color. Defaults to white. */ @Getter private Color foregroundColor = Color.WHITE; /** The bounding box of the character's area. */ @Getter private final Rectangle boundingBox = new Rectangle(); /** Whether or not to draw the character as underlined. */ @Getter @Setter private boolean isUnderlined = false; /** The thickness of the underline to draw beneath the character. */ @Getter private int underlineThickness = 2; /** Whether or not the character should be flipped horizontally when drawn. */ @Getter @Setter private boolean isFlippedHorizontally = false; /** Whether or not the character should be flipped vertically when drawn. */ @Getter @Setter private boolean isFlippedVertically = false; private Timer blinkTimer; /** The amount of time, in milliseconds, before the blink effect can occur. */ @Getter private short millsBetweenBlinks = 1000; /** * Constructs a new AsciiCharacter. * * @param character * The character. */ public AsciiCharacter(final char character) { this.character = character; } @Override public String toString() { return "Character:\n" + "\tCharacter: '" + character + "'\n" + "\tBackground Color: " + backgroundColor + "\n" + "\tForeground Color: " + foregroundColor + "\n"; } @Override public boolean equals(final Object object) { if (object instanceof AsciiCharacter == false) { return false; } final AsciiCharacter otherCharacter = (AsciiCharacter) object; if (character != otherCharacter.character) { return false; } if (backgroundColor.equals(otherCharacter.backgroundColor) == false) { return false; } if (foregroundColor.equals(otherCharacter.foregroundColor) == false) { return false; } return true; } /** * Draws the character onto the specified context. * * @param gc * The graphics context to draw with. * * @param font * The font to draw with. * * @param columnIndex * The x-axis (column) coordinate where the character is to be drawn. * * @param rowIndex * The y-axis (row) coordinate where the character is to be drawn. */ public void draw(final Graphics2D gc, final Font font, int columnIndex, int rowIndex) { BufferedImage bufferedImage = font.getCharacterImage(character, backgroundColor != TRANSPARENT_COLOR); // Handle Horizontal/Vertical Flipping: if (isFlippedHorizontally || isFlippedVertically) { AffineTransform tx; if (isFlippedHorizontally && isFlippedVertically) { tx = AffineTransform.getScaleInstance(-1, -1); tx.translate(-bufferedImage.getWidth(), -bufferedImage.getHeight()); } else if (isFlippedHorizontally) { tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-bufferedImage.getWidth(), 0); } else { tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -bufferedImage.getHeight()); } final BufferedImageOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC); bufferedImage = op.filter(bufferedImage, null); } // Retrieve character image & set colors: Image image = bufferedImage; if (foregroundColor.equals(Color.WHITE) == false || (backgroundColor.equals(Color.BLACK) == false && backgroundColor.equals(TRANSPARENT_COLOR) == false)) { final BufferedImageOp op = COLOR_REPLACER.retrieveOperation(backgroundColor, foregroundColor); image = op.filter(bufferedImage, null); } // Draw character: final int fontWidth = font.getWidth(); final int fontHeight = font.getHeight(); columnIndex *= fontWidth; rowIndex *= fontHeight; gc.drawImage(image, columnIndex, rowIndex,null); boundingBox.setLocation(columnIndex, rowIndex); boundingBox.setSize(fontWidth, fontHeight); // Draw underline: if (isUnderlined) { gc.setColor(foregroundColor); final int y = rowIndex + fontHeight - underlineThickness; gc.fillRect(columnIndex, y, fontWidth, underlineThickness); } } /** * Enables the blink effect. * * @param millsBetweenBlinks * The amount of time, in milliseconds, before the blink effect can occur. * * @param radio * The Radio to transmit a DRAW event to whenever a blink occurs. */ public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) { if (radio == null) { throw new NullPointerException("You must specify a Radio when enabling a blink effect."); } if (millsBetweenBlinks <= 0) { this.millsBetweenBlinks = 1000; } else { this.millsBetweenBlinks = millsBetweenBlinks; } blinkTimer = new Timer(this.millsBetweenBlinks, e -> { isHidden = !isHidden; radio.transmit("DRAW"); }); blinkTimer.setInitialDelay(this.millsBetweenBlinks); blinkTimer.setRepeats(true); blinkTimer.start(); } /** Resumes the blink effect. */ public void resumeBlinkEffect() { if (blinkTimer != null) { if (blinkTimer.isRunning() == false) { blinkTimer.start(); } } } /** Pauses the blink effect. */ public void pauseBlinkEffect() { if (blinkTimer != null) { if (blinkTimer.isRunning()) { isHidden = false; blinkTimer.stop(); } } } /** Disables the blink effect. */ public void disableBlinkEffect() { if (blinkTimer != null) { blinkTimer.stop(); blinkTimer = null; } } /** Swaps the background and foreground colors. */ public void invertColors() { final Color temp = backgroundColor; setBackgroundColor(foregroundColor); setForegroundColor(temp); } /** * Sets the new background color. * * Does nothing if the specified color is null. * * @param color * The new background color. */ public void setBackgroundColor(final Color color) { boolean canProceed = color != null; canProceed &= backgroundColor.equals(color) == false; if (canProceed) { this.backgroundColor = color; } } /** * Sets the new foreground color. * * Does nothing if the specified color is null. * * @param color * The new foreground color. */ public void setForegroundColor(final Color color) { boolean canProceed = color != null; canProceed &= foregroundColor.equals(color) == false; if (canProceed) { this.foregroundColor = color; } } /** * Sets the new underline thickness. * * If the specified thickness is negative, then the thickness is set to 1. * If the specified thickness is greater than the font height, then the thickness is set to the font height. * If the font height is greater than Byte.MAX_VALUE, then the thickness is set to Byte.MAX_VALUE. * * @param underlineThickness * The new underline thickness. */ public void setUnderlineThickness(final int underlineThickness) { if (underlineThickness > boundingBox.getHeight()) { this.underlineThickness = (int) boundingBox.getHeight(); } else if (underlineThickness <= 0) { this.underlineThickness = 1; } else { this.underlineThickness = underlineThickness; } } }
package org.tianocore.framework.tasks; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import org.apache.tools.ant.BuildException; import org.tianocore.common.logger.EdkLog; /** Class Tool is to define an external tool to be used for genffsfile **/ public class Tool implements EfiDefine, Section { private String toolName = ""; private ToolArg toolArgList = new ToolArg(); private Input inputFiles = new Input(); private Input tempInputFile = new Input(); private String outputPath; private String outputFileName ; private List<Section> gensectList = new ArrayList<Section>(); /** Call extern tool @param buffer The buffer to put the result with alignment **/ public void toBuffer (DataOutputStream buffer){ /// call extern tool try { executeTool (); } catch (Exception e) { throw new BuildException("Call to executeTool failed!\n" + e.getMessage()); } /// check if file exist File outputFile = new File (this.outputFileName); if (!outputFile.exists()) { throw new BuildException("The file " + outputFile.getPath() + " does not exist!\n"); } /// Read output file and write it's cotains to buffer FileInputStream fs = null; DataInputStream in = null; try { fs = new FileInputStream (outputFile); in = new DataInputStream (fs); int fileLen = (int)outputFile.length(); byte[] data = new byte[fileLen]; in.read(data); buffer.write(data, 0, fileLen); /// 4 byte alignment while ((fileLen & 0x03) != 0) { fileLen++; buffer.writeByte(0); } } catch (Exception e) { EdkLog.log(e.getMessage()); throw new BuildException("Tool call, toBuffer failed!\n"); } finally { try { if (in != null) { in.close(); } if (fs != null) { fs.close(); } outputFile.delete(); } catch (Exception e) { EdkLog.log("WARNING: Cannot close " + outputFile.getPath()); } } } /// execute external tool for genffsfile private void executeTool () { String command = ""; String argument = ""; command = toolName; // Get each section which under the compress {}; // And add it is contains to File; Section sect; try{ Iterator SectionIter = this.gensectList.iterator(); while (SectionIter.hasNext()){ sect = (Section)SectionIter.next(); // Parse <genSection> element File outputFile = File.createTempFile("temp", "sec1", new File(outputPath)); FileOutputStream bo = new FileOutputStream(outputFile); DataOutputStream Do = new DataOutputStream (bo); // Call each section class's toBuffer function. try { sect.toBuffer(Do); } catch (BuildException e) { EdkLog.log(e.getMessage()); throw new BuildException ("GenSection failed at Tool!"); } finally { if (Do != null){ Do.close(); } } this.tempInputFile.insFile(outputFile.getPath()); } } catch (IOException e){ throw new BuildException ("Gensection failed at tool!"); } try { Random ran = new Random(9999); this.outputFileName = "Temp" + ran.nextInt(); argument = toolArgList + inputFiles.toStringWithSinglepPrefix(" -i ") + tempInputFile.toString(" ")+ " -o " + outputFileName; EdkLog.log(this, EdkLog.EDK_VERBOSE, command + " " + argument); /// execute command line Process process = Runtime.getRuntime().exec(command + " " + argument); process.waitFor(); Iterator tempFile = tempInputFile.getNameList().iterator(); while (tempFile.hasNext()){ File file = new File((String)tempFile.next()); if (file.exists()) { file.delete(); } } } catch (Exception e) { EdkLog.log(e.getMessage()); throw new BuildException("Execution of externalTool task failed!\n"); } } /** Add method of ANT task/datatype for nested ToolArg type of element @param toolArg The ToolArg object containing arguments for the tool **/ public void addConfiguredToolArg (ToolArg toolArg) { toolArgList.insert(toolArg); } /** Get method of ANT task/datatype for attribute "OutputPath" @returns The name of output path **/ public String getOutputPath() { return outputPath; } /** Set method of ANT task/datatype for attribute "OutputPath" @param outputPath The name of output path **/ public void setOutputPath(String outPutPath) { this.outputPath = outPutPath; } /** Get method of ANT task/datatype for attribute "ToolName" @returns The name of the tool. **/ public String getToolName() { return toolName; } /** Set method of ANT task/datatype for attribute "ToolName" @param toolName The name of the tool **/ public void setToolName(String toolName) { this.toolName = toolName; } /** Add method of ANT task/datatype for nested Input type of element @param file The Input objec which represents a file **/ public void addConfiguredInput(Input file) { inputFiles.insert(file); } // /** // addTool // // This function is to add instance of Tool to list. // // @param tool instance of Tool. // **/ // public void addTool(Tool tool){ // this.toolList.add(tool); public void addGenSection(GenSectionTask genSect){ this.gensectList.add(genSect); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: address.proto package ch.rasc.dataformat.proto; public final class AddressProtos { private AddressProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface AddressOrBuilder extends // @@protoc_insertion_point(interface_extends:Address) com.google.protobuf.MessageOrBuilder { /** * <code>uint32 id = 1;</code> */ int getId(); /** * <code>string lastName = 2;</code> */ java.lang.String getLastName(); /** * <code>string lastName = 2;</code> */ com.google.protobuf.ByteString getLastNameBytes(); /** * <code>string firstName = 3;</code> */ java.lang.String getFirstName(); /** * <code>string firstName = 3;</code> */ com.google.protobuf.ByteString getFirstNameBytes(); /** * <code>string street = 4;</code> */ java.lang.String getStreet(); /** * <code>string street = 4;</code> */ com.google.protobuf.ByteString getStreetBytes(); /** * <code>string zip = 5;</code> */ java.lang.String getZip(); /** * <code>string zip = 5;</code> */ com.google.protobuf.ByteString getZipBytes(); /** * <code>string city = 6;</code> */ java.lang.String getCity(); /** * <code>string city = 6;</code> */ com.google.protobuf.ByteString getCityBytes(); /** * <code>string country = 7;</code> */ java.lang.String getCountry(); /** * <code>string country = 7;</code> */ com.google.protobuf.ByteString getCountryBytes(); /** * <code>float lat = 8;</code> */ float getLat(); /** * <code>float lng = 9;</code> */ float getLng(); /** * <code>string email = 10;</code> */ java.lang.String getEmail(); /** * <code>string email = 10;</code> */ com.google.protobuf.ByteString getEmailBytes(); /** * <code>sint32 dob = 11;</code> */ int getDob(); } /** * Protobuf type {@code Address} */ public static final class Address extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:Address) AddressOrBuilder { private static final long serialVersionUID = 0L; // Use Address.newBuilder() to construct. private Address(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Address() { lastName_ = ""; firstName_ = ""; street_ = ""; zip_ = ""; city_ = ""; country_ = ""; email_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Address(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Address( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { id_ = input.readUInt32(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); lastName_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); firstName_ = s; break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); street_ = s; break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); zip_ = s; break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); city_ = s; break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); country_ = s; break; } case 69: { lat_ = input.readFloat(); break; } case 77: { lng_ = input.readFloat(); break; } case 82: { java.lang.String s = input.readStringRequireUtf8(); email_ = s; break; } case 88: { dob_ = input.readSInt32(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Address_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Address_fieldAccessorTable .ensureFieldAccessorsInitialized( ch.rasc.dataformat.proto.AddressProtos.Address.class, ch.rasc.dataformat.proto.AddressProtos.Address.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private int id_; /** * <code>uint32 id = 1;</code> */ public int getId() { return id_; } public static final int LASTNAME_FIELD_NUMBER = 2; private volatile java.lang.Object lastName_; /** * <code>string lastName = 2;</code> */ public java.lang.String getLastName() { java.lang.Object ref = lastName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastName_ = s; return s; } } /** * <code>string lastName = 2;</code> */ public com.google.protobuf.ByteString getLastNameBytes() { java.lang.Object ref = lastName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lastName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FIRSTNAME_FIELD_NUMBER = 3; private volatile java.lang.Object firstName_; /** * <code>string firstName = 3;</code> */ public java.lang.String getFirstName() { java.lang.Object ref = firstName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); firstName_ = s; return s; } } /** * <code>string firstName = 3;</code> */ public com.google.protobuf.ByteString getFirstNameBytes() { java.lang.Object ref = firstName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); firstName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STREET_FIELD_NUMBER = 4; private volatile java.lang.Object street_; /** * <code>string street = 4;</code> */ public java.lang.String getStreet() { java.lang.Object ref = street_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); street_ = s; return s; } } /** * <code>string street = 4;</code> */ public com.google.protobuf.ByteString getStreetBytes() { java.lang.Object ref = street_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); street_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ZIP_FIELD_NUMBER = 5; private volatile java.lang.Object zip_; /** * <code>string zip = 5;</code> */ public java.lang.String getZip() { java.lang.Object ref = zip_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); zip_ = s; return s; } } /** * <code>string zip = 5;</code> */ public com.google.protobuf.ByteString getZipBytes() { java.lang.Object ref = zip_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); zip_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CITY_FIELD_NUMBER = 6; private volatile java.lang.Object city_; /** * <code>string city = 6;</code> */ public java.lang.String getCity() { java.lang.Object ref = city_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); city_ = s; return s; } } /** * <code>string city = 6;</code> */ public com.google.protobuf.ByteString getCityBytes() { java.lang.Object ref = city_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); city_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int COUNTRY_FIELD_NUMBER = 7; private volatile java.lang.Object country_; /** * <code>string country = 7;</code> */ public java.lang.String getCountry() { java.lang.Object ref = country_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); country_ = s; return s; } } /** * <code>string country = 7;</code> */ public com.google.protobuf.ByteString getCountryBytes() { java.lang.Object ref = country_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); country_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LAT_FIELD_NUMBER = 8; private float lat_; /** * <code>float lat = 8;</code> */ public float getLat() { return lat_; } public static final int LNG_FIELD_NUMBER = 9; private float lng_; /** * <code>float lng = 9;</code> */ public float getLng() { return lng_; } public static final int EMAIL_FIELD_NUMBER = 10; private volatile java.lang.Object email_; /** * <code>string email = 10;</code> */ public java.lang.String getEmail() { java.lang.Object ref = email_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); email_ = s; return s; } } /** * <code>string email = 10;</code> */ public com.google.protobuf.ByteString getEmailBytes() { java.lang.Object ref = email_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); email_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DOB_FIELD_NUMBER = 11; private int dob_; /** * <code>sint32 dob = 11;</code> */ public int getDob() { return dob_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (id_ != 0) { output.writeUInt32(1, id_); } if (!getLastNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, lastName_); } if (!getFirstNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, firstName_); } if (!getStreetBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, street_); } if (!getZipBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, zip_); } if (!getCityBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, city_); } if (!getCountryBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, country_); } if (lat_ != 0F) { output.writeFloat(8, lat_); } if (lng_ != 0F) { output.writeFloat(9, lng_); } if (!getEmailBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 10, email_); } if (dob_ != 0) { output.writeSInt32(11, dob_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (id_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, id_); } if (!getLastNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, lastName_); } if (!getFirstNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, firstName_); } if (!getStreetBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, street_); } if (!getZipBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, zip_); } if (!getCityBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, city_); } if (!getCountryBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, country_); } if (lat_ != 0F) { size += com.google.protobuf.CodedOutputStream .computeFloatSize(8, lat_); } if (lng_ != 0F) { size += com.google.protobuf.CodedOutputStream .computeFloatSize(9, lng_); } if (!getEmailBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(10, email_); } if (dob_ != 0) { size += com.google.protobuf.CodedOutputStream .computeSInt32Size(11, dob_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ch.rasc.dataformat.proto.AddressProtos.Address)) { return super.equals(obj); } ch.rasc.dataformat.proto.AddressProtos.Address other = (ch.rasc.dataformat.proto.AddressProtos.Address) obj; if (getId() != other.getId()) return false; if (!getLastName() .equals(other.getLastName())) return false; if (!getFirstName() .equals(other.getFirstName())) return false; if (!getStreet() .equals(other.getStreet())) return false; if (!getZip() .equals(other.getZip())) return false; if (!getCity() .equals(other.getCity())) return false; if (!getCountry() .equals(other.getCountry())) return false; if (java.lang.Float.floatToIntBits(getLat()) != java.lang.Float.floatToIntBits( other.getLat())) return false; if (java.lang.Float.floatToIntBits(getLng()) != java.lang.Float.floatToIntBits( other.getLng())) return false; if (!getEmail() .equals(other.getEmail())) return false; if (getDob() != other.getDob()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId(); hash = (37 * hash) + LASTNAME_FIELD_NUMBER; hash = (53 * hash) + getLastName().hashCode(); hash = (37 * hash) + FIRSTNAME_FIELD_NUMBER; hash = (53 * hash) + getFirstName().hashCode(); hash = (37 * hash) + STREET_FIELD_NUMBER; hash = (53 * hash) + getStreet().hashCode(); hash = (37 * hash) + ZIP_FIELD_NUMBER; hash = (53 * hash) + getZip().hashCode(); hash = (37 * hash) + CITY_FIELD_NUMBER; hash = (53 * hash) + getCity().hashCode(); hash = (37 * hash) + COUNTRY_FIELD_NUMBER; hash = (53 * hash) + getCountry().hashCode(); hash = (37 * hash) + LAT_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits( getLat()); hash = (37 * hash) + LNG_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits( getLng()); hash = (37 * hash) + EMAIL_FIELD_NUMBER; hash = (53 * hash) + getEmail().hashCode(); hash = (37 * hash) + DOB_FIELD_NUMBER; hash = (53 * hash) + getDob(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ch.rasc.dataformat.proto.AddressProtos.Address parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ch.rasc.dataformat.proto.AddressProtos.Address prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Address} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Address) ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Address_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Address_fieldAccessorTable .ensureFieldAccessorsInitialized( ch.rasc.dataformat.proto.AddressProtos.Address.class, ch.rasc.dataformat.proto.AddressProtos.Address.Builder.class); } // Construct using ch.rasc.dataformat.proto.AddressProtos.Address.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); id_ = 0; lastName_ = ""; firstName_ = ""; street_ = ""; zip_ = ""; city_ = ""; country_ = ""; lat_ = 0F; lng_ = 0F; email_ = ""; dob_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Address_descriptor; } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Address getDefaultInstanceForType() { return ch.rasc.dataformat.proto.AddressProtos.Address.getDefaultInstance(); } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Address build() { ch.rasc.dataformat.proto.AddressProtos.Address result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Address buildPartial() { ch.rasc.dataformat.proto.AddressProtos.Address result = new ch.rasc.dataformat.proto.AddressProtos.Address(this); result.id_ = id_; result.lastName_ = lastName_; result.firstName_ = firstName_; result.street_ = street_; result.zip_ = zip_; result.city_ = city_; result.country_ = country_; result.lat_ = lat_; result.lng_ = lng_; result.email_ = email_; result.dob_ = dob_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ch.rasc.dataformat.proto.AddressProtos.Address) { return mergeFrom((ch.rasc.dataformat.proto.AddressProtos.Address)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ch.rasc.dataformat.proto.AddressProtos.Address other) { if (other == ch.rasc.dataformat.proto.AddressProtos.Address.getDefaultInstance()) return this; if (other.getId() != 0) { setId(other.getId()); } if (!other.getLastName().isEmpty()) { lastName_ = other.lastName_; onChanged(); } if (!other.getFirstName().isEmpty()) { firstName_ = other.firstName_; onChanged(); } if (!other.getStreet().isEmpty()) { street_ = other.street_; onChanged(); } if (!other.getZip().isEmpty()) { zip_ = other.zip_; onChanged(); } if (!other.getCity().isEmpty()) { city_ = other.city_; onChanged(); } if (!other.getCountry().isEmpty()) { country_ = other.country_; onChanged(); } if (other.getLat() != 0F) { setLat(other.getLat()); } if (other.getLng() != 0F) { setLng(other.getLng()); } if (!other.getEmail().isEmpty()) { email_ = other.email_; onChanged(); } if (other.getDob() != 0) { setDob(other.getDob()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ch.rasc.dataformat.proto.AddressProtos.Address parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ch.rasc.dataformat.proto.AddressProtos.Address) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int id_ ; /** * <code>uint32 id = 1;</code> */ public int getId() { return id_; } /** * <code>uint32 id = 1;</code> */ public Builder setId(int value) { id_ = value; onChanged(); return this; } /** * <code>uint32 id = 1;</code> */ public Builder clearId() { id_ = 0; onChanged(); return this; } private java.lang.Object lastName_ = ""; /** * <code>string lastName = 2;</code> */ public java.lang.String getLastName() { java.lang.Object ref = lastName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string lastName = 2;</code> */ public com.google.protobuf.ByteString getLastNameBytes() { java.lang.Object ref = lastName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); lastName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string lastName = 2;</code> */ public Builder setLastName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } lastName_ = value; onChanged(); return this; } /** * <code>string lastName = 2;</code> */ public Builder clearLastName() { lastName_ = getDefaultInstance().getLastName(); onChanged(); return this; } /** * <code>string lastName = 2;</code> */ public Builder setLastNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); lastName_ = value; onChanged(); return this; } private java.lang.Object firstName_ = ""; /** * <code>string firstName = 3;</code> */ public java.lang.String getFirstName() { java.lang.Object ref = firstName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); firstName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string firstName = 3;</code> */ public com.google.protobuf.ByteString getFirstNameBytes() { java.lang.Object ref = firstName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); firstName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string firstName = 3;</code> */ public Builder setFirstName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } firstName_ = value; onChanged(); return this; } /** * <code>string firstName = 3;</code> */ public Builder clearFirstName() { firstName_ = getDefaultInstance().getFirstName(); onChanged(); return this; } /** * <code>string firstName = 3;</code> */ public Builder setFirstNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); firstName_ = value; onChanged(); return this; } private java.lang.Object street_ = ""; /** * <code>string street = 4;</code> */ public java.lang.String getStreet() { java.lang.Object ref = street_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); street_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string street = 4;</code> */ public com.google.protobuf.ByteString getStreetBytes() { java.lang.Object ref = street_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); street_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string street = 4;</code> */ public Builder setStreet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } street_ = value; onChanged(); return this; } /** * <code>string street = 4;</code> */ public Builder clearStreet() { street_ = getDefaultInstance().getStreet(); onChanged(); return this; } /** * <code>string street = 4;</code> */ public Builder setStreetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); street_ = value; onChanged(); return this; } private java.lang.Object zip_ = ""; /** * <code>string zip = 5;</code> */ public java.lang.String getZip() { java.lang.Object ref = zip_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); zip_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string zip = 5;</code> */ public com.google.protobuf.ByteString getZipBytes() { java.lang.Object ref = zip_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); zip_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string zip = 5;</code> */ public Builder setZip( java.lang.String value) { if (value == null) { throw new NullPointerException(); } zip_ = value; onChanged(); return this; } /** * <code>string zip = 5;</code> */ public Builder clearZip() { zip_ = getDefaultInstance().getZip(); onChanged(); return this; } /** * <code>string zip = 5;</code> */ public Builder setZipBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); zip_ = value; onChanged(); return this; } private java.lang.Object city_ = ""; /** * <code>string city = 6;</code> */ public java.lang.String getCity() { java.lang.Object ref = city_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); city_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string city = 6;</code> */ public com.google.protobuf.ByteString getCityBytes() { java.lang.Object ref = city_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); city_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string city = 6;</code> */ public Builder setCity( java.lang.String value) { if (value == null) { throw new NullPointerException(); } city_ = value; onChanged(); return this; } /** * <code>string city = 6;</code> */ public Builder clearCity() { city_ = getDefaultInstance().getCity(); onChanged(); return this; } /** * <code>string city = 6;</code> */ public Builder setCityBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); city_ = value; onChanged(); return this; } private java.lang.Object country_ = ""; /** * <code>string country = 7;</code> */ public java.lang.String getCountry() { java.lang.Object ref = country_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); country_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string country = 7;</code> */ public com.google.protobuf.ByteString getCountryBytes() { java.lang.Object ref = country_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); country_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string country = 7;</code> */ public Builder setCountry( java.lang.String value) { if (value == null) { throw new NullPointerException(); } country_ = value; onChanged(); return this; } /** * <code>string country = 7;</code> */ public Builder clearCountry() { country_ = getDefaultInstance().getCountry(); onChanged(); return this; } /** * <code>string country = 7;</code> */ public Builder setCountryBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); country_ = value; onChanged(); return this; } private float lat_ ; /** * <code>float lat = 8;</code> */ public float getLat() { return lat_; } /** * <code>float lat = 8;</code> */ public Builder setLat(float value) { lat_ = value; onChanged(); return this; } /** * <code>float lat = 8;</code> */ public Builder clearLat() { lat_ = 0F; onChanged(); return this; } private float lng_ ; /** * <code>float lng = 9;</code> */ public float getLng() { return lng_; } /** * <code>float lng = 9;</code> */ public Builder setLng(float value) { lng_ = value; onChanged(); return this; } /** * <code>float lng = 9;</code> */ public Builder clearLng() { lng_ = 0F; onChanged(); return this; } private java.lang.Object email_ = ""; /** * <code>string email = 10;</code> */ public java.lang.String getEmail() { java.lang.Object ref = email_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); email_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string email = 10;</code> */ public com.google.protobuf.ByteString getEmailBytes() { java.lang.Object ref = email_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); email_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string email = 10;</code> */ public Builder setEmail( java.lang.String value) { if (value == null) { throw new NullPointerException(); } email_ = value; onChanged(); return this; } /** * <code>string email = 10;</code> */ public Builder clearEmail() { email_ = getDefaultInstance().getEmail(); onChanged(); return this; } /** * <code>string email = 10;</code> */ public Builder setEmailBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); email_ = value; onChanged(); return this; } private int dob_ ; /** * <code>sint32 dob = 11;</code> */ public int getDob() { return dob_; } /** * <code>sint32 dob = 11;</code> */ public Builder setDob(int value) { dob_ = value; onChanged(); return this; } /** * <code>sint32 dob = 11;</code> */ public Builder clearDob() { dob_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:Address) } // @@protoc_insertion_point(class_scope:Address) private static final ch.rasc.dataformat.proto.AddressProtos.Address DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ch.rasc.dataformat.proto.AddressProtos.Address(); } public static ch.rasc.dataformat.proto.AddressProtos.Address getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Address> PARSER = new com.google.protobuf.AbstractParser<Address>() { @java.lang.Override public Address parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Address(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Address> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Address> getParserForType() { return PARSER; } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Address getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AddressesOrBuilder extends // @@protoc_insertion_point(interface_extends:Addresses) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .Address address = 1;</code> */ java.util.List<ch.rasc.dataformat.proto.AddressProtos.Address> getAddressList(); /** * <code>repeated .Address address = 1;</code> */ ch.rasc.dataformat.proto.AddressProtos.Address getAddress(int index); /** * <code>repeated .Address address = 1;</code> */ int getAddressCount(); /** * <code>repeated .Address address = 1;</code> */ java.util.List<? extends ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder> getAddressOrBuilderList(); /** * <code>repeated .Address address = 1;</code> */ ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder getAddressOrBuilder( int index); } /** * Protobuf type {@code Addresses} */ public static final class Addresses extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:Addresses) AddressesOrBuilder { private static final long serialVersionUID = 0L; // Use Addresses.newBuilder() to construct. private Addresses(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Addresses() { address_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Addresses(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Addresses( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { address_ = new java.util.ArrayList<ch.rasc.dataformat.proto.AddressProtos.Address>(); mutable_bitField0_ |= 0x00000001; } address_.add( input.readMessage(ch.rasc.dataformat.proto.AddressProtos.Address.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { address_ = java.util.Collections.unmodifiableList(address_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Addresses_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Addresses_fieldAccessorTable .ensureFieldAccessorsInitialized( ch.rasc.dataformat.proto.AddressProtos.Addresses.class, ch.rasc.dataformat.proto.AddressProtos.Addresses.Builder.class); } public static final int ADDRESS_FIELD_NUMBER = 1; private java.util.List<ch.rasc.dataformat.proto.AddressProtos.Address> address_; /** * <code>repeated .Address address = 1;</code> */ public java.util.List<ch.rasc.dataformat.proto.AddressProtos.Address> getAddressList() { return address_; } /** * <code>repeated .Address address = 1;</code> */ public java.util.List<? extends ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder> getAddressOrBuilderList() { return address_; } /** * <code>repeated .Address address = 1;</code> */ public int getAddressCount() { return address_.size(); } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.Address getAddress(int index) { return address_.get(index); } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder getAddressOrBuilder( int index) { return address_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < address_.size(); i++) { output.writeMessage(1, address_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < address_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, address_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof ch.rasc.dataformat.proto.AddressProtos.Addresses)) { return super.equals(obj); } ch.rasc.dataformat.proto.AddressProtos.Addresses other = (ch.rasc.dataformat.proto.AddressProtos.Addresses) obj; if (!getAddressList() .equals(other.getAddressList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAddressCount() > 0) { hash = (37 * hash) + ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getAddressList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ch.rasc.dataformat.proto.AddressProtos.Addresses prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Addresses} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Addresses) ch.rasc.dataformat.proto.AddressProtos.AddressesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Addresses_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Addresses_fieldAccessorTable .ensureFieldAccessorsInitialized( ch.rasc.dataformat.proto.AddressProtos.Addresses.class, ch.rasc.dataformat.proto.AddressProtos.Addresses.Builder.class); } // Construct using ch.rasc.dataformat.proto.AddressProtos.Addresses.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getAddressFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (addressBuilder_ == null) { address_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { addressBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return ch.rasc.dataformat.proto.AddressProtos.internal_static_Addresses_descriptor; } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Addresses getDefaultInstanceForType() { return ch.rasc.dataformat.proto.AddressProtos.Addresses.getDefaultInstance(); } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Addresses build() { ch.rasc.dataformat.proto.AddressProtos.Addresses result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Addresses buildPartial() { ch.rasc.dataformat.proto.AddressProtos.Addresses result = new ch.rasc.dataformat.proto.AddressProtos.Addresses(this); int from_bitField0_ = bitField0_; if (addressBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { address_ = java.util.Collections.unmodifiableList(address_); bitField0_ = (bitField0_ & ~0x00000001); } result.address_ = address_; } else { result.address_ = addressBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof ch.rasc.dataformat.proto.AddressProtos.Addresses) { return mergeFrom((ch.rasc.dataformat.proto.AddressProtos.Addresses)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(ch.rasc.dataformat.proto.AddressProtos.Addresses other) { if (other == ch.rasc.dataformat.proto.AddressProtos.Addresses.getDefaultInstance()) return this; if (addressBuilder_ == null) { if (!other.address_.isEmpty()) { if (address_.isEmpty()) { address_ = other.address_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureAddressIsMutable(); address_.addAll(other.address_); } onChanged(); } } else { if (!other.address_.isEmpty()) { if (addressBuilder_.isEmpty()) { addressBuilder_.dispose(); addressBuilder_ = null; address_ = other.address_; bitField0_ = (bitField0_ & ~0x00000001); addressBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getAddressFieldBuilder() : null; } else { addressBuilder_.addAllMessages(other.address_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { ch.rasc.dataformat.proto.AddressProtos.Addresses parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (ch.rasc.dataformat.proto.AddressProtos.Addresses) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<ch.rasc.dataformat.proto.AddressProtos.Address> address_ = java.util.Collections.emptyList(); private void ensureAddressIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { address_ = new java.util.ArrayList<ch.rasc.dataformat.proto.AddressProtos.Address>(address_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< ch.rasc.dataformat.proto.AddressProtos.Address, ch.rasc.dataformat.proto.AddressProtos.Address.Builder, ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder> addressBuilder_; /** * <code>repeated .Address address = 1;</code> */ public java.util.List<ch.rasc.dataformat.proto.AddressProtos.Address> getAddressList() { if (addressBuilder_ == null) { return java.util.Collections.unmodifiableList(address_); } else { return addressBuilder_.getMessageList(); } } /** * <code>repeated .Address address = 1;</code> */ public int getAddressCount() { if (addressBuilder_ == null) { return address_.size(); } else { return addressBuilder_.getCount(); } } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.Address getAddress(int index) { if (addressBuilder_ == null) { return address_.get(index); } else { return addressBuilder_.getMessage(index); } } /** * <code>repeated .Address address = 1;</code> */ public Builder setAddress( int index, ch.rasc.dataformat.proto.AddressProtos.Address value) { if (addressBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAddressIsMutable(); address_.set(index, value); onChanged(); } else { addressBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder setAddress( int index, ch.rasc.dataformat.proto.AddressProtos.Address.Builder builderForValue) { if (addressBuilder_ == null) { ensureAddressIsMutable(); address_.set(index, builderForValue.build()); onChanged(); } else { addressBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder addAddress(ch.rasc.dataformat.proto.AddressProtos.Address value) { if (addressBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAddressIsMutable(); address_.add(value); onChanged(); } else { addressBuilder_.addMessage(value); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder addAddress( int index, ch.rasc.dataformat.proto.AddressProtos.Address value) { if (addressBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAddressIsMutable(); address_.add(index, value); onChanged(); } else { addressBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder addAddress( ch.rasc.dataformat.proto.AddressProtos.Address.Builder builderForValue) { if (addressBuilder_ == null) { ensureAddressIsMutable(); address_.add(builderForValue.build()); onChanged(); } else { addressBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder addAddress( int index, ch.rasc.dataformat.proto.AddressProtos.Address.Builder builderForValue) { if (addressBuilder_ == null) { ensureAddressIsMutable(); address_.add(index, builderForValue.build()); onChanged(); } else { addressBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder addAllAddress( java.lang.Iterable<? extends ch.rasc.dataformat.proto.AddressProtos.Address> values) { if (addressBuilder_ == null) { ensureAddressIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, address_); onChanged(); } else { addressBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder clearAddress() { if (addressBuilder_ == null) { address_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { addressBuilder_.clear(); } return this; } /** * <code>repeated .Address address = 1;</code> */ public Builder removeAddress(int index) { if (addressBuilder_ == null) { ensureAddressIsMutable(); address_.remove(index); onChanged(); } else { addressBuilder_.remove(index); } return this; } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.Address.Builder getAddressBuilder( int index) { return getAddressFieldBuilder().getBuilder(index); } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder getAddressOrBuilder( int index) { if (addressBuilder_ == null) { return address_.get(index); } else { return addressBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .Address address = 1;</code> */ public java.util.List<? extends ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder> getAddressOrBuilderList() { if (addressBuilder_ != null) { return addressBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(address_); } } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.Address.Builder addAddressBuilder() { return getAddressFieldBuilder().addBuilder( ch.rasc.dataformat.proto.AddressProtos.Address.getDefaultInstance()); } /** * <code>repeated .Address address = 1;</code> */ public ch.rasc.dataformat.proto.AddressProtos.Address.Builder addAddressBuilder( int index) { return getAddressFieldBuilder().addBuilder( index, ch.rasc.dataformat.proto.AddressProtos.Address.getDefaultInstance()); } /** * <code>repeated .Address address = 1;</code> */ public java.util.List<ch.rasc.dataformat.proto.AddressProtos.Address.Builder> getAddressBuilderList() { return getAddressFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< ch.rasc.dataformat.proto.AddressProtos.Address, ch.rasc.dataformat.proto.AddressProtos.Address.Builder, ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder> getAddressFieldBuilder() { if (addressBuilder_ == null) { addressBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< ch.rasc.dataformat.proto.AddressProtos.Address, ch.rasc.dataformat.proto.AddressProtos.Address.Builder, ch.rasc.dataformat.proto.AddressProtos.AddressOrBuilder>( address_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); address_ = null; } return addressBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:Addresses) } // @@protoc_insertion_point(class_scope:Addresses) private static final ch.rasc.dataformat.proto.AddressProtos.Addresses DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ch.rasc.dataformat.proto.AddressProtos.Addresses(); } public static ch.rasc.dataformat.proto.AddressProtos.Addresses getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Addresses> PARSER = new com.google.protobuf.AbstractParser<Addresses>() { @java.lang.Override public Addresses parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Addresses(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Addresses> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Addresses> getParserForType() { return PARSER; } @java.lang.Override public ch.rasc.dataformat.proto.AddressProtos.Addresses getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_Address_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Address_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_Addresses_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Addresses_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\raddress.proto\"\254\001\n\007Address\022\n\n\002id\030\001 \001(\r\022" + "\020\n\010lastName\030\002 \001(\t\022\021\n\tfirstName\030\003 \001(\t\022\016\n\006" + "street\030\004 \001(\t\022\013\n\003zip\030\005 \001(\t\022\014\n\004city\030\006 \001(\t\022" + "\017\n\007country\030\007 \001(\t\022\013\n\003lat\030\010 \001(\002\022\013\n\003lng\030\t \001" + "(\002\022\r\n\005email\030\n \001(\t\022\013\n\003dob\030\013 \001(\021\"&\n\tAddres" + "ses\022\031\n\007address\030\001 \003(\0132\010.AddressB)\n\030ch.ras" + "c.dataformat.protoB\rAddressProtosb\006proto" + "3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_Address_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Address_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Address_descriptor, new java.lang.String[] { "Id", "LastName", "FirstName", "Street", "Zip", "City", "Country", "Lat", "Lng", "Email", "Dob", }); internal_static_Addresses_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_Addresses_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Addresses_descriptor, new java.lang.String[] { "Address", }); } // @@protoc_insertion_point(outer_class_scope) }
package com.wakatime.intellij.plugin; import com.intellij.AppTopics; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.Messages; import com.intellij.util.PlatformUtils; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import org.apache.log4j.Level; public class WakaTime implements ApplicationComponent { public static final String VERSION = "4.0.2"; public static final String CONFIG = ".wakatime.cfg"; public static final long FREQUENCY = 2; // minutes between pings public static final Logger log = Logger.getInstance("WakaTime"); public static String IDE_NAME; public static String IDE_VERSION; public static MessageBusConnection connection; public static Boolean DEBUG = false; public static Boolean READY = false; public static String lastFile = null; public static long lastTime = 0; public WakaTime() { } public void initComponent() { log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)"); // Set runtime constants IDE_NAME = PlatformUtils.getPlatformPrefix(); IDE_VERSION = ApplicationInfo.getInstance().getFullVersion(); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (!Dependencies.isCLIInstalled()) { log.info("Downloading and installing wakatime-cli ..."); Dependencies.installCLI(); WakaTime.READY = true; log.info("Finished downloading and installing wakatime-cli."); } else if (Dependencies.isCLIOld()) { log.info("Upgrading wakatime-cli ..."); Dependencies.upgradeCLI(); WakaTime.READY = true; log.info("Finished upgrading wakatime-cli."); } else { WakaTime.READY = true; log.info("wakatime-cli is up to date."); } } }); } }); if (Dependencies.isPythonInstalled()) { WakaTime.DEBUG = WakaTime.isDebugEnabled(); if (WakaTime.DEBUG) { log.setLevel(Level.DEBUG); log.debug("Logging level set to DEBUG"); } log.debug("Python location: " + Dependencies.getPythonLocation()); log.debug("CLI location: " + Dependencies.getCLILocation()); // prompt for apiKey if it does not already exist if (ApiKey.getApiKey().equals("")) { Project project = ProjectManager.getInstance().getDefaultProject(); ApiKey apiKey = new ApiKey(project); apiKey.promptForApiKey(); } log.debug("Api Key: "+ApiKey.getApiKey()); // add WakaTime item to File menu ActionManager am = ActionManager.getInstance(); PluginMenu action = new PluginMenu(); am.registerAction("WakaTimeApiKey", action); DefaultActionGroup fileMenu = (DefaultActionGroup) am.getAction("FileMenu"); fileMenu.addSeparator(); fileMenu.add(action); // Setup message listeners MessageBus bus = ApplicationManager.getApplication().getMessageBus(); connection = bus.connect(); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener()); EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new CustomDocumentListener()); log.info("Finished initializing WakaTime plugin"); } else { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { log.info("Python not found, downloading python..."); // download and install python Dependencies.installPython(); if (Dependencies.isPythonInstalled()) { log.info("Finished installing python..."); } else { Messages.showErrorDialog("WakaTime requires Python to be installed.\nYou can install it from https: } } }); } }); } } public void disposeComponent() { try { connection.disconnect(); } catch(Exception e) { } } public static void logFile(String file, boolean isWrite) { if (WakaTime.READY) { WakaTime.executeCLI(file, isWrite, 0); } } public static void executeCLI(String file, boolean isWrite, int tries) { ArrayList<String> cmds = new ArrayList<String>(); cmds.add(Dependencies.getPythonLocation()); cmds.add(Dependencies.getCLILocation()); cmds.add("--key"); cmds.add(ApiKey.getApiKey()); cmds.add("--file"); cmds.add(file); String project = WakaTime.getProjectName(); if (project != null) { cmds.add("--project"); cmds.add(project); } cmds.add("--plugin"); cmds.add(IDE_NAME+"/"+IDE_VERSION+" "+IDE_NAME+"-wakatime/"+VERSION); if (isWrite) cmds.add("--write"); try { log.debug("Executing CLI: " + Arrays.toString(cmds.toArray())); Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()])); if (WakaTime.DEBUG) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdInput.readLine()) != null) { log.debug(s); } while ((s = stdError.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: "+proc.exitValue()); } } catch (Exception e) { if (tries < 3) { log.debug(e); try { Thread.sleep(30); } catch (InterruptedException e1) { log.error(e1); } WakaTime.executeCLI(file, isWrite, tries+1); } else { log.error(e); } } } public static String getProjectName() { DataContext dataContext = DataManager.getInstance().getDataContext(); if (dataContext != null) { Project project = null; try { project = PlatformDataKeys.PROJECT.getData(dataContext); } catch (NoClassDefFoundError e) { try { project = DataKeys.PROJECT.getData(dataContext); } catch (NoClassDefFoundError ex) { } } if (project != null) { return project.getName(); } } return null; } public static boolean enoughTimePassed(long currentTime) { return WakaTime.lastTime + FREQUENCY * 60 < currentTime; } public static Boolean isDebugEnabled() { Boolean debug = false; File userHome = new File(System.getProperty("user.home")); File configFile = new File(userHome, WakaTime.CONFIG); BufferedReader br = null; try { br = new BufferedReader(new FileReader(configFile.getAbsolutePath())); } catch (FileNotFoundException e1) {} if (br != null) { try { String line = br.readLine(); while (line != null) { String[] parts = line.split("="); if (parts.length == 2 && parts[0].trim().equals("debug") && parts[1].trim().toLowerCase().equals("true")) { debug = true; } line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return debug; } @NotNull public String getComponentName() { return "WakaTime"; } }
package nz.ac.auckland.view; import org.apache.log4j.Logger; import java.io.File; import java.io.IOException; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.stage.FileChooser; public class RootLayoutController extends VIDEVOXController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(RootLayoutController.class); public static final String PREVIEW = "preview"; public static final String EDITOR = "editor"; @FXML private Button _previewButton; @FXML private Button _editorButton; @FXML private void selectVideo() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Please select a video file to work on"); // Set visible extensions FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Video Files ", "*.mp4"); fileChooser.getExtensionFilters().add(extFilter); File file; file = fileChooser.showOpenDialog(_application.getStage()); if (file == null) { // User canceled selecting video return; } logger.debug("Video name: " + file.getName()); // set the video } @FXML private void close() { _application.saveAndClose(); } @FXML private void editorButtonAction() { setViewToggle(EDITOR); } @FXML private void previewButtonAction() { setViewToggle(PREVIEW); } public void setViewToggle(String option) { switch (option) { case PREVIEW: _editorButton.setDisable(false); _previewButton.setDisable(true); break; case EDITOR: _previewButton.setDisable(false); _editorButton.setDisable(true); break; default: } } }
package com.podio.sdk.domain.field; import com.podio.sdk.domain.Profile; import com.podio.sdk.domain.Space; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class ContactField extends Field<ContactField.Value> { private static class Settings { private final String type = null; private final String[] valid_types = null; } public static class Configuration extends Field.Configuration { public enum Type { space_contacts, space_users, all_users, undefined; public static Type fromString(String string) { try { return Type.valueOf(string); } catch (IllegalArgumentException e) { return Type.undefined; } catch (NullPointerException e) { return Type.undefined; } } } private final Value default_value = null; private final Settings settings = null; public Value getDefaultValue() { return default_value; } public Type getType() { return settings != null ? Type.fromString(settings.type) : Type.undefined; } public List<String> getValidTypes() { return settings != null && settings.valid_types != null ? Arrays.asList(settings.valid_types) : Arrays.asList(new String[0]); } } public static class Value extends Field.Value { protected static abstract class CreateData { protected String type; /** * Enumerates the supported types of contacts that can be added to a contact field */ enum CreateDataTypes { user, profile, space } protected CreateData() { //do nothing } public CreateData(CreateDataTypes type) { this.type = type.name(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CreateData that = (CreateData) o; return !(type != null ? !type.equals(that.type) : that.type != null); } @Override public int hashCode() { return type != null ? type.hashCode() : 0; } } protected static class ContactCreateData extends CreateData { private long id; public ContactCreateData(long id, CreateData.CreateDataTypes type) { super(type); this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ContactCreateData that = (ContactCreateData) o; return id == that.id; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (id ^ (id >>> 32)); return result; } } private final Profile value; protected CreateData createData; protected Value() { value = null; } /** * Create a contact field value based on a profile object * * @param profile */ public Value(Profile profile) { this.value = profile; createData = new ContactCreateData(profile.getId(), CreateData.CreateDataTypes.profile); } /** * Create a contact field value based on a space object * * @param space */ public Value(Space space) { value = null; createData = new ContactCreateData(space.getSpaceId(), CreateData.CreateDataTypes.space); } @Override public Map<String, Object> getCreateData() { HashMap<String, Object> data = new HashMap<String, Object>(); if (createData != null) { data.put("value", createData); } else if (value != null) { data.put("value", value.getId()); } else { data = null; } return data; } public String getExternalId() { return value != null ? value.getExternalId() : null; } public Profile getProfile() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Value value1 = (Value) o; if (value != null ? !value.equals(value1.value) : value1.value != null) return false; //in this case we don't care to check on the create data if(value.equals(value1.value)) return true; return !(createData != null ? !createData.equals(value1.createData) : value1.createData != null); } @Override public int hashCode() { int result = value != null ? value.hashCode() : 0; result = 31 * result + (createData != null ? createData.hashCode() : 0); return result; } } // Private fields private final Configuration config = null; private final ArrayList<Value> values; public ContactField(String externalId) { super(externalId); this.values = new ArrayList<Value>(); } @Override public void setValues(List<Value> values) { this.values.clear(); this.values.addAll(values); } @Override public void addValue(Value value) { if (values != null && !values.contains(value)) { values.add(value); } } @Override public Value getValue(int index) { return values != null ? values.get(index) : null; } @Override public List<Value> getValues() { return values; } @Override public void removeValue(Value value) { if (values != null && values.contains(value)) { values.remove(value); } } @Override public void clearValues() { values.clear(); } @Override public int valuesCount() { return values != null ? values.size() : 0; } public Configuration getConfiguration() { return config; } }
package com.heaven7.java.visitor.util; /** * help we handle version info * @author heaven7 * @since 1.1.2 */ //not opened. /*public*/ final class JDKVersion { private static final String VERSION; static { VERSION = System.getProperty("java.version"); } public static boolean isJdK18() { return VERSION != null && VERSION.startsWith("1.8"); } /*public static void main(String[] args) { System.out.println(isJdK18()); }*/ }
package com.bio4j.angulillos; import java.util.stream.Stream; import java.util.Optional; public interface TypedElementIndex < // element E extends TypedElement<E,ET,G,I,RV,RVT,RE,RET>, ET extends TypedElement.Type<E,ET,G,I,RV,RVT,RE,RET>, // property P extends Property<E,ET,P,V,G,I,RV,RVT,RE,RET>, V, // graph G extends TypedGraph<G,I,RV,RVT,RE,RET>, I extends UntypedGraph<RV,RVT,RE,RET>, RV,RVT, RE,RET > { /* get the indexed property. */ P property(); public enum ComparePredicate { EQUAL, GREATER_THAN, GREATER_THAN_EQUAL, LESS_THAN, LESS_THAN_EQUAL, NOT_EQUAL; } /* query this index by the property value */ Stream<E> query(ComparePredicate predicate, V value); /* This interface declares that this index is over a property that uniquely classifies a element type for exact match queries; it adds the method `getTypedElement` for that. */ public interface Unique < // element E extends TypedElement<E,ET,G,I,RV,RVT,RE,RET>, ET extends TypedElement.Type<E,ET,G,I,RV,RVT,RE,RET>, // property P extends Property<E,ET,P,V,G,I,RV,RVT,RE,RET>, V, // graph G extends TypedGraph<G,I,RV,RVT,RE,RET>, I extends UntypedGraph<RV,RVT,RE,RET>, RV,RVT, RE,RET > extends TypedElementIndex<E,ET, P,V, G, I,RV,RVT,RE,RET> { /* get a element by providing a value of the indexed property. The default implementation relies on `query`. */ default Optional<E> getElement(V byValue) { return query(ComparePredicate.EQUAL, byValue).findFirst(); } } /* This interface declares that this index is over a property that classifies lists of elements for exact match queries; it adds the method `getTypedElements` for that. */ public interface List < // element E extends TypedElement<E,ET,G,I,RV,RVT,RE,RET>, ET extends TypedElement.Type<E,ET,G,I,RV,RVT,RE,RET>, // property P extends Property<E,ET,P,V,G,I,RV,RVT,RE,RET>, V, // graph G extends TypedGraph<G,I,RV,RVT,RE,RET>, I extends UntypedGraph<RV,RVT,RE,RET>, RV,RVT, RE,RET > extends TypedElementIndex<E,ET, P,V, G, I,RV,RVT,RE,RET> { /* get a list of elements by providing a value of the property. The default ... */ default Stream<E> getElements(V byValue) { return query(ComparePredicate.EQUAL, byValue); } } }
package edu.wustl.catissuecore.actionForm; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.domain.CellSpecimen; import edu.wustl.catissuecore.domain.DistributedItem; import edu.wustl.catissuecore.domain.Distribution; import edu.wustl.catissuecore.domain.FluidSpecimen; import edu.wustl.catissuecore.domain.MolecularSpecimen; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.TissueSpecimen; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; /** * * Description: This Class handles the Distribution.. */ public class DistributionForm extends SpecimenEventParametersForm { //private String fromSite; private String toSite; private int counter=1; private String distributionProtocolId; private boolean idChange = false; private int rowNo=0; /** * Map to handle values of all Events */ protected Map values = new HashMap(); public int getFormId() { return Constants.DISTRIBUTION_FORM_ID; } public void setAllValues(AbstractDomainObject abstractDomain) { super.setAllValues(abstractDomain); Logger.out.debug("setAllValues of DistributionForm"); Distribution distributionObject = (Distribution)abstractDomain ; this.distributionProtocolId = String.valueOf(distributionObject.getDistributionProtocol().getId()); //this.fromSite = String.valueOf(distributionObject.getFromSite().getId()); this.toSite = String.valueOf(distributionObject.getToSite().getId()); this.activityStatus = Utility.toString(distributionObject.getActivityStatus()); Logger.out.debug("this.activityStatus "+this.activityStatus); Collection distributedItemCollection = distributionObject.getDistributedItemCollection(); if(distributedItemCollection != null) { values = new HashMap(); Iterator it = distributedItemCollection.iterator(); int i=1; while(it.hasNext()) { String key1 = "DistributedItem:"+i+"_systemIdentifier"; String key2 = "DistributedItem:"+i+"_Specimen_systemIdentifier"; String key3 = "DistributedItem:"+i+"_quantity"; String key4 = "DistributedItem:"+i+"_unitSpan"; String key5 = "DistributedItem:"+i+"_tissueSite"; String key6 = "DistributedItem:"+i+"_tissueSide"; String key7 = "DistributedItem:"+i+"_pathologicalStatus"; String key8 = "DistributedItem:"+i+"_Specimen_className"; String key9 = "DistributedItem:"+i+"_availableQty"; String key10 = "DistributedItem:"+i+"_previousQuantity"; String key11 = "DistributedItem:"+i+"_Specimen_type"; DistributedItem dItem = (DistributedItem)it.next(); Specimen specimen =dItem.getSpecimen(); String unit= getUnitSpan(specimen); Double quantity = dItem.getQuantity(); //dItem.setPreviousQty(quantity); values.put(key1,Utility.toString(dItem.getSystemIdentifier())); values.put(key2,Utility.toString(specimen.getSystemIdentifier())); values.put(key3,quantity); values.put(key4,unit); values.put(key5,specimen.getSpecimenCharacteristics().getTissueSite()); values.put(key6,specimen.getSpecimenCharacteristics().getTissueSide()); values.put(key7,specimen.getSpecimenCharacteristics().getPathologicalStatus()); values.put(key8,specimen.getClassName()); values.put(key9,getAvailableQty(specimen)); values.put(key10,quantity); values.put(key11,specimen.getType()); i++; } Logger.out.debug("Display Map Values"+values); counter = distributedItemCollection.size(); } //At least one row should be displayed in ADD MORE therefore if(counter == 0) counter = 1; } public void setAllVal(Object obj) { edu.wustl.catissuecore.domainobject.Distribution distributionObject = (edu.wustl.catissuecore.domainobject.Distribution)obj; super.setAllVal(distributionObject); Logger.out.debug("setAllValues of DistributionForm"); this.distributionProtocolId = String.valueOf(distributionObject.getDistributionProtocol().getId()); //this.fromSite = String.valueOf(distributionObject.getFromSite().getId()); this.toSite = String.valueOf(distributionObject.getToSite().getId()); this.activityStatus = Utility.toString(distributionObject.getActivityStatus()); Logger.out.debug("this.activityStatus "+this.activityStatus); Collection distributedItemCollection = distributionObject.getDistributedItemCollection(); if(distributedItemCollection != null) { values = new HashMap(); Iterator it = distributedItemCollection.iterator(); int i=1; while(it.hasNext()) { String key1 = "DistributedItem:"+i+"_systemIdentifier"; String key2 = "DistributedItem:"+i+"_Specimen_systemIdentifier"; String key3 = "DistributedItem:"+i+"_quantity"; String key4 = "DistributedItem:"+i+"_unitSpan"; String key5 = "DistributedItem:"+i+"_tissueSite"; String key6 = "DistributedItem:"+i+"_tissueSide"; String key7 = "DistributedItem:"+i+"_pathologicalStatus"; String key8 = "DistributedItem:"+i+"_Specimen_className"; String key9 = "DistributedItem:"+i+"_availableQty"; String key10 = "DistributedItem:"+i+"_previousQuantity"; String key11 = "DistributedItem:"+i+"_Specimen_type"; edu.wustl.catissuecore.domainobject.DistributedItem dItem = (edu.wustl.catissuecore.domainobject.DistributedItem)it.next(); edu.wustl.catissuecore.domainobject.Specimen specimen =dItem.getSpecimen(); String unit= getDomainObjectUnitSpan(specimen); Double quantity = dItem.getQuantity(); //dItem.setPreviousQty(quantity); values.put(key1,Utility.toString(dItem.getId())); values.put(key2,Utility.toString(specimen.getId())); values.put(key3,Utility.toString(quantity)); values.put(key4,Utility.toString(unit)); values.put(key5,specimen.getSpecimenCharacteristics().getTissueSite()); values.put(key6,specimen.getSpecimenCharacteristics().getTissueSide()); values.put(key7,specimen.getSpecimenCharacteristics().getPathologicalStatus()); values.put(key8,getDomainObjectClassName(specimen)); values.put(key9,Utility.toString(getDomainObjectAvailableQty(specimen))); values.put(key10,Utility.toString(quantity)); values.put(key11,specimen.getType()); i++; } Logger.out.debug("Display Map Values"+values); counter = distributedItemCollection.size(); } //At least one row should be displayed in ADD MORE therefore if(counter == 0) counter = 1; } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { //ActionErrors errors = super.validate(mapping, request); ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); Logger.out.debug("Inside validate function"); if (!validator.isValidOption(""+userId)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue("distribution.distributedBy"))); } // date validation according to bug id 722 and 730 String errorKey = validator.validateDate(dateOfEvent,true ); if(errorKey.trim().length() >0 ) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(errorKey,ApplicationProperties.getValue("eventparameters.dateofevent"))); } if(!validator.isValidOption(distributionProtocolId)) { Logger.out.debug("dist prot"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue("distribution.protocol"))); } // if(!validator.isValidOption(fromSite)) // Logger.out.debug("from site"); // errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue("distribution.fromSite"))); if(!validator.isValidOption(toSite)) { Logger.out.debug("to site"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue("distribution.toSite"))); } //Validations for Add-More Block if (this.values.keySet().isEmpty()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.one.item.required",ApplicationProperties.getValue("distribution.distributedItem"))); } Iterator it = this.values.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); String value = (String)values.get(key); if(key.indexOf("Specimen_systemIdentifier")!=-1 && !validator.isValidOption( value)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue("itemrecord.specimenId"))); } if(key.indexOf("_quantity")!=-1 ) { if((validator.isEmpty(value) )) { Logger.out.debug("Quantity empty**************"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue("itemrecord.quantity"))); } else if(!validator.isDouble(value)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue("itemrecord.quantity"))); } } //} if quantity } return errors; } /** * @return Returns the distributionProtocolId. */ public String getDistributionProtocolId() { return distributionProtocolId; } /** * @param distributionProtocolId The distributionProtocolId to set. */ public void setDistributionProtocolId(String distributionProtocolId) { this.distributionProtocolId = distributionProtocolId; } // /** // * @return fromSite // */ // public String getFromSite() { // return fromSite; // /** // * @param fromSite // */ // public void setFromSite(String fromSite) { // this.fromSite = fromSite; /** * @return */ public int getCounter() { return counter; } /** * @param counter The counter to set. */ public void setCounter(int counter) { this.counter = counter; } public String getToSite() { return toSite; } /** * @param toSite */ public void setToSite(String toSite) { this.toSite = toSite; } /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValue(String key, Object value) { if (isMutable()) values.put(key, value); } /** * Returns the object to which this map maps the specified key. * * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getValue(String key) { return values.get(key); } /** * @param values The values to set. */ public void setValues(Map values) { this.values = values; } /** * @return */ public Map getValues() { return values; } protected void reset() { // super.reset(); // this.distributionProtocolId = null; // this.fromSite = null; // this.toSite = null; // this.counter =1; } /** * @return Returns the idChange. */ public boolean isIdChange() { return idChange; } /** * @param idChange The idChange to set. */ public void setIdChange(boolean idChange) { this.idChange = idChange; } /** * @return Returns the rowNo. */ public int getRowNo() { return rowNo; } /** * @param rowNo The rowNo to set. */ public void setRowNo(int rowNo) { this.rowNo = rowNo; } private static String getUnitSpan(Specimen specimen) { if(specimen instanceof TissueSpecimen) { return Constants.UNIT_GM; } else if(specimen instanceof CellSpecimen) { return Constants.UNIT_CC; } else if(specimen instanceof MolecularSpecimen) { return Constants.UNIT_MG; } else if(specimen instanceof FluidSpecimen) { return Constants.UNIT_ML; } return null; } /** * This method returns UnitSpan for edu.wustl.catissuecore.domainobject.Specimen */ private static String getDomainObjectUnitSpan(edu.wustl.catissuecore.domainobject.Specimen specimen) { if(specimen instanceof edu.wustl.catissuecore.domainobject.TissueSpecimen) { return Constants.UNIT_GM; } else if(specimen instanceof edu.wustl.catissuecore.domainobject.CellSpecimen) { return Constants.UNIT_CC; } else if(specimen instanceof edu.wustl.catissuecore.domainobject.MolecularSpecimen) { return Constants.UNIT_MG; } else if(specimen instanceof edu.wustl.catissuecore.domainobject.FluidSpecimen) { return Constants.UNIT_ML; } return null; } public Object getAvailableQty(Specimen specimen) { //Retrieve the Available quantity for the particular specimen if(specimen instanceof TissueSpecimen) { TissueSpecimen tissueSpecimen = (TissueSpecimen) specimen; Logger.out.debug("tissueSpecimenAvailableQuantityInGram "+tissueSpecimen.getAvailableQuantityInGram()); return tissueSpecimen.getAvailableQuantityInGram(); } else if(specimen instanceof CellSpecimen) { CellSpecimen cellSpecimen = (CellSpecimen) specimen; return cellSpecimen.getAvailableQuantityInCellCount(); } else if(specimen instanceof MolecularSpecimen) { MolecularSpecimen molecularSpecimen = (MolecularSpecimen) specimen; return molecularSpecimen.getAvailableQuantityInMicrogram(); } else if(specimen instanceof FluidSpecimen) { FluidSpecimen fluidSpecimen = (FluidSpecimen) specimen; return fluidSpecimen.getAvailableQuantityInMilliliter(); } return null; } /** * This method returns AvailableQunatity for edu.wustl.catissuecore.domainobject.Specimen */ public Object getDomainObjectAvailableQty(edu.wustl.catissuecore.domainobject.Specimen specimen) { //Retrieve the Available quantity for the particular specimen if(specimen instanceof edu.wustl.catissuecore.domainobject.TissueSpecimen) { edu.wustl.catissuecore.domainobject.TissueSpecimen tissueSpecimen = (edu.wustl.catissuecore.domainobject.TissueSpecimen) specimen; Logger.out.debug("tissueSpecimenAvailableQuantityInGram "+tissueSpecimen.getAvailableQuantityInGram()); return tissueSpecimen.getAvailableQuantityInGram(); } else if(specimen instanceof edu.wustl.catissuecore.domainobject.CellSpecimen) { edu.wustl.catissuecore.domainobject.CellSpecimen cellSpecimen = (edu.wustl.catissuecore.domainobject.CellSpecimen) specimen; return cellSpecimen.getAvailableQuantityInCellCount(); } else if(specimen instanceof edu.wustl.catissuecore.domainobject.MolecularSpecimen) { edu.wustl.catissuecore.domainobject.MolecularSpecimen molecularSpecimen = (edu.wustl.catissuecore.domainobject.MolecularSpecimen) specimen; return molecularSpecimen.getAvailableQuantityInMicrogram(); } else if(specimen instanceof edu.wustl.catissuecore.domainobject.FluidSpecimen) { edu.wustl.catissuecore.domainobject.FluidSpecimen fluidSpecimen = (edu.wustl.catissuecore.domainobject.FluidSpecimen) specimen; return fluidSpecimen.getAvailableQuantityInMilliliter(); } return null; } /** * This method returns ClassName for edu.wustl.catissuecore.domainobject.Specimen */ public final String getDomainObjectClassName(edu.wustl.catissuecore.domainobject.Specimen specimen) { String className = null; if(specimen instanceof edu.wustl.catissuecore.domainobject.CellSpecimen) { className = "Cell"; } else if(specimen instanceof edu.wustl.catissuecore.domainobject.MolecularSpecimen) { className = "Molecular"; } else if(specimen instanceof edu.wustl.catissuecore.domainobject.FluidSpecimen) { className = "Fluid"; } else if(specimen instanceof edu.wustl.catissuecore.domainobject.TissueSpecimen) { className = "Tissue"; } return className; } }
package org.jaudiotagger.audio.flac; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.tag.TagFieldKey; import org.jaudiotagger.tag.reference.PictureTypes; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import org.jaudiotagger.tag.flac.FlacTag; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.generic.Utils; import org.jaudiotagger.audio.flac.metadatablock.MetadataBlockDataPicture; import java.io.File; import java.awt.image.BufferedImage; import junit.framework.TestCase; import javax.imageio.ImageIO; /** * basic Flac tests */ public class FlacHeaderTest extends TestCase { public void testReadFileWithVorbisComment() { Exception exceptionCaught = null; try { File testFile = AbstractTestCase.copyAudioToTmp("test.flac"); AudioFile f = AudioFileIO.read(testFile); assertEquals("192",f.getAudioHeader().getBitRate()); assertEquals("FLAC 16 bits",f.getAudioHeader().getEncodingType()); assertEquals("2",f.getAudioHeader().getChannels()); assertEquals("44100",f.getAudioHeader().getSampleRate()); assertTrue(f.getTag() instanceof FlacTag); FlacTag tag = (FlacTag)f.getTag(); FlacInfoReader infoReader = new FlacInfoReader(); assertEquals(6,infoReader.countMetaBlocks(f.getFile())); //Ease of use methods for common fields assertEquals("Artist", tag.getFirstArtist()); assertEquals("Album", tag.getFirstAlbum()); assertEquals("test3", tag.getFirstTitle()); assertEquals("comments", tag.getFirstComment()); assertEquals("1971", tag.getFirstYear()); assertEquals("4", tag.getFirstTrack()); assertEquals("Crossover", tag.getFirstGenre()); //Lookup by generickey assertEquals("Artist", tag.getFirst(TagFieldKey.ARTIST)); assertEquals("Album", tag.getFirst(TagFieldKey.ALBUM)); assertEquals("test3", tag.getFirst(TagFieldKey.TITLE)); assertEquals("comments", tag.getFirst(TagFieldKey.COMMENT)); assertEquals("1971", tag.getFirst(TagFieldKey.YEAR)); assertEquals("4", tag.getFirst(TagFieldKey.TRACK)); assertEquals("Composer", tag.getFirst(TagFieldKey.COMPOSER)); //Images assertEquals(2,tag.get(TagFieldKey.COVER_ART).size()); assertEquals(2,tag.get(TagFieldKey.COVER_ART.name()).size()); assertEquals(2,tag.getImages().size()); //Image MetadataBlockDataPicture image = tag.getImages().get(0); assertEquals((int) PictureTypes.DEFAULT_ID,(int)image.getPictureType()); assertEquals("image/png",image.getMimeType()); assertFalse(image.isImageUrl()); assertEquals("", image.getImageUrl()); assertEquals("",image.getDescription()); assertEquals(0,image.getWidth()); assertEquals(0,image.getHeight()); assertEquals(0,image.getColourDepth()); assertEquals(0,image.getIndexedColourCount()); assertEquals(18545,image.getImageData().length); //Image Link image = tag.getImages().get(1); assertEquals(7,(int)image.getPictureType()); assertEquals("-->",image.getMimeType()); assertTrue(image.isImageUrl()); assertEquals("coverart.gif", Utils.getString(image.getImageData(),0,image.getImageData().length, TextEncoding.CHARSET_ISO_8859_1)); assertEquals("coverart.gif", image.getImageUrl()); //Create Image Link tag.getImages().add((MetadataBlockDataPicture)tag.createLinkedArtworkField("../testdata/coverart.jpg")); f.commit(); f = AudioFileIO.read(testFile); image = tag.getImages().get(2); assertEquals(3,(int)image.getPictureType()); assertEquals("-->",image.getMimeType()); assertTrue(image.isImageUrl()); assertEquals("../testdata/coverart.jpg", Utils.getString(image.getImageData(),0,image.getImageData().length, TextEncoding.CHARSET_ISO_8859_1)); assertEquals("../testdata/coverart.jpg", image.getImageUrl()); //Can we actually create Buffered Image from the url of course remember url is relative to the audio file //not where we run the program from File file = new File("testdatatmp", image.getImageUrl()); assertTrue(file.exists()); BufferedImage bi = ImageIO.read(file); assertEquals(200,bi.getWidth()); assertEquals(200,bi.getHeight()); } catch(Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); } /** * Only contains vorbis comment with minimum encoder info */ public void testReadFileWithOnlyVorbisCommentEncoder() { Exception exceptionCaught = null; try { File testFile = AbstractTestCase.copyAudioToTmp("test2.flac"); AudioFile f = AudioFileIO.read(testFile); assertEquals("192",f.getAudioHeader().getBitRate()); assertEquals("FLAC 16 bits",f.getAudioHeader().getEncodingType()); assertEquals("2",f.getAudioHeader().getChannels()); assertEquals("44100",f.getAudioHeader().getSampleRate()); assertTrue(f.getTag() instanceof FlacTag); FlacTag tag = (FlacTag)f.getTag(); FlacInfoReader infoReader = new FlacInfoReader(); assertEquals(4,infoReader.countMetaBlocks(f.getFile())); //No Images assertEquals(0,tag.getImages().size()); } catch(Exception e) { e.printStackTrace(); exceptionCaught = e; } assertNull(exceptionCaught); } }
package com.cisco.trex.stateless; import com.cisco.trex.stateless.model.RPCResponse; import com.cisco.trex.stateless.util.IDataCompressor; import com.cisco.trex.stateless.util.TRexDataCompressor; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZMQ; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TRexTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TRexTransport.class); public static final int DEFAULT_TIMEOUT = 3000; private final String connectionString; private final IDataCompressor dataCompressor; private ZMQ.Context zmqCtx = ZMQ.context(1); private ZMQ.Socket zmqSocket; private String protocol = "tcp"; private String host; private String port; public TRexTransport(String host, String port, int timeout, IDataCompressor dataCompressor) { this.host = host; this.port = port; zmqSocket = zmqCtx.socket(ZMQ.REQ); int actualTimeout = timeout <= 0 ? DEFAULT_TIMEOUT : timeout; zmqSocket.setReceiveTimeOut(actualTimeout); zmqSocket.setSendTimeOut(actualTimeout); connectionString = protocol + "://"+ this.host +":" + this.port; zmqSocket.connect(connectionString); this.dataCompressor = dataCompressor; } public TRexTransport(String host, String port, int timeout) { this(host, port, timeout, new TRexDataCompressor()); } public RPCResponse sendCommand(TRexCommand command) throws IOException { String json = new ObjectMapper().writeValueAsString(command.getParameters()); String response = sendJson(json); ObjectMapper objectMapper = new ObjectMapper(); if (objectMapper.readTree(response).isArray()) { // for versions of TRex before v2.61, single entry response also wrapped with json array RPCResponse[] rpcResult = objectMapper.readValue(response, RPCResponse[].class); return rpcResult[0]; } return objectMapper.readValue(response, RPCResponse.class); } public RPCResponse[] sendCommands(List<TRexCommand> commands) throws IOException { if (commands.size() == 1) { return new RPCResponse[] {sendCommand(commands.get(0))}; } List<Map<String, Object>> commandList = commands.stream().map(TRexCommand::getParameters).collect(Collectors.toList()); if (commandList.isEmpty()) { return new RPCResponse[0]; } String json = new ObjectMapper().writeValueAsString(commandList); String response = sendJson(json); return new ObjectMapper().readValue(response, RPCResponse[].class); } public String getHost() { return host; } public String getPort() { return port; } synchronized public void close() { zmqSocket.disconnect(connectionString); zmqSocket.close(); zmqCtx.close(); } public ZMQ.Socket getSocket() { return zmqSocket; } synchronized public String sendJson(String json) { LOGGER.debug("JSON Req: " + json); byte[] compressed = this.dataCompressor.compressStringToBytes(json); zmqSocket.send(compressed); byte[] msg = zmqSocket.recv(); String response = this.dataCompressor.decompressBytesToString(msg); LOGGER.debug("JSON Resp: " + response); return response; } }
package com.raizlabs.net.requests; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.message.BasicNameValuePair; import android.util.Log; import com.raizlabs.baseutils.IOUtils; import com.raizlabs.baseutils.Logger; import com.raizlabs.events.ProgressListener; import com.raizlabs.net.HttpMethod; import com.raizlabs.net.ProgressInputStreamEntity; import com.raizlabs.net.webservicemanager.BuildConfig; /** * Builder class which allows for the construction of a request. This class * abstracts the implementation and can build either an {@link HttpURLConnection} * or an {@link HttpUriRequest} to represent and execute the given request. * * @author Dylan James * */ public class RequestBuilder { protected static class ParamLocation { private static final int AUTO = 0; private static final int URL = 10; private static final int BODY = 20; } private URI uri; private HttpMethod method; private LinkedHashMap<String, String> params; private LinkedHashMap<String, String> forcedBodyParams; private LinkedHashMap<String, String> headers; private UsernamePasswordCredentials basicAuthCredentials; private int paramLocation = ParamLocation.AUTO; /** * Constructs a {@link RequestBuilder} using the given {@link HttpMethod} * and pointing to the given url. * @param method The {@link HttpMethod} to use for the request. * @param url The url the request targets. */ public RequestBuilder(HttpMethod method, String url) { this(method, URI.create(url)); } /** * Constructs a {@link RequestBuilder} using the given {@link HttpMethod} * and pointing to the given {@link URI}. * @param method The {@link HttpMethod} to use for the request. * @param uri The {@link URI} the request targets. */ public RequestBuilder(HttpMethod method, URI uri) { this.method = method; this.uri = uri; this.params = new LinkedHashMap<String, String>(); this.forcedBodyParams = new LinkedHashMap<String, String>(); this.headers = new LinkedHashMap<String, String>(); } /** * Sets the target URL for this {@link RequestBuilder}. * @param url The url the request should target. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setURL(String url) { return setURI(URI.create(url)); } /** * Sets the target {@link URI} for this {@link RequestBuilder}. * @param uri the {@link URI} the request targets. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setURI(URI uri) { this.uri = uri; return this; } /** * Adds a parameter to this request. * @param key The parameter key. * @param value The parameter value. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addParam(String key, String value) { params.put(key, value); return this; } /** * Adds a parameter to the request if the value is not null. Note that this method * will still add an empty string value to the request. * @param key The parameter key. * @param value The parameter value. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addParamIfNotNull(String key, String value) { if (value != null) { addParam(key, value); } return this; } /** * Adds a {@link Collection} of {@link NameValuePair} as parameters to this * request. Parameters are added in iteration order. * @param params The collection of {@link NameValuePair} to add. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addParams(Collection<NameValuePair> params) { putEntries(params, this.params); return this; } /** * Adds a {@link Map} of parameter key value pairs as parameters of this * request. Parameters are added in iteration order. Params added through this * method will adhere to settings {@link #setSendParamsInBody()} or * {@link #setSendParamsInURL()}. If you would like to force params to be * sent in the body, use {@link #addParamToBodyForced(String, String)}. * @param params The {@link Map} of parameters. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addParams(Map<String, String> params) { putEntries(params, this.params); return this; } /** * Adds a parameter to this request that will be sent only as part of * the request's body. * @param key The parameter key. * @param value The parameter value. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addParamToBodyForced(String key, String value) { forcedBodyParams.put(key, value); return this; } /** * Adds a parameter to this request that will be sent only as part of * the request's body. This is added only if the value is not null. See also: * {@link #addParamToBodyForced(String, String)}. * @param key The parameter key. * @param value The parameter value. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addParamToBodyForcedIfNotNull(String key, String value) { if (value != null) { addParamToBodyForced(key, value); } return this; } /** * Adds a header to this request with the given name and value. * @param name The name of the header. * @param value The value for the header. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addHeader(String name, String value) { headers.put(name, value); return this; } /** * Adds a {@link Collection} of {@link NameValuePair} of headers to * add to this request. Headers are added in iteration order. * @param headers The {@link Collection} of parameters to add. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addHeaders(Collection<NameValuePair> headers) { putEntries(headers, this.headers); return this; } /** * Adds a {@link Map} of key value pairs as headers to this request. * Headers are added in iteration order. * @param headers The {@link Map} of header key value pairs to add. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder addHeaders(Map<String, String> headers) { putEntries(headers, this.headers); return this; } /** * Adds basic authentication to this request. * @param user The username to use for basic auth. * @param pass The password to use for basic auth. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setBasicAuth(String user, String pass) { basicAuthCredentials = new UsernamePasswordCredentials(user, pass); return this; } private InputStream inputStream; private long inputStreamLength; private ProgressListener inputStreamProgressListener; private int inputStreamProgressUpdateInterval = 128; /** * Sets the interval for which input stream progress updates will be sent. * Setting this low will result in more frequent updates which will slightly * reduce performance, while setting this high may result in too infrequent updates. * @param interval The interval, in bytes. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setInputStreamProgressUpdateInterval(int interval) { this.inputStreamProgressUpdateInterval = interval; return this; } /** * Sets the {@link InputStream} to be used as the body of the request. * <br><br> * @see #setInputStreamProgressUpdateInterval(int) * @see #setFileInput(File, ProgressListener) * @param input The {@link InputStream} to write into the body. * @param length The length of the {@link InputStream}. May send negative * if unknown, though the actual request may not support this. * @param progressListener The {@link ProgressListener} which will be called * periodically to be notified of the progress. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setInputStream(InputStream input, long length, ProgressListener progressListener) { this.inputStream = input; this.inputStreamLength = length; this.inputStreamProgressListener = progressListener; return this; } /** * Sets a {@link File} to be used as the body of the request. * <br><br> * @see #setInputStreamProgressUpdateInterval(int) * @see #setInputStream(InputStream, long, ProgressListener) * @param file The {@link File} to set as the body. * @param progressListener The {@link ProgressListener} which will be called * periodically to be notified of the progress. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setFileInput(File file, ProgressListener progressListener) { if (file.exists()){ try { setInputStream(new FileInputStream(file), file.length(), progressListener); } catch (FileNotFoundException e) { if (BuildConfig.DEBUG) { Log.e(getClass().getName(), e.getMessage(), e); } } } return this; } /** * Sets a string to be used as the body of the request. This will overwrite * any existing input. * @param string The string to write as the body. * @param progressListener The {@link ProgressListener} which will be called * periodically to be notified of the progress. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setStringInput(String string, ProgressListener progressListener) { setInputStream(IOUtils.getInputStream(string), string.length(), progressListener); return this; } /** * Resolves where parameters should be sent and returns the value. This * will resolve automatic detection and return the final endpoint instead * of {@link ParamLocation#AUTO} * @return One of the values defined in {@link ParamLocation} where params * should be sent */ protected int getParamLocationResolved() { if (paramLocation == ParamLocation.AUTO) { if (method == HttpMethod.Post) { return ParamLocation.BODY; } else { return ParamLocation.URL; } } else { return paramLocation; } } /** * Causes the params set by addParam calls to be sent in the URL of this * request. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setSendParamsInURL() { paramLocation = ParamLocation.URL; return this; } /** * Causes the params set by addParam calls to be sent in the body of this * request. * @return This {@link RequestBuilder} object to allow for chaining of calls. */ public RequestBuilder setSendParamsInBody() { paramLocation = ParamLocation.BODY; return this; } private void putEntries(Collection<NameValuePair> entries, Map<String, String> map) { for (NameValuePair entry : entries) { map.put(entry.getName(), entry.getValue()); } } private void putEntries(Map<String, String> entries, Map<String, String> map) { for (Entry<String, String> entry : entries.entrySet()) { map.put(entry.getKey(), entry.getValue()); } } private void writeToStream(OutputStream out) throws IOException { byte[] buffer = new byte[1024]; long totalRead = 0; long lastUpdate = 0; int read; try { // Loop through the whole stream and write the data while ((read = inputStream.read(buffer)) != -1) { out.write(buffer, 0, read); out.flush(); totalRead += read; if (inputStreamProgressListener != null) { // If we have a listener, and we've read more than the given interval // since the last update, notify the listener if (totalRead - lastUpdate >= inputStreamProgressUpdateInterval) { inputStreamProgressListener.onProgressUpdate(totalRead, inputStreamLength); lastUpdate = totalRead; } } } } finally { // Reset the input stream just in case it is used again // We are closing it anyway, but resetting just to be safe. try { inputStream.reset(); } catch (IOException e) { // Not a huge deal... Log.i(getClass().getName(), "Failed to reset input stream after use.", e); } IOUtils.safeClose(inputStream); IOUtils.safeClose(out); } } private List<NameValuePair> getNameValuePairs(Map<String, String> map) { List<NameValuePair> pairs = new LinkedList<NameValuePair>(); for (Entry<String, String> entry : map.entrySet()) { pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return pairs; } private String getQueryString(Map<String, String> map) { StringBuilder queryBuilder = new StringBuilder(); boolean first = true; for (Entry<String, String> entry : map.entrySet()) { // This will throw a NullPointerException if you call URLEncoder.encode(null). // Instead caught & thrown with description above. String value = entry.getValue(); if (value == null) { // Can't be more specific without jeopardizing security. throw new NullPointerException("Malformed Request. RequestBuilder entry " + "has null value for key "+entry.getKey()+" on URI "+this.uri+"."); } if (!first) { queryBuilder.append("&"); } queryBuilder.append(entry.getKey()); queryBuilder.append("="); queryBuilder.append(URLEncoder.encode(value)); first = false; } return queryBuilder.toString(); } /** * Gets the URL that this {@link RequestBuilder} points to. * @return The URL the {@link RequestBuilder} is pointing to. */ protected String getUrl() { String url = uri.toString(); // If we should set params in the url and we have params to set, do so if ((getParamLocationResolved() == ParamLocation.URL) && (params.size() > 0)) { String queryString = "?" + getQueryString(params); url = String.format("%s%s", uri, queryString); } return url; } /** * Gets a {@link HttpURLConnection} which can be used to execute this request. * @return */ public HttpURLConnection getConnection() { try { // Get our current URL URL url = new URL(getUrl()); // "Open" the connection, which really just gives us the object, doesn't // actually connect HttpURLConnection connection = (HttpURLConnection)url.openConnection(); // Set the request method appropriately connection.setRequestMethod(method.getMethodName()); // Add all headers for (Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } // Add any basic auth if (basicAuthCredentials != null) { Header authHeader = BasicScheme.authenticate(basicAuthCredentials, Charset.defaultCharset().name(), false); connection.setRequestProperty(authHeader.getName(), authHeader.getValue()); } // If we have params and this is a post, we need to do output // but they will be written later if (params.size() > 0 && (getParamLocationResolved() == ParamLocation.BODY)) { connection.setDoOutput(true); } // If we have an input stream, set the content length and indicate // that we will be doing output if (inputStream != null) { connection.setRequestProperty("Content-Length", Long.toString(inputStreamLength)); connection.setDoOutput(true); // Try to set the chunked size, but this doesn't work in HttpsUrlConnections // due to bugs in Android URLConnection logic. Supposedly fixed in 4.1 connection.setChunkedStreamingMode(8192); } return connection; } catch (MalformedURLException e) { if (BuildConfig.DEBUG) { Log.e(getClass().getName(), e.getMessage(), e); } } catch (IOException e) { if (BuildConfig.DEBUG) { Log.e(getClass().getName(), e.getMessage(), e); } } return null; } /** * Called once the connection has been established. Should be called after * {@link #getConnection()} to allow adding the rest of the data. * @param connection The opened connection */ public void onConnected(HttpURLConnection connection) { // If we have params and this is a put, we need to write them here boolean shouldAddNormalParams = (params.size() > 0 && (getParamLocationResolved() == ParamLocation.BODY)); boolean shouldAddForcedBodyParams = (forcedBodyParams.size() > 0); LinkedHashMap<String, String> bodyParams = null; if (shouldAddNormalParams && shouldAddForcedBodyParams) { bodyParams = new LinkedHashMap<String, String>(); bodyParams.putAll(params); bodyParams.putAll(forcedBodyParams); } else if (shouldAddNormalParams) { bodyParams = params; } else if (shouldAddForcedBodyParams) { bodyParams = forcedBodyParams; } if (bodyParams != null) { // Convert the params to a query string, and write it to the body. String query = getQueryString(bodyParams); try { connection.getOutputStream().write(query.getBytes()); } catch (IOException e) { if (BuildConfig.DEBUG) { Log.e(getClass().getName(), e.getMessage(), e); } } } // If we have an input stream, we need to write it to the body if (inputStream != null) { try { OutputStream out = connection.getOutputStream(); writeToStream(out); } catch (IOException e) { if (BuildConfig.DEBUG) { Log.e(getClass().getName(), e.getMessage(), e); } } } } /** * Gets an {@link HttpUriRequest} which can be used to execute this request. * @return */ public HttpUriRequest getRequest() { // Get the base request from the current method HttpRequestBase request = method.createRequest(); // Set the uri to our url request.setURI(URI.create(getUrl())); // Add all headers for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } // Add any basic auth if (basicAuthCredentials != null) { try { request.addHeader(new BasicScheme().authenticate(basicAuthCredentials, request)); } catch (AuthenticationException e) { Logger.e(getClass().getName(), "Basic authentication on request threw Authentication Exception: " + e.getMessage()); return null; } } // If we have parameters and this is a post, we need to add // the parameters to the body if (params.size() > 0 && (getParamLocationResolved() == ParamLocation.BODY)) { try { ((HttpEntityEnclosingRequest)request).setEntity(new UrlEncodedFormEntity(getNameValuePairs(params))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if (inputStream != null && request instanceof HttpEntityEnclosingRequestBase) { Logger.w(getClass().getName(), "Both post params and an input stream were declared in a request. The params will be overwritten."); } } // If we have an input stream and this request supports an entity, add it. if (inputStream != null && request instanceof HttpEntityEnclosingRequestBase) { // Use a progress input stream entity which notifies the progress listener ProgressInputStreamEntity entity = new ProgressInputStreamEntity(inputStream, inputStreamLength, inputStreamProgressListener, inputStreamProgressUpdateInterval); ((HttpEntityEnclosingRequestBase)request).setEntity(entity); } return request; } }
package com.conveyal.r5.streets; import com.conveyal.r5.analyst.PointSet; import com.conveyal.r5.analyst.WebMercatorGridPointSet; import com.conveyal.r5.common.GeometryUtils; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.profile.StreetMode; import com.conveyal.r5.util.LambdaCounter; import com.vividsolutions.jts.geom.*; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.hash.TIntIntHashMap; import com.conveyal.r5.streets.EdgeStore.Edge; import gnu.trove.set.TIntSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * A LinkedPointSet is a PointSet that has been connected to a StreetLayer in a non-destructive, reversible way. * For each feature in the PointSet, we record the closest edge and the distance to the vertices at the ends of that * edge (like a Splice or a Sample in OTP). */ public class LinkedPointSet implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(LinkedPointSet.class); /** * LinkedPointSets are long-lived and not extremely numerous, so we keep references to the objects it was built * from. Besides these fields are useful for later processing of LinkedPointSets. */ public final PointSet pointSet; /** * We need to retain the street layer so we can look up edge endpoint vertices for the edge IDs. Besides, this * object is inextricably linked to one street network. */ public final StreetLayer streetLayer; /** * The linkage may be different depending on what mode of travel one uses to reach the points from transit stops. * Along with the PointSet and StreetLayer this mode is what determines the contents of a particular * LinkedPointSet. */ public final StreetMode streetMode; static final int BICYCLE_DISTANCE_LINKING_LIMIT_METERS = 8000; static final int CAR_TIME_LINKING_LIMIT_SECONDS = 60 * 60; // 1 hour // Fair to assume that people walk from nearest OSM way to their ultimate destination? Should we just use the // walk speed from the analysis request? static final int OFF_STREET_SPEED_MILLIMETERS_PER_SECOND = (int) 1.3f * 1000; /** * For each point, the closest edge in the street layer. This is in fact the even (forward) edge ID of the closest * edge pairs. */ public int[] edges; /** * For each point, distance from the beginning vertex of the edge geometry up to the split point (closest point on * the edge to the point to be linked), plus the distance from the linked point to the split point */ public int[] distances0_mm; /** * For each point, distance from the end vertex of the edge geometry up to the split point (closest point on the * edge to the point to be linked), plus the distance from the linked point to the split point */ public int[] distances1_mm; // TODO Refactor following three to own class /** For each transit stop, the distances (or times) to nearby PointSet points as packed (point_index, distance) * pairs. */ public List<int[]> stopToPointLinkageCostTables; /** * For each pointset point, the stops reachable without using transit, as a map from StopID to distance. For walk * and bike, distance is in millimeters; for car, distance is actually time in seconds. Inverted version of * stopToPointLinkageCostTables. This is used in PerTargetPropagator to find all the stops near a particular point * (grid cell) so we can perform propagation to that grid cell only. We only retain a few percentiles of travel * time at each target cell, so doing one cell at a time allows us to keep the output size within reason. */ public transient List<TIntIntMap> pointToStopLinkageCostTables; public StreetRouter.State.RoutingVariable linkageCostUnit = StreetRouter.State.RoutingVariable.DISTANCE_MILLIMETERS; /** * A LinkedPointSet is a PointSet that has been pre-connected to a StreetLayer in a non-destructive, reversible way. * These objects are long-lived and not extremely numerous, so we keep references to the objects it was built from. * Besides they are useful for later processing of LinkedPointSets. However once we start evicting * TransportNetworks, we have to make sure we're not holding references to entire StreetLayers in LinkedPointSets * (memory leak). */ public LinkedPointSet (PointSet pointSet, StreetLayer streetLayer, StreetMode streetMode, LinkedPointSet baseLinkage) { LOG.info("Linking pointset to street network..."); this.pointSet = pointSet; this.streetLayer = streetLayer; this.streetMode = streetMode; final int nPoints = pointSet.featureCount(); final int nStops = streetLayer.parentNetwork.transitLayer.getStopCount(); // The regions within which we want to link points to edges, then connect transit stops to points. // Null means relink and rebuild everything, but this will be constrained below if a base linkage was supplied. Geometry treeRebuildZone = null; // This has been commented out because this was evaluating to true frequently on car searches // Perhaps the effect of identity equality comparisons and the fact that both base layer and new linkage are coming from a cache? // if (baseLinkage != null && ( // baseLinkage.pointSet != pointSet || // baseLinkage.streetLayer != streetLayer.baseStreetLayer || // baseLinkage.streetMode != streetMode)) { // LOG.error("Cannot reuse linkage with mismatched characteristics. THIS IS A BUG."); // // Relink everything as if no base linkage was supplied. // baseLinkage = null; if (baseLinkage == null) { // TODO investigate whether we also need to check baseLinkage.streetMode != streetMode edges = new int[nPoints]; distances0_mm = new int[nPoints]; distances1_mm = new int[nPoints]; stopToPointLinkageCostTables = new ArrayList<>(); } else { // The caller has supplied an existing linkage for a scenario StreetLayer's base StreetLayer. // We want to re-use most of that that existing linkage to reduce linking time. LOG.info("Linking a subset of points and copying other linkages from an existing base linkage."); LOG.info("The base linkage is for street mode {}", baseLinkage.streetMode); // Copy the supplied base linkage into this new LinkedPointSet. // The new linkage has the same PointSet as the base linkage, so the linkage arrays remain the same length // stopToVertexDistanceTables list might need to grow. edges = Arrays.copyOf(baseLinkage.edges, nPoints); distances0_mm = Arrays.copyOf(baseLinkage.distances0_mm, nPoints); distances1_mm = Arrays.copyOf(baseLinkage.distances1_mm, nPoints); stopToPointLinkageCostTables = new ArrayList<>(baseLinkage.stopToPointLinkageCostTables); // TODO We need to determine which points to re-link and which stops should have their stop-to-point tables re-built. // This should be all the points within the (bird-fly) linking radius of any modified edge. // The stop-to-vertex trees should already be rebuilt elsewhere when applying the scenario. // This should be all the stops within the (network or bird-fly) tree radius of any modified edge, including // And build trees from stops to points. // Even though currently the only changes to the street network are re-splitting edges to connect new // transit stops, we still need to re-link points and rebuild stop trees (both the trees to the vertices // and the trees to the points, because some existing stop-to-vertex trees might not include new splitter // vertices). treeRebuildZone = streetLayer.scenarioEdgesBoundingGeometry(TransitLayer.DISTANCE_TABLE_SIZE_METERS); } // If dealing with a scenario, pad out the stop trees list from the base linkage to match the new stop count. // If dealing with a base network linkage, fill the stop trees list entirely with nulls. while (stopToPointLinkageCostTables.size() < nStops) stopToPointLinkageCostTables.add(null); // First, link the points in this PointSet to specific street vertices. // If there is no base linkage, link all streets. this.linkPointsToStreets(baseLinkage == null); // Second, make a table of distances from each transit stop to the points in this PointSet. this.makeStopToPointLinkageCostTables(treeRebuildZone); } /** * Construct a new LinkedPointSet for a grid that falls entirely within an existing grid LinkedPointSet. * * @param sourceLinkage a LinkedPointSet whose PointSet must be a WebMercatorGridPointset * @param subGrid the grid for which to create a linkage */ public LinkedPointSet (LinkedPointSet sourceLinkage, WebMercatorGridPointSet subGrid) { if (!(sourceLinkage.pointSet instanceof WebMercatorGridPointSet)) { throw new IllegalArgumentException("Source linkage must be for a gridded point set."); } WebMercatorGridPointSet superGrid = (WebMercatorGridPointSet) sourceLinkage.pointSet; if (superGrid.zoom != subGrid.zoom) { throw new IllegalArgumentException("Source and sub-grid zoom level do not match."); } if (subGrid.west + subGrid.width < superGrid.west //sub-grid is entirely west of super-grid || superGrid.west + superGrid.width < subGrid.west // super-grid is entirely west of sub-grid || subGrid.north + subGrid.height < superGrid.north //sub-grid is entirely north of super-grid (note Web Mercator conventions) || superGrid.north + superGrid.height < subGrid.north) { //super-grid is entirely north of sub-grid LOG.warn("Sub-grid is entirely outside the super-grid. Points will not be linked to any street edges."); } // Initialize the fields of the new LinkedPointSet instance pointSet = sourceLinkage.pointSet; streetLayer = sourceLinkage.streetLayer; streetMode = sourceLinkage.streetMode; int nCells = subGrid.width * subGrid.height; edges = new int[nCells]; distances0_mm = new int[nCells]; distances1_mm = new int[nCells]; // Copy values over from the source linkage to the new sub-linkage // x, y, and pixel are relative to the new linkage for (int y = 0, pixel = 0; y < subGrid.height; y++) { for (int x = 0; x < subGrid.width; x++, pixel++) { int sourceColumn = subGrid.west + x - superGrid.west; int sourceRow = subGrid.north + y - superGrid.north; if (sourceColumn < 0 || sourceColumn >= superGrid.width || sourceRow < 0 || sourceRow >= superGrid.height) { //point is outside super-grid //Set the edge value to -1 to indicate no linkage. //Distances should never be read downstream, so they don't need to be set here. edges[pixel] = -1; } else { //point is inside super-grid int sourcePixel = sourceRow * superGrid.width + sourceColumn; edges[pixel] = sourceLinkage.edges[sourcePixel]; distances0_mm[pixel] = sourceLinkage.distances0_mm[sourcePixel]; distances1_mm[pixel] = sourceLinkage.distances1_mm[sourcePixel]; } } } stopToPointLinkageCostTables = sourceLinkage.stopToPointLinkageCostTables.stream() .map(distanceTable -> { if (distanceTable == null) return null; // if it was previously unlinked, it is still unlinked TIntList newDistanceTable = new TIntArrayList(); for (int i = 0; i < distanceTable.length; i += 2) { int targetInSuperLinkage = distanceTable[i]; int distance = distanceTable[i + 1]; int superX = targetInSuperLinkage % superGrid.width; int superY = targetInSuperLinkage / superGrid.width; int subX = superX + superGrid.west - subGrid.west; int subY = superY + superGrid.north - subGrid.north; if (subX >= 0 && subX < subGrid.width && subY >= 0 && subY < subGrid.height) { // only retain connections to points that fall within the subGrid int targetInSubLinkage = subY * subGrid.width + subX; newDistanceTable.add(targetInSubLinkage); newDistanceTable.add(distance); // distance to target does not change when we crop the pointset } } if (newDistanceTable.isEmpty()) return null; // not near any points in sub pointset else return newDistanceTable.toArray(); }) .collect(Collectors.toList()); } /** * Associate the points in this PointSet with the street vertices at the ends of the closest street edge. * * @param all If true, link all points, otherwise link only those that were previously connected to edges that have * been deleted (i.e. split). We will need to change this behavior when we allow creating new edges * rather than simply splitting existing ones. */ private void linkPointsToStreets (boolean all) { LambdaCounter counter = new LambdaCounter(LOG, pointSet.featureCount(), 10000, "Linked {} of {} PointSet points to streets."); // Perform linkage calculations in parallel, writing results to the shared parallel arrays. IntStream.range(0, pointSet.featureCount()).parallel().forEach(p -> { // When working with a scenario, skip all points that are not linked to a deleted street (i.e. one that has // been split). At the current time, the only street network modification we support is splitting existing streets, // so the only way a point can need to be relinked is if it is connected to a street which was split (and therefore deleted). // FIXME when we permit street network modifications beyond adding transit stops we will need to change how this works, // we may be able to use some type of flood-fill algorithm in geographic space, expanding the relink envelope until we // hit edges on all sides or reach some predefined maximum. if (all || (streetLayer.edgeStore.temporarilyDeletedEdges != null && streetLayer.edgeStore.temporarilyDeletedEdges.contains(edges[p]))) { // Use radius from StreetLayer such that maximum origin and destination walk distances are symmetric. Split split = streetLayer.findSplit(pointSet.getLat(p), pointSet.getLon(p), StreetLayer.LINK_RADIUS_METERS, streetMode); if (split == null) { edges[p] = -1; } else { edges[p] = split.edge; distances0_mm[p] = split.distance0_mm; distances1_mm[p] = split.distance1_mm; } counter.increment(); } }); long unlinked = Arrays.stream(edges).filter(e -> e == -1).count(); counter.done(); LOG.info("{} points are not linked to the street network.", unlinked); } /** @return the number of linkages, which should be the same as the number of points in the PointSet. */ public int size () { return edges.length; } /** * A functional interface for fetching the travel time to any street vertex in the transport network. Note that * TIntIntMap::get matches this functional interface. There may be a generic IntToIntFunction library interface * somewhere, but this interface provides type information about what the function and its parameters mean. */ @FunctionalInterface public static interface TravelTimeFunction { /** * @param vertexId the index of a vertex in the StreetLayer of a TransitNetwork. * @return the travel time to the given street vertex, or Integer.MAX_VALUE if the vertex is unreachable. */ public int getTravelTime (int vertexId); } @Deprecated public PointSetTimes eval (TravelTimeFunction travelTimeForVertex) { // R5 used to not differentiate between seconds and meters, preserve that behavior in this deprecated function // by using 1 m / s return eval(travelTimeForVertex, 1000); } public PointSetTimes eval (TravelTimeFunction travelTimeForVertex, int offstreetTravelSpeedMillimetersPerSecond) { int[] travelTimes = new int[edges.length]; // Iterate over all locations in this temporary vertex list. EdgeStore.Edge edge = streetLayer.edgeStore.getCursor(); for (int i = 0; i < edges.length; i++) { if (edges[i] < 0) { travelTimes[i] = Integer.MAX_VALUE; continue; } edge.seek(edges[i]); int time0 = travelTimeForVertex.getTravelTime(edge.getFromVertex()); int time1 = travelTimeForVertex.getTravelTime(edge.getToVertex()); // An "off-roading" penalty is applied to limit extending isochrones into water bodies, etc. // We may want to keep the MAX_OFFSTREET_WALK_METERS relatively high to avoid holes in the isochrones, // but make it costly to walk long distances where there aren't streets. The approach below // accomplishes that, applying a penalty to off-street distances greater than the typical grid cell size. // We could use a distance threshold more closely tied to pointset resolution/coverage if (time0 != Integer.MAX_VALUE) { time0 += (distances0_mm[i]) / offstreetTravelSpeedMillimetersPerSecond; } if (time1 != Integer.MAX_VALUE) { time1 += (distances1_mm[i]) / offstreetTravelSpeedMillimetersPerSecond; } travelTimes[i] = time0 < time1 ? time0 : time1; } return new PointSetTimes(pointSet, travelTimes); } /** * Given a table of distances to street vertices from a particular transit stop, create a table of distances to * points in this PointSet from the same transit stop. All points outside the distanceTableZone are skipped as an * optimization. See JavaDoc on the caller makeStopToPointLinkageCostTables - this is one of the slowest parts of * building a network. * * @return A packed array of (pointIndex, distanceMillimeters) */ private int[] extendDistanceTableToPoints (TIntIntMap distanceTableToVertices, Envelope distanceTableZone) { int nPoints = this.size(); TIntIntMap distanceToPoint = new TIntIntHashMap(nPoints, 0.5f, Integer.MAX_VALUE, Integer.MAX_VALUE); Edge edge = streetLayer.edgeStore.getCursor(); TIntSet relevantPoints = pointSet.spatialIndex.query(distanceTableZone); relevantPoints.forEach(p -> { // An edge index of -1 for a particular point indicates that this point is unlinked if (edges[p] == -1) return true; edge.seek(edges[p]); int t1 = Integer.MAX_VALUE, t2 = Integer.MAX_VALUE; // TODO this is not strictly correct when there are turn restrictions onto the edge this is linked to if (distanceTableToVertices.containsKey(edge.getFromVertex())) { t1 = distanceTableToVertices.get(edge.getFromVertex()) + distances0_mm[p]; } if (distanceTableToVertices.containsKey(edge.getToVertex())) { t2 = distanceTableToVertices.get(edge.getToVertex()) + distances1_mm[p]; } int t = Math.min(t1, t2); if (t != Integer.MAX_VALUE) { if (t < distanceToPoint.get(p)) { distanceToPoint.put(p, t); } } return true; // Continue iteration. }); if (distanceToPoint.size() == 0) { return null; } // Convert a packed array of pairs. // TODO don't put in a list and convert to array, just make an array. TIntList packed = new TIntArrayList(distanceToPoint.size() * 2); distanceToPoint.forEachEntry((point, distance) -> { packed.add(point); packed.add(distance); return true; // Continue iteration. }); return packed.toArray(); } /** * For each transit stop in the associated TransportNetwork, make a table of distances to nearby points in this * PointSet. * At one point we experimented with doing the entire search from the transit stops all the way up to the points * within this method. However, that takes too long when switching PointSets. So we pre-cache distances to all * street vertices in the TransitNetwork, and then just extend those tables to the points in the PointSet. * This is one of the slowest steps in working with a new scenario. It takes about 50 seconds to link 400000 points. * The run time is not shocking when you consider the complexity of the operation: there are nStops * nPoints * iterations, which is 8000 * 400000 in the example case. This means 6 msec per transit stop, or 2e-8 sec per point * iteration, which is not horribly slow. There are just too many iterations. * * @param treeRebuildZone only build trees for stops inside this geometry in FIXED POINT DEGREES, leaving all the * others alone. If null, build trees for all stops. */ public void makeStopToPointLinkageCostTables(Geometry treeRebuildZone) { LOG.info("Creating linkage cost tables from each transit stop to PointSet points."); // FIXME this is wasting a lot of memory and not needed for gridded pointsets - overload for gridded and freeform PointSets pointSet.createSpatialIndexAsNeeded(); if (treeRebuildZone != null) { LOG.info("Selectively computing tables for only those stops that might be affected by the scenario."); } TransitLayer transitLayer = streetLayer.parentNetwork.transitLayer; int nStops = transitLayer.getStopCount(); LambdaCounter counter = new LambdaCounter(LOG, nStops, 1000, "Computed distances to PointSet points from {} of {} transit stops."); // Create a distance table from each transit stop to the points in this PointSet in parallel. // When applying a scenario, keep the existing distance table for those stops that could not be affected. stopToPointLinkageCostTables = IntStream.range(0, nStops).parallel().mapToObj(stopIndex -> { Point stopPoint = transitLayer.getJTSPointForStopFixed(stopIndex); // If the stop is not linked to the street network, it should have no distance table. if (stopPoint == null) return null; if (treeRebuildZone != null && !treeRebuildZone.contains(stopPoint)) { // This stop is not affected by the scenario. Return the existing distance table. // all stops outside the relink zone should already have a distance table entry. if (stopIndex >= stopToPointLinkageCostTables.size()) { throw new AssertionError("A stop created by a scenario is located outside relink zone."); } return stopToPointLinkageCostTables.get(stopIndex); } int[] linkageCostToPoints; if (streetMode == StreetMode.WALK) { // Walking distances from stops to street vertices are saved in the transitLayer. // Get the pre-computed distance table from the stop to the street vertices, // then extend that table out from the street vertices to the points in this PointSet. TIntIntMap distanceTableToVertices = transitLayer.stopToVertexDistanceTables.get(stopIndex); // walk! Envelope distanceTableZone = stopPoint.getEnvelopeInternal(); GeometryUtils.expandEnvelopeFixed(distanceTableZone, TransitLayer.DISTANCE_TABLE_SIZE_METERS); linkageCostToPoints = distanceTableToVertices == null ? null : extendDistanceTableToPoints(distanceTableToVertices, distanceTableZone); } else if (streetMode == StreetMode.BICYCLE) { // Biking distances from stops to street vertices are not saved in the transitLayer, so additional // steps are needed compared to Walk. StreetRouter sr = new StreetRouter(transitLayer.parentNetwork.streetLayer); sr.streetMode = StreetMode.BICYCLE; sr.distanceLimitMeters = BICYCLE_DISTANCE_LINKING_LIMIT_METERS; sr.quantityToMinimize = linkageCostUnit; sr.setOrigin(stopPoint.getY(), stopPoint.getX()); sr.route(); Envelope distanceTableZone = stopPoint.getEnvelopeInternal(); GeometryUtils.expandEnvelopeFixed(distanceTableZone, BICYCLE_DISTANCE_LINKING_LIMIT_METERS); linkageCostToPoints = extendDistanceTableToPoints(sr.getReachedVertices(), distanceTableZone); } else if (streetMode == StreetMode.CAR) { // The speeds for Walk and Bicycle can be specified in an analysis request, so it makes sense above to // store distances and apply the requested speed. In contrast, car speeds vary by link and cannot be // set in analysis requests, so it makes sense to use seconds directly as the linkage cost. linkageCostUnit = StreetRouter.State.RoutingVariable.DURATION_SECONDS; // TODO confirm this works as expected when modifications can affect street layer. StreetRouter sr = new StreetRouter(transitLayer.parentNetwork.streetLayer); sr.streetMode = StreetMode.CAR; sr.timeLimitSeconds = CAR_TIME_LINKING_LIMIT_SECONDS; sr.quantityToMinimize = linkageCostUnit; sr.setOrigin(stopPoint.getY(), stopPoint.getX()); sr.route(); // TODO limit search radius using envelope, as above. This optimization will require care to avoid // creating a resource-limiting problem. linkageCostToPoints = eval(sr::getTravelTimeToVertex, OFF_STREET_SPEED_MILLIMETERS_PER_SECOND).travelTimes; } else { throw new UnsupportedOperationException("Tried to link a pointset with an unsupported mode"); } counter.increment(); return linkageCostToPoints; }).collect(Collectors.toList()); counter.done(); } // FIXME Method and block inside are both synchronized on "this", is that intentional? See comment in internal block. public synchronized void makePointToStopDistanceTablesIfNeeded () { if (pointToStopLinkageCostTables != null) return; synchronized (this) { // check again in case they were built while waiting on this synchronized block if (pointToStopLinkageCostTables != null) return; if (stopToPointLinkageCostTables == null) makeStopToPointLinkageCostTables(null); TIntIntMap[] result = new TIntIntMap[size()]; for (int stop = 0; stop < stopToPointLinkageCostTables.size(); stop++) { int[] stopToPointDistanceTable = stopToPointLinkageCostTables.get(stop); if (stopToPointDistanceTable == null) continue; for (int idx = 0; idx < stopToPointDistanceTable.length; idx += 2) { int point = stopToPointDistanceTable[idx]; int distance = stopToPointDistanceTable[idx + 1]; if (result[point] == null) result[point] = new TIntIntHashMap(); result[point].put(stop, distance); } } pointToStopLinkageCostTables = Arrays.asList(result); } } }
package com.pcloud.networking; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.*; import static com.pcloud.networking.Util.typesMatch; public class Cyclone { private final static Collection<TypeAdapterFactory> DEFAULT_FACTORIES; static { DEFAULT_FACTORIES = new ArrayList<>(4); DEFAULT_FACTORIES.add(new PrimitiveTypesAdapterFactory()); DEFAULT_FACTORIES.add(new CollectionsTypeAdapterFactory()); DEFAULT_FACTORIES.add(new ArrayTypeAdapterFactory()); DEFAULT_FACTORIES.add(new ClassTypeAdapterFactory()); } public static Builder create() { return new Builder(); } private final List<TypeAdapterFactory> adapterFactories; private final Map<Type, TypeAdapter<?>> typeToAdapterMap; private final ThreadLocal<List<StubTypeAdapter<?>>> pendingAdapterRef; private Cyclone(Builder builder) { typeToAdapterMap = new LinkedHashMap<>(); pendingAdapterRef = new ThreadLocal<>(); adapterFactories = new ArrayList<>(); adapterFactories.addAll(DEFAULT_FACTORIES); adapterFactories.addAll(builder.factories); } public <T> TypeAdapter<T> getTypeAdapter(Class<T> type) { return getTypeAdapter((Type)type); } public <T> TypeAdapter<T> getTypeAdapter(Type type) { type = Types.canonicalize(type); // Try to return a cached adapter, if any. synchronized (typeToAdapterMap) { TypeAdapter<?> result = typeToAdapterMap.get(type); if (result != null) { return (TypeAdapter<T>) result; } } // Check for any pending cyclic adapters List<StubTypeAdapter<?>> pendingAdapters = pendingAdapterRef.get(); if (pendingAdapters != null) { for (StubTypeAdapter<?> adapter : pendingAdapters) { if (adapter.cacheKey.equals(type)) { // There's a pending adapter, return the stub to // avoid an endless recursion. return (TypeAdapter<T>) adapter; } } } else { pendingAdapters = new ArrayList<>(); pendingAdapterRef.set(pendingAdapters); } // Create a stub adapter for the requested type. StubTypeAdapter<T> adapterStub = new StubTypeAdapter<>(type); pendingAdapters.add(adapterStub); // Iterate though the factories and create an adapter for the type. try { for (TypeAdapterFactory factory : adapterFactories) { TypeAdapter<T> result = (TypeAdapter<T>) factory.create(type, Collections.<Annotation>emptySet(), this); if (result != null) { adapterStub.setDelegate(result); synchronized (typeToAdapterMap) { typeToAdapterMap.put(type, result); } return result; } } } finally { pendingAdapters.remove(pendingAdapters.size() - 1); if (pendingAdapters.isEmpty()) { pendingAdapterRef.remove(); } } throw new IllegalStateException("Cannot create an adapter for type '" + type + "'."); } public Builder newBuilder() { List<TypeAdapterFactory> customFactories = new ArrayList<>(adapterFactories); customFactories.removeAll(DEFAULT_FACTORIES); return new Builder(customFactories); } public static class Builder { private List<TypeAdapterFactory> factories; private Builder() { factories = new ArrayList<>(); } private Builder(List<TypeAdapterFactory> factories) { this.factories = new ArrayList<>(factories); } public <T> Builder addTypeAdapter(final Type type, final TypeAdapter<T> adapter) { if (type == null) { throw new IllegalArgumentException("Type argument cannot be null."); } if (adapter == null) { throw new IllegalArgumentException("TypeAdapter argument cannot be null."); } factories.add(new TypeAdapterFactory() { @Override public TypeAdapter<?> create(Type requested, Set<? extends Annotation> annotations, Cyclone cyclone) { return typesMatch(type, requested) ? adapter : null; } }); return this; } public Builder addTypeAdapterFactory(TypeAdapterFactory adapterFactory) { if (adapterFactory == null) { throw new IllegalArgumentException("TypeAdapterFactory cannot be null."); } factories.add(adapterFactory); return this; } public Cyclone build() { return new Cyclone(this); } } }
package com.creativemd.littletiles; import java.util.List; import com.creativemd.creativecore.common.packet.CreativeCorePacket; import com.creativemd.creativecore.gui.container.SubContainer; import com.creativemd.creativecore.gui.container.SubGui; import com.creativemd.creativecore.gui.opener.CustomGuiHandler; import com.creativemd.creativecore.gui.opener.GuiHandler; import com.creativemd.littletiles.common.action.LittleAction; import com.creativemd.littletiles.common.action.LittleActionCombined; import com.creativemd.littletiles.common.action.block.LittleActionActivated; import com.creativemd.littletiles.common.action.block.LittleActionColorBoxes; import com.creativemd.littletiles.common.action.block.LittleActionColorBoxes.LittleActionColorBoxesFiltered; import com.creativemd.littletiles.common.action.block.LittleActionDestroy; import com.creativemd.littletiles.common.action.block.LittleActionDestroyBoxes; import com.creativemd.littletiles.common.action.block.LittleActionDestroyBoxes.LittleActionDestroyBoxesFiltered; import com.creativemd.littletiles.common.action.block.LittleActionPlaceAbsolute; import com.creativemd.littletiles.common.action.block.LittleActionPlaceRelative; import com.creativemd.littletiles.common.action.block.LittleActionReplace; import com.creativemd.littletiles.common.action.tool.LittleActionGlowstone; import com.creativemd.littletiles.common.action.tool.LittleActionGlowstone.LittleActionGlowstoneRevert; import com.creativemd.littletiles.common.action.tool.LittleActionSaw; import com.creativemd.littletiles.common.action.tool.LittleActionSaw.LittleActionSawRevert; import com.creativemd.littletiles.common.api.ILittleTile; import com.creativemd.littletiles.common.api.ISpecialBlockSelector; import com.creativemd.littletiles.common.api.blocks.DefaultBlockHandler; import com.creativemd.littletiles.common.blocks.BlockLTColored; import com.creativemd.littletiles.common.blocks.BlockLTFlowingWater; import com.creativemd.littletiles.common.blocks.BlockLTFlowingWater.LittleFlowingWaterPreview; import com.creativemd.littletiles.common.blocks.BlockLTParticle; import com.creativemd.littletiles.common.blocks.BlockLTTransparentColored; import com.creativemd.littletiles.common.blocks.BlockStorageTile; import com.creativemd.littletiles.common.blocks.BlockTile; import com.creativemd.littletiles.common.blocks.ItemBlockColored; import com.creativemd.littletiles.common.blocks.ItemBlockFlowingWater; import com.creativemd.littletiles.common.blocks.ItemBlockTransparentColored; import com.creativemd.littletiles.common.command.ExportCommand; import com.creativemd.littletiles.common.command.ImportCommand; import com.creativemd.littletiles.common.command.OpenCommand; import com.creativemd.littletiles.common.config.IGCMLoader; import com.creativemd.littletiles.common.container.SubContainerConfigure; import com.creativemd.littletiles.common.container.SubContainerExport; import com.creativemd.littletiles.common.container.SubContainerImport; import com.creativemd.littletiles.common.container.SubContainerParticle; import com.creativemd.littletiles.common.container.SubContainerRecipeAdvanced; import com.creativemd.littletiles.common.container.SubContainerStorage; import com.creativemd.littletiles.common.entity.EntityDoorAnimation; import com.creativemd.littletiles.common.entity.EntitySizedTNTPrimed; import com.creativemd.littletiles.common.events.LittleEvent; import com.creativemd.littletiles.common.gui.SubGuiChisel; import com.creativemd.littletiles.common.gui.SubGuiExport; import com.creativemd.littletiles.common.gui.SubGuiImport; import com.creativemd.littletiles.common.gui.SubGuiParticle; import com.creativemd.littletiles.common.gui.SubGuiRecipeAdvanced; import com.creativemd.littletiles.common.gui.SubGuiStorage; import com.creativemd.littletiles.common.gui.handler.LittleGuiHandler; import com.creativemd.littletiles.common.items.ItemBlockTiles; import com.creativemd.littletiles.common.items.ItemColorTube; import com.creativemd.littletiles.common.items.ItemHammer; import com.creativemd.littletiles.common.items.ItemLittleChisel; import com.creativemd.littletiles.common.items.ItemLittleGrabber; import com.creativemd.littletiles.common.items.ItemLittleSaw; import com.creativemd.littletiles.common.items.ItemLittleScrewdriver; import com.creativemd.littletiles.common.items.ItemLittleWrench; import com.creativemd.littletiles.common.items.ItemMultiTiles; import com.creativemd.littletiles.common.items.ItemRecipe; import com.creativemd.littletiles.common.items.ItemRecipeAdvanced; import com.creativemd.littletiles.common.items.ItemRubberMallet; import com.creativemd.littletiles.common.items.ItemTileContainer; import com.creativemd.littletiles.common.items.ItemUtilityKnife; import com.creativemd.littletiles.common.packet.LittleBedPacket; import com.creativemd.littletiles.common.packet.LittleBlockPacket; import com.creativemd.littletiles.common.packet.LittleDoorInteractPacket; import com.creativemd.littletiles.common.packet.LittleEntityRequestPacket; import com.creativemd.littletiles.common.packet.LittleFlipPacket; import com.creativemd.littletiles.common.packet.LittleNeighborUpdatePacket; import com.creativemd.littletiles.common.packet.LittleRotatePacket; import com.creativemd.littletiles.common.packet.LittleSlidingDoorPacket; import com.creativemd.littletiles.common.packet.LittleTileUpdatePacket; import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket; import com.creativemd.littletiles.common.structure.LittleStorage; import com.creativemd.littletiles.common.structure.LittleStructure; import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles; import com.creativemd.littletiles.common.tileentity.TileEntityParticle; import com.creativemd.littletiles.common.tiles.LittleTile; import com.creativemd.littletiles.common.tiles.LittleTileBlock; import com.creativemd.littletiles.common.tiles.LittleTileBlockColored; import com.creativemd.littletiles.common.tiles.LittleTileTE; import com.creativemd.littletiles.common.tiles.advanced.LittleTileParticle; import com.creativemd.littletiles.common.tiles.preview.LittleTilePreview; import com.creativemd.littletiles.common.tiles.preview.LittleTilePreviewHandler; import com.creativemd.littletiles.common.utils.grid.LittleGridContext; import com.creativemd.littletiles.common.utils.placing.PlacementHelper; import com.creativemd.littletiles.server.LittleTilesServer; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @Mod(modid = LittleTiles.modid, version = LittleTiles.version, name = "LittleTiles",acceptedMinecraftVersions="",guiFactory="com.creativemd.littletiles.client.LittleTilesSettings") @Mod.EventBusSubscriber public class LittleTiles { @SidedProxy(clientSide = "com.creativemd.littletiles.client.LittleTilesClient", serverSide = "com.creativemd.littletiles.server.LittleTilesServer") public static LittleTilesServer proxy; public static final String modid = "littletiles"; public static final String version = "1.5.0"; public static CreativeTabs littleTab = new CreativeTabs("littletiles") { @Override public ItemStack getTabIconItem() { return new ItemStack(hammer); } }; public static BlockTile blockTile = (BlockTile) new BlockTile(Material.ROCK).setRegistryName("BlockLittleTiles"); public static Block coloredBlock = new BlockLTColored().setRegistryName("LTColoredBlock").setUnlocalizedName("LTColoredBlock").setHardness(1.5F); public static Block transparentColoredBlock = new BlockLTTransparentColored().setRegistryName("LTTransparentColoredBlock").setUnlocalizedName("LTTransparentColoredBlock").setHardness(0.3F); public static Block storageBlock = new BlockStorageTile().setRegistryName("LTStorageBlockTile").setUnlocalizedName("LTStorageBlockTile").setHardness(1.5F); public static Block particleBlock = new BlockLTParticle().setRegistryName("LTParticleBlock").setUnlocalizedName("LTParticleBlock").setHardness(1.5F); public static Block flowingWater = new BlockLTFlowingWater().setRegistryName("LTFlowingWater").setUnlocalizedName("LTFlowingWater").setHardness(0.3F); public static Item hammer; public static Item recipe; public static Item recipeAdvanced; public static Item multiTiles; public static Item saw; public static Item container; public static Item wrench; public static Item screwdriver; public static Item chisel; public static Item colorTube; public static Item rubberMallet; public static Item utilityKnife; public static Item grabber; private void removeMissingProperties(String path, ConfigCategory category, List<String> allowedNames) { for(ConfigCategory child : category.getChildren()) removeMissingProperties(path + (path.isEmpty() ? "" : ".") + category.getName(), child, allowedNames); for(String propertyName : category.getPropertyOrder()) { String name = path + (path.isEmpty() ? "" : ".") + propertyName; if(!allowedNames.contains(name)) category.remove(propertyName); } } @EventHandler public void PreInit(FMLPreInitializationEvent event) { event.getModMetadata().version = version; Configuration config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); LittleGridContext.loadGrid(config.getInt("minSize", "core", 1, 1, Integer.MAX_VALUE, "The minimum grid size possible. ATTENTION! This needs be equal for every client & server. Backup your world."), config.getInt("defaultSize", "core", 16, 1, Integer.MAX_VALUE, "Needs to be part of the row. ATTENTION! This needs be equal for every client & server. Backup your world. This will make your tiles either shrink down or increase in size!"), config.getInt("scale", "core", 6, 1, Integer.MAX_VALUE, "How many grids there are. ATTENTION! This needs be equal for every client & server. Make sure that it is enough for the defaultSize to exist."), config.getInt("exponent", "core", 2, 1, Integer.MAX_VALUE, "minSize ^ (exponent * scale). ATTENTION! This needs be equal for every client & server. Default is two -> (1, 2, 4, 8, 16, 32 etc.).")); List<String> allowedPropertyNames = LittleTilesConfig.getConfigProperties(); for(String categoryName : config.getCategoryNames()) removeMissingProperties(categoryName, config.getCategory(categoryName), allowedPropertyNames); config.save(); proxy.loadSidePre(); hammer = new ItemHammer().setUnlocalizedName("LTHammer").setRegistryName("hammer"); recipe = new ItemRecipe().setUnlocalizedName("LTRecipe").setRegistryName("recipe"); recipeAdvanced = new ItemRecipeAdvanced().setUnlocalizedName("LTRecipeAdvanced").setRegistryName("recipeadvanced"); multiTiles = new ItemMultiTiles().setUnlocalizedName("LTMultiTiles").setRegistryName("multiTiles"); saw = new ItemLittleSaw().setUnlocalizedName("LTSaw").setRegistryName("saw"); container = new ItemTileContainer().setUnlocalizedName("LTContainer").setRegistryName("container"); wrench = new ItemLittleWrench().setUnlocalizedName("LTWrench").setRegistryName("wrench"); screwdriver = new ItemLittleScrewdriver().setUnlocalizedName("LTScrewdriver").setRegistryName("screwdriver"); chisel = new ItemLittleChisel().setUnlocalizedName("LTChisel").setRegistryName("chisel"); colorTube = new ItemColorTube().setUnlocalizedName("LTColorTube").setRegistryName("colorTube"); rubberMallet = new ItemRubberMallet().setUnlocalizedName("LTRubberMallet").setRegistryName("rubberMallet"); utilityKnife = new ItemUtilityKnife().setUnlocalizedName("LTUtilityKnife").setRegistryName("utilityKnife"); grabber = new ItemLittleGrabber().setUnlocalizedName("LTGrabber").setRegistryName("grabber"); } @SubscribeEvent public static void registerBlocks(RegistryEvent.Register<Block> event) { event.getRegistry().registerAll(coloredBlock, transparentColoredBlock, blockTile, storageBlock, particleBlock, flowingWater); } @SubscribeEvent public static void registerItems(RegistryEvent.Register<Item> event) { event.getRegistry().registerAll(hammer, recipe, recipeAdvanced, saw, container, wrench, screwdriver, chisel, colorTube, rubberMallet, multiTiles, utilityKnife, grabber, new ItemBlock(storageBlock).setRegistryName(storageBlock.getRegistryName()), new ItemBlock(particleBlock).setRegistryName(particleBlock.getRegistryName()), new ItemBlockColored(coloredBlock, coloredBlock.getRegistryName()).setRegistryName(coloredBlock.getRegistryName()), new ItemBlockTransparentColored(transparentColoredBlock, transparentColoredBlock.getRegistryName()).setRegistryName(transparentColoredBlock.getRegistryName()), new ItemBlockTiles(blockTile, blockTile.getRegistryName()).setRegistryName(blockTile.getRegistryName()), new ItemBlockFlowingWater(flowingWater, flowingWater.getRegistryName()).setRegistryName(flowingWater.getRegistryName())); proxy.loadSide(); } @EventHandler public void Init(FMLInitializationEvent event) { ForgeModContainer.fullBoundingBoxLadders = true; GameRegistry.registerTileEntity(TileEntityLittleTiles.class, "LittleTilesTileEntity"); GameRegistry.registerTileEntity(TileEntityParticle.class, "LittleTilesParticle"); LittleTile.registerLittleTile(LittleTileBlock.class, "BlockTileBlock", LittleTilePreviewHandler.defaultHandler); LittleTile.registerLittleTile(LittleTileTE.class, "BlockTileEntity", LittleTilePreviewHandler.defaultHandler); LittleTile.registerLittleTile(LittleTileBlockColored.class, "BlockTileColored", LittleTilePreviewHandler.defaultHandler); LittleTile.registerLittleTile(LittleTileParticle.class, "BlockTileParticle", LittleTilePreviewHandler.defaultHandler); LittleTilePreview.registerPreviewType("water", LittleFlowingWaterPreview.class); GuiHandler.registerGuiHandler("littleStorageStructure", new LittleGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) { if(tile.isStructureBlock && tile.structure instanceof LittleStorage) return new SubGuiStorage((LittleStorage) tile.structure); return null; } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) { if(tile.isStructureBlock && tile.structure instanceof LittleStorage) return new SubContainerStorage(player, (LittleStorage) tile.structure); return null; } }); GuiHandler.registerGuiHandler("littleparticle", new LittleGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) { if(tile instanceof LittleTileParticle) return new SubGuiParticle((TileEntityParticle) ((LittleTileParticle) tile).getTileEntity()); return null; } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) { if(tile instanceof LittleTileParticle) return new SubContainerParticle(player, (TileEntityParticle) ((LittleTileParticle) tile).getTileEntity()); return null; } }); GuiHandler.registerGuiHandler("configure", new CustomGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { ItemStack stack = player.getHeldItemMainhand(); ILittleTile iTile = PlacementHelper.getLittleInterface(stack); if(iTile != null) return iTile.getConfigureGUI(player, stack); else if(stack.getItem() instanceof ISpecialBlockSelector) return ((ISpecialBlockSelector) stack.getItem()).getConfigureGUI(player, stack); return null; } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { return new SubContainerConfigure(player, player.getHeldItemMainhand()); } }); GuiHandler.registerGuiHandler("chisel", new CustomGuiHandler(){ @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { return new SubGuiChisel(player.getHeldItemMainhand()); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { return new SubContainerConfigure(player, player.getHeldItemMainhand()); } }); GuiHandler.registerGuiHandler("grabber", new CustomGuiHandler(){ @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { ItemStack stack = player.getHeldItemMainhand(); return ItemLittleGrabber.getMode(stack).getGui(player, stack, ((ILittleTile) stack.getItem()).getPositionContext(stack)); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { ItemStack stack = player.getHeldItemMainhand(); return ItemLittleGrabber.getMode(stack).getContainer(player, stack); } }); GuiHandler.registerGuiHandler("recipeadvanced", new CustomGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { return new SubGuiRecipeAdvanced(player.getHeldItemMainhand()); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { return new SubContainerRecipeAdvanced(player, player.getHeldItemMainhand(), new BlockPos(nbt.getInteger("posX"), nbt.getInteger("posY"), nbt.getInteger("posZ"))); } }); GuiHandler.registerGuiHandler("lt-import", new CustomGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { return new SubGuiImport(); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { return new SubContainerImport(player); } }); GuiHandler.registerGuiHandler("lt-export", new CustomGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { return new SubGuiExport(); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { return new SubContainerExport(player); } }); CreativeCorePacket.registerPacket(LittleBlockPacket.class, "LittleBlock"); CreativeCorePacket.registerPacket(LittleRotatePacket.class, "LittleRotate"); CreativeCorePacket.registerPacket(LittleFlipPacket.class, "LittleFlip"); CreativeCorePacket.registerPacket(LittleNeighborUpdatePacket.class, "LittleNeighbor"); CreativeCorePacket.registerPacket(LittleDoorInteractPacket.class, "LittleDoor"); CreativeCorePacket.registerPacket(LittleSlidingDoorPacket.class, "LittleSlidingDoor"); CreativeCorePacket.registerPacket(LittleEntityRequestPacket.class, "EntityRequest"); CreativeCorePacket.registerPacket(LittleBedPacket.class, "LittleBed"); CreativeCorePacket.registerPacket(LittleTileUpdatePacket.class, "TileUpdate"); CreativeCorePacket.registerPacket(LittleVanillaBlockPacket.class, "VanillaBlock"); LittleAction.registerLittleAction("com", LittleActionCombined.class); LittleAction.registerLittleAction("act", LittleActionActivated.class); LittleAction.registerLittleAction("col", LittleActionColorBoxes.class, LittleActionColorBoxesFiltered.class); LittleAction.registerLittleAction("deB", LittleActionDestroyBoxes.class, LittleActionDestroyBoxesFiltered.class); LittleAction.registerLittleAction("des", LittleActionDestroy.class); LittleAction.registerLittleAction("plR", LittleActionPlaceRelative.class); LittleAction.registerLittleAction("plA", LittleActionPlaceAbsolute.class); LittleAction.registerLittleAction("glo", LittleActionGlowstone.class, LittleActionGlowstoneRevert.class); LittleAction.registerLittleAction("saw", LittleActionSaw.class, LittleActionSawRevert.class); LittleAction.registerLittleAction("rep", LittleActionReplace.class); MinecraftForge.EVENT_BUS.register(new LittleEvent()); //MinecraftForge.EVENT_BUS.register(ChiselAndBitsConveration.class); LittleStructure.initStructures(); //Entity EntityRegistry.registerModEntity(new ResourceLocation(modid, "sizeTNT"), EntitySizedTNTPrimed.class, "sizedTNT", 0, this, 250, 250, true); EntityRegistry.registerModEntity(new ResourceLocation(modid, "doorAnimation"), EntityDoorAnimation.class, "doorAnimation", 1, this, 2000, 250, true); DefaultBlockHandler.initVanillaBlockHandlers(); proxy.loadSidePost(); if(Loader.isModLoaded("igcm")) IGCMLoader.initIGCM(); } @EventHandler public void serverStarting(FMLServerStartingEvent event) { event.registerServerCommand(new ExportCommand()); event.registerServerCommand(new ImportCommand()); event.registerServerCommand(new OpenCommand()); } }
package com.github.anba.es6draft.parser; import static com.github.anba.es6draft.semantics.StaticSemantics.BoundNames; import static com.github.anba.es6draft.semantics.StaticSemantics.IsSimpleParameterList; import static com.github.anba.es6draft.semantics.StaticSemantics.PropName; import static com.github.anba.es6draft.semantics.StaticSemantics.SpecialMethod; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.github.anba.es6draft.ast.*; import com.github.anba.es6draft.ast.BreakableStatement.Abrupt; import com.github.anba.es6draft.ast.MethodDefinition.MethodType; import com.github.anba.es6draft.parser.ParserException.ExceptionType; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.SmallArrayList; /** * Parser for ECMAScript6 source code * <ul> * <li>11 Expressions * <li>12 Statements and Declarations * <li>13 Functions and Generators * <li>14 Scripts and Modules * </ul> */ public class Parser { private static final boolean MODULES_ENABLED = false; private static final boolean DEBUG = false; private static final Binding NO_INHERITED_BINDING = null; private static final Set<String> EMPTY_LABEL_SET = Collections.emptySet(); private final String sourceFile; private final int sourceLine; private final EnumSet<Option> options; private TokenStream ts; private ParseContext context; private enum StrictMode { Unknown, Strict, NonStrict } private enum StatementType { Iteration, Breakable, Statement } private enum ContextKind { Script, Function, Generator, ArrowFunction } private static class ParseContext { final ParseContext parent; final ContextKind kind; boolean superReference = false; boolean yieldAllowed = false; StrictMode strictMode = StrictMode.Unknown; ParserException strictError = null; List<FunctionNode> deferred = null; Map<String, LabelContext> labelSet = null; LabelContext labels = null; ScopeContext scopeContext; final FunctionContext funContext; ParseContext() { this.parent = null; this.kind = null; this.funContext = null; } ParseContext(ParseContext parent, ContextKind kind) { this.parent = parent; this.kind = kind; this.funContext = new FunctionContext(this); this.scopeContext = funContext; if (parent.strictMode == StrictMode.Strict) { this.strictMode = parent.strictMode; } } void setReferencesSuper() { ParseContext cx = this; while (cx.kind == ContextKind.ArrowFunction) { cx = cx.parent; } cx.superReference = true; } boolean hasSuperReference() { return superReference; } } private static class FunctionContext extends ScopeContext implements FunctionScope { final ScopeContext enclosing; Set<String> parameterNames = null; boolean directEval = false; FunctionContext(ParseContext context) { super(null); this.enclosing = context.parent.scopeContext; } private boolean isStrict() { if (node instanceof FunctionNode) { return ((FunctionNode) node).isStrict(); } else { assert node instanceof Script; return ((Script) node).isStrict(); } } @Override public ScopeContext getEnclosingScope() { return enclosing; } @Override public boolean isDynamic() { return directEval && !isStrict(); } @Override public Set<String> parameterNames() { return parameterNames; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public Set<String> varDeclaredNames() { return varDeclaredNames; } @Override public List<StatementListItem> varScopedDeclarations() { return varScopedDeclarations; } } private static class BlockContext extends ScopeContext implements BlockScope { final boolean dynamic; BlockContext(ScopeContext parent, boolean dynamic) { super(parent); this.dynamic = dynamic; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public boolean isDynamic() { return dynamic; } } private abstract static class ScopeContext implements Scope { final ScopeContext parent; ScopedNode node = null; HashSet<String> varDeclaredNames = null; HashSet<String> lexDeclaredNames = null; List<StatementListItem> varScopedDeclarations = null; List<Declaration> lexScopedDeclarations = null; ScopeContext(ScopeContext parent) { this.parent = parent; } @Override public Scope getParent() { return parent; } @Override public ScopedNode getNode() { return node; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("var: ").append(varDeclaredNames != null ? varDeclaredNames : "<null>"); sb.append("\t"); sb.append("lex: ").append(lexDeclaredNames != null ? lexDeclaredNames : "<null>"); return sb.toString(); } boolean isTopLevel() { return (parent == null); } boolean addVarDeclaredName(String name) { if (varDeclaredNames == null) { varDeclaredNames = new HashSet<>(); } varDeclaredNames.add(name); return (lexDeclaredNames == null || !lexDeclaredNames.contains(name)); } boolean addLexDeclaredName(String name) { if (lexDeclaredNames == null) { lexDeclaredNames = new HashSet<>(); } return lexDeclaredNames.add(name) && (varDeclaredNames == null || !varDeclaredNames.contains(name)); } void addVarScopedDeclaration(StatementListItem decl) { if (varScopedDeclarations == null) { varScopedDeclarations = newSmallList(); } varScopedDeclarations.add(decl); } void addLexScopedDeclaration(Declaration decl) { if (lexScopedDeclarations == null) { lexScopedDeclarations = newSmallList(); } lexScopedDeclarations.add(decl); } } private static class LabelContext { final LabelContext parent; final StatementType type; final Set<String> labelSet; final EnumSet<Abrupt> abrupts = EnumSet.noneOf(Abrupt.class); LabelContext(LabelContext parent, StatementType type, Set<String> labelSet) { this.parent = parent; this.type = type; this.labelSet = labelSet; } void mark(Abrupt abrupt) { abrupts.add(abrupt); } } public enum Option { Strict, FunctionCode, LocalScope, DirectEval, EvalScript } public Parser(String sourceFile, int sourceLine) { this(sourceFile, sourceLine, EnumSet.noneOf(Option.class)); } public Parser(String sourceFile, int sourceLine, EnumSet<Option> options) { this.sourceFile = sourceFile; this.sourceLine = sourceLine; this.options = options; context = new ParseContext(); context.strictMode = options.contains(Option.Strict) ? StrictMode.Strict : StrictMode.NonStrict; } private ParseContext newContext(ContextKind kind) { return context = new ParseContext(context, kind); } private ParseContext restoreContext() { if (context.parent.strictError == null) { context.parent.strictError = context.strictError; } return context = context.parent; } private BlockContext enterWithContext() { BlockContext cx = new BlockContext(context.scopeContext, true); context.scopeContext = cx; return cx; } private ScopeContext exitWithContext() { return exitScopeContext(); } private BlockContext enterBlockContext() { BlockContext cx = new BlockContext(context.scopeContext, false); context.scopeContext = cx; return cx; } private ScopeContext exitBlockContext() { return exitScopeContext(); } private ScopeContext exitScopeContext() { ScopeContext scope = context.scopeContext; ScopeContext parent = scope.parent; assert parent != null : "exitScopeContext() on top-level"; HashSet<String> varDeclaredNames = scope.varDeclaredNames; if (varDeclaredNames != null) { scope.varDeclaredNames = null; for (String name : varDeclaredNames) { addVarDeclaredName(parent, name); } } return context.scopeContext = parent; } private void addFunctionDecl(FunctionDeclaration funDecl) { addFunctionDecl(funDecl, funDecl.getIdentifier()); } private void addGeneratorDecl(GeneratorDeclaration genDecl) { // TODO: for now same rules as function declaration addFunctionDecl(genDecl, genDecl.getIdentifier()); } private void addFunctionDecl(Declaration decl, BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); ScopeContext parentScope = context.parent.scopeContext; if (parentScope.isTopLevel()) { // top-level function declaration parentScope.addVarScopedDeclaration(decl); if (!parentScope.addVarDeclaredName(name)) { reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } else { // block-scoped function declaration parentScope.addLexScopedDeclaration(decl); if (!parentScope.addLexDeclaredName(name)) { reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } } private void addLexScopedDeclaration(Declaration decl) { context.scopeContext.addLexScopedDeclaration(decl); } private void addVarScopedDeclaration(VariableStatement decl) { context.funContext.addVarScopedDeclaration(decl); } private void addVarDeclaredName(ScopeContext scope, String name) { if (!scope.addVarDeclaredName(name)) { reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } private void addLexDeclaredName(ScopeContext scope, String name) { if (!scope.addLexDeclaredName(name)) { reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } /** * <strong>[12.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ @SuppressWarnings("unused") private void addVarDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addVarDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addVarDeclaredName((BindingPattern) binding); } } private void addVarDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addVarDeclaredName(context.scopeContext, name); } private void addVarDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addVarDeclaredName(context.scopeContext, name); } } /** * <strong>[12.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any * duplicate entries. * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ private void addLexDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addLexDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addLexDeclaredName((BindingPattern) binding); } } private void addLexDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addLexDeclaredName(context.scopeContext, name); } private void addLexDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addLexDeclaredName(context.scopeContext, name); } } private void removeLexDeclaredName(ScopeContext scope, Binding binding) { HashSet<String> lexDeclaredNames = scope.lexDeclaredNames; if (binding instanceof BindingIdentifier) { BindingIdentifier bindingIdentifier = (BindingIdentifier) binding; String name = BoundName(bindingIdentifier); lexDeclaredNames.remove(name); } else { assert binding instanceof BindingPattern; BindingPattern bindingPattern = (BindingPattern) binding; for (String name : BoundNames(bindingPattern)) { lexDeclaredNames.remove(name); } } } private LabelContext enterLabelled(StatementType type, Set<String> labelSet) { LabelContext cx = context.labels = new LabelContext(context.labels, type, labelSet); if (!labelSet.isEmpty() && context.labelSet == null) { context.labelSet = new HashMap<>(); } for (String label : labelSet) { if (context.labelSet.containsKey(label)) { reportSyntaxError(Messages.Key.DuplicateLabel, label); } context.labelSet.put(label, cx); } return cx; } private LabelContext exitLabelled() { for (String label : context.labels.labelSet) { context.labelSet.remove(label); } return context.labels = context.labels.parent; } private LabelContext enterIteration(Set<String> labelSet) { return enterLabelled(StatementType.Iteration, labelSet); } private void exitIteration() { exitLabelled(); } private LabelContext enterBreakable(Set<String> labelSet) { return enterLabelled(StatementType.Breakable, labelSet); } private void exitBreakable() { exitLabelled(); } private LabelContext findContinueTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type == StatementType.Iteration : cx.labelSet.contains(label)) { return cx; } } return null; } private LabelContext findBreakTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null || cx.labelSet.contains(label)) { return cx; } } return null; } private static <T> List<T> newSmallList() { return new SmallArrayList<>(); } private static <T> List<T> newList() { return new SmallArrayList<>(); } private static <T> List<T> merge(List<T> list1, List<T> list2) { if (!(list1.isEmpty() || list2.isEmpty())) { List<T> merged = new ArrayList<>(); merged.addAll(list1); merged.addAll(list2); return merged; } return list1.isEmpty() ? list2 : list1; } private ParserException reportException(ParserException exception) { throw exception; } private ParserException reportTokenMismatch(Token expected, Token actual) { if (actual == Token.EOF) { throw new ParserEOFException(Messages.Key.UnexpectedToken, ts.getLine(), actual.toString(), expected.toString()); } throw new ParserException(ExceptionType.SyntaxError, ts.getLine(), Messages.Key.UnexpectedToken, actual.toString(), expected.toString()); } private ParserException reportTokenMismatch(String expected, Token actual) { if (actual == Token.EOF) { throw new ParserEOFException(Messages.Key.UnexpectedToken, ts.getLine(), actual.toString(), expected); } throw new ParserException(ExceptionType.SyntaxError, ts.getLine(), Messages.Key.UnexpectedToken, actual.toString(), expected); } private static ParserException reportError(ExceptionType type, int line, Messages.Key messageKey, String... args) { throw new ParserException(type, line, messageKey, args); } private static ParserException reportSyntaxError(Messages.Key messageKey, int line, String... args) { throw reportError(ExceptionType.SyntaxError, line, messageKey, args); } @SuppressWarnings("unused") private static ParserException reportReferenceError(Messages.Key messageKey, int line, String... args) { throw reportError(ExceptionType.ReferenceError, line, messageKey, args); } private ParserException reportSyntaxError(Messages.Key messageKey, String... args) { throw reportError(ExceptionType.SyntaxError, ts.getLine(), messageKey, args); } private ParserException reportReferenceError(Messages.Key messageKey, String... args) { throw reportError(ExceptionType.ReferenceError, ts.getLine(), messageKey, args); } private void reportStrictModeError(ExceptionType type, Messages.Key messageKey, String... args) { if (context.strictMode == StrictMode.Unknown) { if (context.strictError == null) { context.strictError = new ParserException(type, ts.getLine(), messageKey, args); } } else if (context.strictMode == StrictMode.Strict) { reportError(type, ts.getLine(), messageKey, args); } } void reportStrictModeSyntaxError(Messages.Key messageKey, String... args) { reportStrictModeError(ExceptionType.SyntaxError, messageKey, args); } void reportStrictModeReferenceError(Messages.Key messageKey, String... args) { reportStrictModeError(ExceptionType.ReferenceError, messageKey, args); } /** * Peeks the next token in the token-stream */ private Token peek() { return ts.peekToken(); } /** * Checks whether the next token in the token-stream is equal to the input token */ private boolean LOOKAHEAD(Token token) { return ts.peekToken() == token; } /** * Returns the current token in the token-stream */ private Token token() { return ts.currentToken(); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(Token tok) { if (tok != token()) reportTokenMismatch(tok, token()); Token next = ts.nextToken(); if (DEBUG) System.out.printf("consume(%s) -> %s\n", tok, next); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(String name) { String string = ts.getString(); consume(Token.NAME); if (!name.equals(string)) reportSyntaxError(Messages.Key.UnexpectedName, string, name); } public Script parse(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); ts = new TokenStream(this, new StringTokenStreamInput(source), sourceLine); return script(); } public Script parse(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); FunctionExpression function; newContext(ContextKind.Function); try { BindingIdentifier identifier = new BindingIdentifier("anonymous"); ts = new TokenStream(this, new StringTokenStreamInput(formals), sourceLine); FormalParameterList parameters = formalParameterList(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } ts = new TokenStream(this, new StringTokenStreamInput(bodyText), sourceLine); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } // FIXME: trailing single-line comment in formals String source = String .format("function anonymous (%s) {\n%s\n}", formals, bodyText); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; function = new FunctionExpression(scope, identifier, parameters, statements, source); scope.node = function; function = inheritStrictness(function); } finally { restoreContext(); } boolean strict = (context.strictMode == StrictMode.Strict); List<StatementListItem> body = newSmallList(); body.add(new ExpressionStatement(function)); FunctionContext scope = context.funContext; Script script = new Script(sourceFile, scope, body, options, strict); scope.node = script; return script; } finally { restoreContext(); } } /** * <strong>[14.1] Script</strong> * * <pre> * Script : * ScriptBody<sub>opt</sub> * ScriptBody : * OuterStatementList * </pre> */ private Script script() { newContext(ContextKind.Script); try { List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = outerStatementList(); boolean strict = (context.strictMode == StrictMode.Strict); FunctionContext scope = context.funContext; Script script = new Script(sourceFile, scope, merge(prologue, body), options, strict); scope.node = script; return script; } finally { restoreContext(); } } /** * <strong>[14.1] Script</strong> * * <pre> * OuterStatementList : * OuterItem * OuterStatementList OuterItem * OuterItem : * ModuleDeclaration * ImportDeclaration * StatementListItem * </pre> */ private List<StatementListItem> outerStatementList() { List<StatementListItem> list = newList(); while (token() != Token.EOF) { if (MODULES_ENABLED) { // TODO: implement modules if (token() == Token.IMPORT) { importDeclaration(); } else if (token() == Token.NAME && "module".equals(getName(token())) && peek() == Token.STRING && !ts.hasNextLineTerminator()) { moduleDeclaration(); } else { list.add(statementListItem()); } } else { list.add(statementListItem()); } } return list; } /** * <strong>[14.2] Modules</strong> * * <pre> * ImportDeclaration ::= "import" ImportClause ("," ImportClause)* ";" * </pre> */ private void importDeclaration() { consume(Token.IMPORT); importClause(); while (token() == Token.COMMA) { consume(Token.COMMA); importClause(); } semicolon(); } /** * <strong>[14.2] Modules</strong> * * <pre> * ImportClause ::= StringLiteral "as" Identifier * | ImportSpecifierSet "from" ModuleSpecifier * </pre> */ private void importClause() { if (token() == Token.STRING) { moduleImport(); } else { importSpecifierSet(); consume("from"); moduleSpecifier(); } } /** * <strong>[14.2] Modules</strong> * * <pre> * ModuleImport ::= StringLiteral "as" Identifier * </pre> */ private void moduleImport() { consume(Token.STRING); consume("as"); identifier(); } /** * <strong>[14.2] Modules</strong> * * <pre> * ImportSpecifierSet ::= "{" ImportSpecifier ("," ImportSpecifier)* "}" * </pre> */ private void importSpecifierSet() { consume(Token.LC); importSpecifier(); while (token() != Token.RC) { consume(Token.COMMA); importSpecifier(); } consume(Token.RC); } /** * <strong>[14.2] Modules</strong> * * <pre> * ImportSpecifier ::= Identifier (":" Identifier)? * </pre> */ private void importSpecifier() { identifier(); if (token() == Token.COLON) { consume(Token.COLON); identifier(); } } /** * <strong>[14.2] Modules</strong> * * <pre> * ModuleSpecifier ::= StringLiteral | Identifier * </pre> */ private void moduleSpecifier() { if (token() == Token.STRING) { consume(Token.STRING); } else { identifier(); } } /** * <strong>[14.2] Modules</strong> * * <pre> * ModuleDeclaration ::= "module" [NoNewline] StringLiteral "{" ModuleBody "}" * </pre> */ private void moduleDeclaration() { consume("module"); consume(Token.STRING); consume(Token.LC); moduleBody(); consume(Token.RC); } /** * <strong>[14.2] Modules</strong> * * <pre> * ModuleBody ::= ModuleElement* * ModuleElement ::= ScriptElement * | ExportDeclaration * </pre> */ private List<StatementListItem> moduleBody() { List<StatementListItem> list = newList(); while (token() != Token.RC) { if (token() == Token.IMPORT) { importDeclaration(); } else if (token() == Token.EXPORT) { exportDeclaration(); } else if (token() == Token.NAME && "module".equals(getName(token())) && peek() == Token.STRING && !ts.hasNextLineTerminator()) { moduleDeclaration(); } else { list.add(statementListItem()); } } return list; } /** * <strong>[14.2] Modules</strong> * * <pre> * ExportDeclaration ::= "export" ExportSpecifierSet ("," ExportSpecifierSet)* ";" * | "export" VariableDeclaration * | "export" FunctionDeclaration * | "export" "get" Identifier "(" ")" "{" FunctionBody "}" * | "export" "set" Identifier "(" DestructuringPattern ")" "{" FunctionBody "}" * | "export" "=" Expression ";" * </pre> */ private void exportDeclaration() { consume(Token.EXPORT); switch (token()) { case VAR: variableStatement(); break; case LET: case CONST: // "export" VariableDeclaration lexicalDeclaration(true); break; case FUNCTION: // "export" FunctionDeclaration if (LOOKAHEAD(Token.MUL)) { generatorDeclaration(); } else { functionDeclaration(); } break; case CLASS: classDeclaration(); break; case ASSIGN: // "export" "=" Expression ";" consume(Token.ASSIGN); expression(true); semicolon(); break; case NAME: { // "export" "get" Identifier "(" ")" "{" FunctionBody "}" // "export" "set" Identifier "(" DestructuringPattern ")" "{" FunctionBody "}" String name = getName(Token.NAME); if (("get".equals(name) || "set".equals(name)) && isIdentifier(peek())) { if ("get".equals(name)) { consume("get"); identifier(); consume(Token.LP); consume(Token.RP); consume(Token.LC); functionBody(Token.RC); consume(Token.RC); } else { consume("set"); identifier(); consume(Token.LP); binding(); consume(Token.RP); consume(Token.LC); functionBody(Token.RC); consume(Token.RC); } break; } // fall-through } default: // "export" ExportSpecifierSet ("," ExportSpecifierSet)* ";" exportSpecifierSet(); while (token() == Token.COMMA) { exportSpecifierSet(); } semicolon(); break; } } /** * <strong>[14.2] Modules</strong> * * <pre> * ExportSpecifierSet ::= "{" ExportSpecifier ("," ExportSpecifier)* "}" * | Identifier * | "*" ("from" Path)? * ExportSpecifier ::= Identifier (":" Path)? * * Path ::= Identifier ("." Identifier)* * </pre> */ private void exportSpecifierSet() { switch (token()) { case LC: // "{" ExportSpecifier ("," ExportSpecifier)* "}" consume(Token.LC); exportSpecifier(); while (token() == Token.COMMA) { consume(Token.COMMA); exportSpecifier(); } consume(Token.RC); break; case MUL: // "*" ("from" Path)? consume(Token.MUL); if (token() == Token.NAME && "from".equals(getName(Token.NAME))) { consume("from"); path(); } break; default: identifier(); break; } } /** * <strong>[14.2] Modules</strong> * * <pre> * ExportSpecifier ::= Identifier (":" Path)? * </pre> */ private void exportSpecifier() { identifier(); if (token() == Token.COLON) { consume(Token.COLON); path(); } } /** * <strong>[14.2] Modules</strong> * * <pre> * Path ::= Identifier ("." Identifier)* * </pre> */ private void path() { identifier(); while (token() == Token.DOT) { consume(Token.DOT); identifier(); } } /** * <strong>[14.1] Directive Prologues and the Use Strict Directive</strong> * * <pre> * DirectivePrologue : * Directive<sub>opt</sub> * Directive: * StringLiteral ; * Directive StringLiteral ; * </pre> */ private List<StatementListItem> directivePrologue() { List<StatementListItem> statements = newSmallList(); boolean strict = false; directive: while (token() == Token.STRING) { boolean hasEscape = ts.hasEscape(); // peek() may clear hasEscape flag Token next = peek(); switch (next) { case SEMI: case RC: case EOF: break; default: if (ts.hasNextLineTerminator() && !isOperator(next)) { break; } break directive; } // got a directive String string = ts.getString(); if (!hasEscape && "use strict".equals(string)) { strict = true; } consume(Token.STRING); semicolon(); statements.add(new ExpressionStatement(new StringLiteral(string))); } applyStrictMode(strict); return statements; } private static boolean isOperator(Token token) { switch (token) { case DOT: case LB: case LP: case TEMPLATE: case COMMA: case HOOK: case ASSIGN: case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: case OR: case AND: case BITAND: case BITOR: case BITXOR: case EQ: case NE: case SHEQ: case SHNE: case LT: case LE: case GT: case GE: case INSTANCEOF: case IN: case SHL: case SHR: case USHR: case ADD: case SUB: case MUL: case DIV: case MOD: return true; default: return false; } } private void applyStrictMode(boolean strict) { if (strict) { context.strictMode = StrictMode.Strict; if (context.strictError != null) { reportException(context.strictError); } } else { if (context.strictMode == StrictMode.Unknown) { context.strictMode = context.parent.strictMode; } } } private <FUNCTION extends FunctionNode> FUNCTION inheritStrictness(FUNCTION function) { if (context.strictMode != StrictMode.Unknown) { boolean strict = (context.strictMode == StrictMode.Strict); function.setStrict(strict); if (context.deferred != null) { for (FunctionNode func : context.deferred) { func.setStrict(strict); } context.deferred = null; } } else { // this case only applies for functions with default parameters assert context.parent.strictMode == StrictMode.Unknown; ParseContext parent = context.parent; if (parent.deferred == null) { parent.deferred = newSmallList(); } parent.deferred.add(function); if (context.deferred != null) { parent.deferred.addAll(context.deferred); context.deferred = null; } } return function; } /** * <strong>[13.1] Function Definitions</strong> * * <pre> * FunctionDeclaration : * function BindingIdentifier ( FormalParameterList ) { FunctionBody } * </pre> */ private FunctionDeclaration functionDeclaration() { newContext(ContextKind.Function); try { consume(Token.FUNCTION); int start = ts.position() - "function".length(); BindingIdentifier identifier = bindingIdentifier(); consume(Token.LP); FormalParameterList parameters = formalParameterList(Token.RP); consume(Token.RP); consume(Token.LC); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); // TODO: insert 'use strict' if in strict-mode String source = ts.range(start, ts.position()); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; FunctionDeclaration function = new FunctionDeclaration(scope, identifier, parameters, statements, source); scope.node = function; addFunctionDecl(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[13.1] Function Definitions</strong> * * <pre> * FunctionExpression : * function BindingIdentifier<sub>opt</sub> ( FormalParameterList ) { FunctionBody } * </pre> */ private FunctionExpression functionExpression() { newContext(ContextKind.Function); try { consume(Token.FUNCTION); int start = ts.position() - "function".length(); BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifier(); } consume(Token.LP); FormalParameterList parameters = formalParameterList(Token.RP); consume(Token.RP); consume(Token.LC); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); // TODO: insert 'use strict' if in strict-mode String source = ts.range(start, ts.position()); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; FunctionExpression function = new FunctionExpression(scope, identifier, parameters, statements, source); scope.node = function; return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[13.1] Function Definitions</strong> * * <pre> * FormalParameterList : * [empty] * FunctionRestParameter * FormalsList * FormalsList, FunctionRestParameter * FormalsList : * FormalParameter * FormalsList, FormalParameter * FunctionRestParameter : * ... BindingIdentifier * FormalParameter : * BindingElement * </pre> */ private FormalParameterList formalParameterList(Token end) { List<FormalParameter> formals = newSmallList(); boolean needComma = false; while (token() != end) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (token() == Token.TRIPLE_DOT) { consume(Token.TRIPLE_DOT); formals.add(new BindingRestElement(bindingIdentifierStrict())); break; } else { formals.add(bindingElement()); needComma = true; } } return new FormalParameterList(formals); } private static <T> T containsAny(Set<T> set, List<T> list) { for (T element : list) { if (set.contains(element)) { return element; } } return null; } private void formalParameterList_StaticSemantics(FormalParameterList parameters) { // TODO: Early Error if intersection of BoundNames(FormalParameterList) and // VarDeclaredNames(FunctionBody) is not the empty set // => only for non-simple parameter list? // => doesn't quite follow the current Function Declaration Instantiation algorithm assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; HashSet<String> lexDeclaredNames = scope.lexDeclaredNames; List<String> boundNames = BoundNames(parameters); HashSet<String> names = new HashSet<>(boundNames); scope.parameterNames = names; boolean hasLexDeclaredNames = !(lexDeclaredNames == null || lexDeclaredNames.isEmpty()); boolean strict = (context.strictMode != StrictMode.NonStrict); boolean simple = IsSimpleParameterList(parameters); if (!strict && simple) { if (hasLexDeclaredNames) { String redeclared = containsAny(lexDeclaredNames, boundNames); if (redeclared != null) { reportSyntaxError(Messages.Key.FormalParameterRedeclaration, redeclared); } } return; } boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (strict) { if (hasDuplicates) { reportStrictModeSyntaxError(Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportStrictModeSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } } if (!simple) { if (hasDuplicates) { reportSyntaxError(Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } } if (hasLexDeclaredNames) { String redeclared = containsAny(lexDeclaredNames, boundNames); if (redeclared != null) { reportSyntaxError(Messages.Key.FormalParameterRedeclaration, redeclared); } } } /** * <strong>[13.1] Function Definitions</strong> * * <pre> * FunctionBody : * StatementList<sub>opt</sub> * </pre> */ private List<StatementListItem> functionBody(Token end) { // enable 'yield' if in generator context.yieldAllowed = (context.kind == ContextKind.Generator); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = statementList(end); return merge(prologue, body); } /** * <strong>[13.2] Arrow Function Definitions</strong> * * <pre> * ArrowFunction : * ArrowParameters => ConciseBody * ArrowParameters : * BindingIdentifier * ( ArrowFormalParameterList ) * ArrowFormalParameterList : * [empty] * FunctionRestParameter * CoverFormalsList * CoverFormalsList , FunctionRestParameter * ConciseBody : * [LA &#x2209; { <b>{</b> }] AssignmentExpression * { FunctionBody } * CoverFormalsList : * Expression * </pre> */ private ArrowFunction arrowFunction() { newContext(ContextKind.ArrowFunction); try { StringBuilder source = new StringBuilder(); source.append("function anonymous"); FormalParameterList parameters; if (token() == Token.LP) { consume(Token.LP); int start = ts.position() - "(".length(); parameters = formalParameterList(Token.RP); consume(Token.RP); source.append(ts.range(start, ts.position())); } else { BindingIdentifier identifier = bindingIdentifier(); FormalParameter parameter = new BindingElement(identifier, null); parameters = new FormalParameterList(singletonList(parameter)); source.append('(').append(identifier.getName()).append(')'); } consume(Token.ARROW); if (token() == Token.LC) { consume(Token.LC); int start = ts.position() - "{".length(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); source.append(ts.range(start, ts.position())); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(scope, parameters, statements, source.toString()); scope.node = function; return inheritStrictness(function); } else { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int start = ts.position(); Expression expression = assignmentExpression(true); source.append("{\nreturn ").append(ts.range(start, ts.position())).append("\n}"); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(scope, parameters, expression, source.toString()); scope.node = function; return inheritStrictness(function); } } finally { restoreContext(); } } /** * <strong>[13.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( FormalParameterList ) { FunctionBody } * * PropertyName ( FormalParameterList ) { FunctionBody } * get PropertyName ( ) { FunctionBody } * set PropertyName ( PropertySetParameterList ) { FunctionBody } * PropertySetParameterList : * BindingIdentifier * BindingPattern * </pre> */ private MethodDefinition methodDefinition() { MethodType type = methodType(); newContext(type != MethodType.Generator ? ContextKind.Function : ContextKind.Generator); try { PropertyName propertyName; FormalParameterList parameters; List<StatementListItem> statements; int start; switch (type) { case Getter: consume(Token.NAME); propertyName = propertyName(); consume(Token.LP); start = ts.position() - "(".length(); parameters = new FormalParameterList(Collections.<FormalParameter> emptyList()); consume(Token.RP); consume(Token.LC); statements = functionBody(Token.RC); consume(Token.RC); break; case Setter: consume(Token.NAME); propertyName = propertyName(); consume(Token.LP); start = ts.position() - "(".length(); FormalParameter setParameter = new BindingElement(binding(), null); parameters = new FormalParameterList(singletonList(setParameter)); consume(Token.RP); consume(Token.LC); statements = functionBody(Token.RC); consume(Token.RC); break; case Generator: consume(Token.MUL); case Function: default: propertyName = propertyName(); consume(Token.LP); start = ts.position() - "(".length(); parameters = formalParameterList(Token.RP); consume(Token.RP); consume(Token.LC); statements = functionBody(Token.RC); consume(Token.RC); break; } StringBuilder source = new StringBuilder(); if (type != MethodType.Generator) { source.append("function "); } else { source.append("function* "); } source.append(ts.range(start, ts.position())); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; MethodDefinition method = new MethodDefinition(scope, type, propertyName, parameters, statements, context.hasSuperReference(), source.toString()); scope.node = method; return inheritStrictness(method); } finally { restoreContext(); } } private MethodType methodType() { Token tok = token(); if (tok == Token.MUL) { return MethodType.Generator; } if (tok == Token.NAME) { String name = getName(tok); if (("get".equals(name) || "set".equals(name)) && isPropertyName(peek())) { return "get".equals(name) ? MethodType.Getter : MethodType.Setter; } } return MethodType.Function; } private boolean isPropertyName(Token token) { return token == Token.STRING || token == Token.NUMBER || isIdentifierName(token); } /** * <strong>[13.4] Generator Definitions</strong> * * <pre> * GeneratorDeclaration : * function * BindingIdentifier ( FormalParameterList ) { FunctionBody } * </pre> */ private GeneratorDeclaration generatorDeclaration() { newContext(ContextKind.Generator); try { consume(Token.FUNCTION); int start = ts.position() - "function".length(); consume(Token.MUL); BindingIdentifier identifier = bindingIdentifier(); consume(Token.LP); FormalParameterList parameters = formalParameterList(Token.RP); consume(Token.RP); consume(Token.LC); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); // TODO: insert 'use strict' if in strict-mode String source = ts.range(start, ts.position()); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; GeneratorDeclaration generator = new GeneratorDeclaration(scope, identifier, parameters, statements, source); scope.node = generator; addGeneratorDecl(generator); return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[13.4] Generator Definitions</strong> * * <pre> * GeneratorExpression : * function * BindingIdentifier<sub>opt</sub> ( FormalParameterList ) { FunctionBody } * </pre> */ private GeneratorExpression generatorExpression() { newContext(ContextKind.Generator); try { consume(Token.FUNCTION); int start = ts.position() - "function".length(); consume(Token.MUL); BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifier(); } consume(Token.LP); FormalParameterList parameters = formalParameterList(Token.RP); consume(Token.RP); consume(Token.LC); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); // TODO: insert 'use strict' if in strict-mode String source = ts.range(start, ts.position()); formalParameterList_StaticSemantics(parameters); FunctionContext scope = context.funContext; GeneratorExpression generator = new GeneratorExpression(scope, identifier, parameters, statements, source); scope.node = generator; return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[13.4] Generator Definitions</strong> * * <pre> * YieldExpression : * yield YieldDelegator<sub>opt</sub> AssignmentExpression * YieldDelegator : * * * </pre> */ private YieldExpression yieldExpression() { if (!context.yieldAllowed) { reportSyntaxError(Messages.Key.InvalidYieldStatement); } consume(Token.YIELD); boolean delegatedYield = false; if (token() == Token.MUL) { consume(Token.MUL); delegatedYield = true; } if (token() == Token.YIELD) { // disallow `yield yield x` but allow `yield (yield x)` // TODO: track spec changes, syntax not yet settled reportSyntaxError(Messages.Key.InvalidYieldStatement); } // TODO: NoLineTerminator() restriction or context dependent? Expression expr; if (delegatedYield || !(token() == Token.SEMI || token() == Token.RC)) { expr = assignmentExpression(true); } else { // extension: allow Spidermonkey syntax expr = null; } return new YieldExpression(delegatedYield, expr); } /** * <strong>[13.5] Class Definitions</strong> * * <pre> * ClassDeclaration : * class BindingIdentifier ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassDeclaration classDeclaration() { consume(Token.CLASS); BindingIdentifier name = bindingIdentifierStrict(); Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = assignmentExpression(true); } consume(Token.LC); List<MethodDefinition> body = classBody(); consume(Token.RC); addLexDeclaredName(name); ClassDeclaration decl = new ClassDeclaration(name, heritage, body); addLexScopedDeclaration(decl); return decl; } /** * <strong>[13.5] Class Definitions</strong> * * <pre> * ClassExpression : * class BindingIdentifier<sub>opt</sub> ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassExpression classExpression() { consume(Token.CLASS); BindingIdentifier name = null; if (token() != Token.EXTENDS && token() != Token.LC) { name = bindingIdentifierStrict(); } Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = assignmentExpression(true); } consume(Token.LC); if (name != null) { enterBlockContext(); addLexDeclaredName(name); } List<MethodDefinition> body = classBody(); if (name != null) { exitBlockContext(); } consume(Token.RC); return new ClassExpression(name, heritage, body); } /** * <strong>[13.5] Class Definitions</strong> * * <pre> * ClassBody : * ClassElementList * ClassElementList : * ClassElement * ClassElementList ClassElement * ClassElement : * MethodDefinition * ; * </pre> */ private List<MethodDefinition> classBody() { List<MethodDefinition> list = newList(); while (token() != Token.RC) { if (token() == Token.SEMI) { consume(Token.SEMI); } else { list.add(methodDefinition()); } } classBody_StaticSemantics(list); return list; } private void classBody_StaticSemantics(List<MethodDefinition> defs) { final int VALUE = 0, GETTER = 1, SETTER = 2; Map<String, Integer> values = new HashMap<>(); for (MethodDefinition def : defs) { String key = PropName(def); if ("constructor".equals(key) && SpecialMethod(def)) { reportSyntaxError(Messages.Key.InvalidConstructorMethod); } MethodDefinition.MethodType type = def.getType(); final int kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : VALUE; if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE) { reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[12] Statements</strong> * * <pre> * Statement : * BlockStatement * VariableStatement * EmptyStatement * ExpressionStatement * IfStatement * BreakableStatement * ContinueStatement * BreakStatement * ReturnStatement * WithStatement * LabelledStatement * ThrowStatement * TryStatement * DebuggerStatement * * BreakableStatement : * IterationStatement * SwitchStatement * </pre> */ private Statement statement() { switch (token()) { case LC: return block(NO_INHERITED_BINDING); case VAR: return variableStatement(); case SEMI: return emptyStatement(); case IF: return ifStatement(); case FOR: return forStatement(EMPTY_LABEL_SET); case WHILE: return whileStatement(EMPTY_LABEL_SET); case DO: return doWhileStatement(EMPTY_LABEL_SET); case CONTINUE: return continueStatement(); case BREAK: return breakStatement(); case RETURN: return returnStatement(); case WITH: return withStatement(); case SWITCH: return switchStatement(EMPTY_LABEL_SET); case THROW: return throwStatement(); case TRY: return tryStatement(); case DEBUGGER: return debuggerStatement(); case NAME: if (LOOKAHEAD(Token.COLON)) { return labelledStatement(); } default: return expressionStatement(); } } /** * <strong>[12.1] Block</strong> * * <pre> * BlockStatement : * Block * Block : * { StatementList<sub>opt</sub> } * </pre> */ private BlockStatement block(Binding inherited) { consume(Token.LC); BlockContext scope = enterBlockContext(); if (inherited != null) { addLexDeclaredName(inherited); } List<StatementListItem> list = statementList(Token.RC); exitBlockContext(); consume(Token.RC); BlockStatement block = new BlockStatement(scope, list); scope.node = block; return block; } /** * <strong>[12.1] Block</strong> * * <pre> * StatementList : * StatementItem * StatementList StatementListItem * </pre> */ private List<StatementListItem> statementList(Token end) { List<StatementListItem> list = newList(); while (token() != end) { list.add(statementListItem()); } return list; } /** * <strong>[12.1] Block</strong> * * <pre> * StatementListItem : * Statement * Declaration * Declaration : * FunctionDeclaration * GeneratorDeclaration * ClassDeclaration * LexicalDeclaration * </pre> */ private StatementListItem statementListItem() { switch (token()) { case FUNCTION: if (LOOKAHEAD(Token.MUL)) { return generatorDeclaration(); } else { return functionDeclaration(); } case CLASS: return classDeclaration(); case LET: case CONST: return lexicalDeclaration(true); default: return statement(); } } /** * <strong>[12.2.1] Let and Const Declarations</strong> * * <pre> * LexicalDeclaration : * LetOrConst BindingList ; * LexicalDeclarationNoIn : * LetOrConst BindingListNoIn * LetOrConst : * let * const * </pre> */ private LexicalDeclaration lexicalDeclaration(boolean allowIn) { LexicalDeclaration.Type type; if (token() == Token.LET) { consume(Token.LET); type = LexicalDeclaration.Type.Let; } else { consume(Token.CONST); type = LexicalDeclaration.Type.Const; } List<LexicalBinding> list = bindingList((type == LexicalDeclaration.Type.Const), allowIn); if (allowIn) { semicolon(); } LexicalDeclaration decl = new LexicalDeclaration(type, list); addLexScopedDeclaration(decl); return decl; } /** * <strong>[12.2.1] Let and Const Declarations</strong> * * <pre> * BindingList : * LexicalBinding * BindingList, LexicalBinding * BindingListNoIn : * LexicalBindingNoIn * BindingListNoIn, LexicalBindingNoIn * </pre> */ private List<LexicalBinding> bindingList(boolean isConst, boolean allowIn) { List<LexicalBinding> list = newSmallList(); list.add(lexicalBinding(isConst, allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(lexicalBinding(isConst, allowIn)); } return list; } /** * <strong>[12.2.1] Let and Const Declarations</strong> * * <pre> * LexicalBinding : * BindingIdentifier Initialiser<sub>opt</sub> * BindingPattern Initialiser * LexicalBindingNoIn : * BindingIdentifier InitialiserNoIn<sub>opt</sub> * BindingPattern InitialiserNoIn * </pre> */ private LexicalBinding lexicalBinding(boolean isConst, boolean allowIn) { Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addLexDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false` initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addLexDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } else if (isConst && allowIn) { // `allowIn == false` indicates for-loop, cf. validateFor{InOf} reportSyntaxError(Messages.Key.ConstMissingInitialiser); } binding = bindingIdentifier; } return new LexicalBinding(binding, initialiser); } /** * <strong>[12.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifier() { String identifier = identifier(); if (context.strictMode != StrictMode.NonStrict) { if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportStrictModeSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } } return new BindingIdentifier(identifier); } /** * <strong>[12.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifierStrict() { String identifier = identifier(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(identifier); } /** * <strong>[12.2.1] Let and Const Declarations</strong> * * <pre> * Initialiser : * = AssignmentExpression * InitialiserNoIn : * = AssignmentExpressionNoIn * </pre> */ private Expression initialiser(boolean allowIn) { consume(Token.ASSIGN); return assignmentExpression(allowIn); } /** * <strong>[12.2.2] Variable Statement</strong> * * <pre> * VariableStatement : * var VariableDeclarationList ; * </pre> */ private VariableStatement variableStatement() { consume(Token.VAR); List<VariableDeclaration> decls = variableDeclarationList(true); semicolon(); VariableStatement varStmt = new VariableStatement(decls); addVarScopedDeclaration(varStmt); return varStmt; } /** * <strong>[12.2.2] Variable Statement</strong> * * <pre> * VariableDeclarationList : * VariableDeclaration * VariableDeclarationList , VariableDeclaration * VariableDeclarationListNoIn : * VariableDeclarationNoIn * VariableDeclarationListNoIn , VariableDeclarationNoIn * </pre> */ private List<VariableDeclaration> variableDeclarationList(boolean allowIn) { List<VariableDeclaration> list = newSmallList(); list.add(variableDeclaration(allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(variableDeclaration(allowIn)); } return list; } /** * <strong>[12.2.2] Variable Statement</strong> * * <pre> * VariableDeclaration : * BindingIdentifier Initialiser<sub>opt</sub> * BindingPattern Initialiser * VariableDeclarationNoIn : * BindingIdentifier InitialiserNoIn<sub>opt</sub> * BindingPattern InitialiserNoIn * </pre> */ private VariableDeclaration variableDeclaration(boolean allowIn) { Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addVarDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false` initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addVarDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } binding = bindingIdentifier; } return new VariableDeclaration(binding, initialiser); } /** * <strong>[12.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingPattern : * ObjectBindingPattern * ArrayBindingPattern * </pre> */ private BindingPattern bindingPattern() { if (token() == Token.LC) { return objectBindingPattern(); } else { return arrayBindingPattern(); } } /** * <strong>[12.2.4] Destructuring Binding Patterns</strong> * * <pre> * ObjectBindingPattern : * { } * { BindingPropertyList } * { BindingPropertyList , } * BindingPropertyList : * BindingProperty * BindingPropertyList , BindingProperty * BindingProperty : * SingleNameBinding * PropertyName : BindingElement * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * PropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private ObjectBindingPattern objectBindingPattern() { List<BindingProperty> list = newSmallList(); consume(Token.LC); if (token() != Token.RC) { list.add(bindingProperty()); while (token() != Token.RC) { consume(Token.COMMA); list.add(bindingProperty()); } } consume(Token.RC); objectBindingPattern_StaticSemantics(list); return new ObjectBindingPattern(list); } /** * <strong>[12.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingProperty : * SingleNameBinding * PropertyName : BindingElement * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * BindingIdentifier : * Identifier * </pre> */ private BindingProperty bindingProperty() { if (LOOKAHEAD(Token.COLON)) { PropertyName propertyName = propertyName(); consume(Token.COLON); Binding binding; if (token() == Token.LC) { binding = objectBindingPattern(); } else if (token() == Token.LB) { binding = arrayBindingPattern(); } else { binding = bindingIdentifierStrict(); } Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(propertyName, binding, initialiser); } else { BindingIdentifier binding = bindingIdentifierStrict(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(binding, initialiser); } } /** * <strong>[12.2.4] Destructuring Binding Patterns</strong> * * <pre> * ArrayBindingPattern : * [ Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ] * [ BindingElementList ] * [ BindingElementList , Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ] * BindingElementList : * Elision<sub>opt</sub> BindingElement * BindingElementList , Elision<sub>opt</sub> BindingElement * BindingRestElement : * ... BindingIdentifier * </pre> */ private ArrayBindingPattern arrayBindingPattern() { List<BindingElementItem> list = newSmallList(); consume(Token.LB); boolean needComma = false; Token tok; while ((tok = token()) != Token.RB) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new BindingElision()); } else if (tok == Token.TRIPLE_DOT) { consume(Token.TRIPLE_DOT); list.add(new BindingRestElement(bindingIdentifierStrict())); break; } else { list.add(bindingElementStrict()); needComma = true; } } consume(Token.RB); arrayBindingPattern_StaticSemantics(list); return new ArrayBindingPattern(list); } /** * <pre> * Binding : * BindingIdentifier * BindingPattern * </pre> */ private Binding binding() { switch (token()) { case LC: return objectBindingPattern(); case LB: return arrayBindingPattern(); default: return bindingIdentifier(); } } /** * <pre> * Binding : * BindingIdentifier * BindingPattern * </pre> */ private Binding bindingStrict() { switch (token()) { case LC: return objectBindingPattern(); case LB: return arrayBindingPattern(); default: return bindingIdentifierStrict(); } } /** * <strong>[12.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * </pre> */ private BindingElement bindingElement() { Binding binding = binding(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(binding, initialiser); } /** * <strong>[12.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * </pre> */ private BindingElement bindingElementStrict() { Binding binding = bindingStrict(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(binding, initialiser); } private static String BoundName(BindingIdentifier binding) { return binding.getName(); } private static String BoundName(BindingRestElement element) { return element.getBindingIdentifier().getName(); } private void objectBindingPattern_StaticSemantics(List<BindingProperty> list) { for (BindingProperty property : list) { // BindingProperty : PropertyName ':' BindingElement // BindingProperty : BindingIdentifier Initialiser<opt> Binding binding = property.getBinding(); if (binding instanceof BindingIdentifier) { String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } } else { assert binding instanceof BindingPattern; assert property.getPropertyName() != null; // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) binding).getList()); // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) // binding).getElements()); } } } private void arrayBindingPattern_StaticSemantics(List<BindingElementItem> list) { for (BindingElementItem element : list) { if (element instanceof BindingElement) { Binding binding = ((BindingElement) element).getBinding(); if (binding instanceof ArrayBindingPattern) { // already done implicitly // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) binding) // .getElements()); } else if (binding instanceof ObjectBindingPattern) { // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) // binding).getList()); } else { assert (binding instanceof BindingIdentifier); String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } } } else if (element instanceof BindingRestElement) { String name = BoundName(((BindingRestElement) element)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(Messages.Key.StrictModeRestrictedIdentifier); } } else { assert element instanceof BindingElision; } } } /** * <strong>[12.3] Empty Statement</strong> * * <pre> * EmptyStatement: * ; * </pre> */ private EmptyStatement emptyStatement() { consume(Token.SEMI); return new EmptyStatement(); } /** * <strong>[12.4] Expression Statement</strong> * * <pre> * ExpressionStatement : * [LA &#x2209; { <b>{, function, class</b> }] Expression ; * </pre> */ private ExpressionStatement expressionStatement() { switch (token()) { case LC: case FUNCTION: case CLASS: reportSyntaxError(Messages.Key.InvalidToken, token().toString()); default: Expression expr = expression(true); semicolon(); return new ExpressionStatement(expr); } } /** * <strong>[12.5] The <code>if</code> Statement</strong> * * <pre> * IfStatement : * if ( Expression ) Statement else Statement * if ( Expression ) Statement * </pre> */ private IfStatement ifStatement() { consume(Token.IF); consume(Token.LP); Expression test = expression(true); consume(Token.RP); Statement then = statement(); Statement otherwise = null; if (token() == Token.ELSE) { consume(Token.ELSE); otherwise = statement(); } return new IfStatement(test, then, otherwise); } /** * <strong>[12.6.1] The <code>do-while</code> Statement</strong> * * <pre> * IterationStatement : * do Statement while ( Expression ) ; * </pre> */ private DoWhileStatement doWhileStatement(Set<String> labelSet) { consume(Token.DO); LabelContext labelCx = enterIteration(labelSet); Statement stmt = statement(); exitIteration(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); if (token() == Token.SEMI) { consume(Token.SEMI); } return new DoWhileStatement(labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[12.6.2] The <code>while</code> Statement</strong> * * <pre> * IterationStatement : * while ( Expression ) Statement * </pre> */ private WhileStatement whileStatement(Set<String> labelSet) { consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); LabelContext labelCx = enterIteration(labelSet); Statement stmt = statement(); exitIteration(); return new WhileStatement(labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[12.6.3] The <code>for</code> Statement</strong> <br> * <strong>[12.6.4] The <code>for-in</code> and <code>for-of</code> Statements</strong> * * <pre> * IterationStatement : * for ( ExpressionNoIn<sub>opt</sub> ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( var VariableDeclarationListNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( LexicalDeclarationNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( LeftHandSideExpression in Expression ) Statement * for ( var ForBinding in Expression ) Statement * for ( ForDeclaration in Expression ) Statement * for ( LeftHandSideExpression of Expression ) Statement * for ( var ForBinding of Expression ) Statement * for ( ForDeclaration of Expression ) Statement * ForDeclaration : * LetOrConst ForBinding * ForBinding : * BindingIdentifier * BindingPattern * </pre> */ private IterationStatement forStatement(Set<String> labelSet) { consume(Token.FOR); consume(Token.LP); BlockContext lexBlockContext = null; Node head; switch (token()) { case VAR: consume(Token.VAR); VariableStatement varStmt = new VariableStatement(variableDeclarationList(false)); addVarScopedDeclaration(varStmt); head = varStmt; break; case LET: case CONST: lexBlockContext = enterBlockContext(); head = lexicalDeclaration(false); break; case SEMI: head = null; break; default: head = expression(false); break; } if (token() == Token.SEMI) { head = validateFor(head); consume(Token.SEMI); Expression test = null; if (token() != Token.SEMI) { test = expression(true); } consume(Token.SEMI); Expression step = null; if (token() != Token.RP) { step = expression(true); } consume(Token.RP); LabelContext labelCx = enterIteration(labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForStatement iteration = new ForStatement(lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, test, step, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else if (token() == Token.IN) { head = validateForInOf(head); consume(Token.IN); Expression expr = expression(true); consume(Token.RP); LabelContext labelCx = enterIteration(labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForInStatement iteration = new ForInStatement(lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else { head = validateForInOf(head); consume("of"); Expression expr = assignmentExpression(true); consume(Token.RP); LabelContext labelCx = enterIteration(labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForOfStatement iteration = new ForOfStatement(lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } /** * @see #forStatement() */ private Node validateFor(Node head) { if (head instanceof VariableStatement) { for (VariableDeclaration decl : ((VariableStatement) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(Messages.Key.DestructuringMissingInitialiser); } } } else if (head instanceof LexicalDeclaration) { boolean isConst = ((LexicalDeclaration) head).getType() == LexicalDeclaration.Type.Const; for (LexicalBinding decl : ((LexicalDeclaration) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(Messages.Key.DestructuringMissingInitialiser); } if (isConst && decl.getInitialiser() == null) { reportSyntaxError(Messages.Key.ConstMissingInitialiser); } } } return head; } /** * @see #forStatement() */ private Node validateForInOf(Node head) { if (head instanceof VariableStatement) { // expected: single variable declaration with no initialiser List<VariableDeclaration> elements = ((VariableStatement) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof LexicalDeclaration) { // expected: single lexical binding with no initialiser List<LexicalBinding> elements = ((LexicalDeclaration) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof Expression) { // expected: left-hand side expression LeftHandSideExpression lhs = validateAssignment((Expression) head); if (lhs == null) { reportSyntaxError(Messages.Key.InvalidAssignmentTarget); } return lhs; } throw reportSyntaxError(Messages.Key.InvalidForInOfHead); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateSimpleAssignment(Expression lhs) { if (lhs instanceof Identifier) { if (context.strictMode != StrictMode.NonStrict) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidAssignmentTarget); } } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getExpression() != null || superExpr.getName() != null) { return superExpr; } } // everything else => invalid lhs return null; } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateAssignment(Expression lhs) { // rewrite object/array literal to destructuring form if (lhs instanceof ObjectLiteral) { ObjectAssignmentPattern pattern = toDestructuring((ObjectLiteral) lhs); if (lhs.isParenthesised()) { pattern.addParentheses(); } return pattern; } else if (lhs instanceof ArrayLiteral) { ArrayAssignmentPattern pattern = toDestructuring((ArrayLiteral) lhs); if (lhs.isParenthesised()) { pattern.addParentheses(); } return pattern; } return validateSimpleAssignment(lhs); } private ObjectAssignmentPattern toDestructuring(ObjectLiteral object) { List<AssignmentProperty> list = newSmallList(); for (PropertyDefinition p : object.getProperties()) { AssignmentProperty property; if (p instanceof PropertyValueDefinition) { // AssignmentProperty : PropertyName ':' AssignmentElement // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression PropertyValueDefinition def = (PropertyValueDefinition) p; PropertyName propertyName = def.getPropertyName(); Expression propertyValue = def.getPropertyValue(); LeftHandSideExpression target; Expression initialiser; if (propertyValue instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) propertyValue; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(Messages.Key.InvalidDestructuring, p.getLine()); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(propertyValue); initialiser = null; } property = new AssignmentProperty(propertyName, target, initialiser); } else if (p instanceof PropertyNameDefinition) { // AssignmentProperty : Identifier PropertyNameDefinition def = (PropertyNameDefinition) p; property = assignmentProperty(def.getPropertyName(), null); } else if (p instanceof CoverInitialisedName) { // AssignmentProperty : Identifier Initialiser CoverInitialisedName def = (CoverInitialisedName) p; property = assignmentProperty(def.getPropertyName(), def.getInitialiser()); } else { assert p instanceof MethodDefinition; throw reportSyntaxError(Messages.Key.InvalidDestructuring, p.getLine()); } list.add(property); } return new ObjectAssignmentPattern(list); } private ArrayAssignmentPattern toDestructuring(ArrayLiteral array) { List<AssignmentElementItem> list = newSmallList(); for (Expression e : array.getElements()) { AssignmentElementItem element; if (e instanceof Elision) { // Elision element = (Elision) e; } else if (e instanceof SpreadElement) { // AssignmentRestElement : ... DestructuringAssignmentTarget // DestructuringAssignmentTarget : LeftHandSideExpression Expression expression = ((SpreadElement) e).getExpression(); // FIXME: spec bug (need to assert only simple-assignment-target) LeftHandSideExpression target = destructuringSimpleAssignmentTarget(expression); element = new AssignmentRestElement(target); } else { // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression LeftHandSideExpression target; Expression initialiser; if (e instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) e; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(Messages.Key.InvalidDestructuring, e.getLine()); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(e); initialiser = null; } element = new AssignmentElement(target, initialiser); } list.add(element); } return new ArrayAssignmentPattern(list); } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, true); } private LeftHandSideExpression destructuringSimpleAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, false); } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs, boolean extended) { if (lhs instanceof Identifier) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportSyntaxError(Messages.Key.InvalidAssignmentTarget, lhs.getLine()); } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (extended && lhs instanceof ObjectAssignmentPattern) { return (ObjectAssignmentPattern) lhs; } else if (extended && lhs instanceof ArrayAssignmentPattern) { return (ArrayAssignmentPattern) lhs; } else if (extended && lhs instanceof ObjectLiteral) { ObjectAssignmentPattern pattern = toDestructuring((ObjectLiteral) lhs); if (lhs.isParenthesised()) { pattern.addParentheses(); } return pattern; } else if (extended && lhs instanceof ArrayLiteral) { ArrayAssignmentPattern pattern = toDestructuring((ArrayLiteral) lhs); if (lhs.isParenthesised()) { pattern.addParentheses(); } return pattern; } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getExpression() != null || superExpr.getName() != null) { return superExpr; } } // FIXME: spec bug (IsInvalidAssignmentPattern not defined) // everything else => invalid lhs throw reportSyntaxError(Messages.Key.InvalidDestructuring, lhs.getLine()); } private AssignmentProperty assignmentProperty(Identifier identifier, Expression initialiser) { switch (identifier.getName()) { case "eval": case "arguments": case "this": case "super": reportSyntaxError(Messages.Key.InvalidDestructuring, identifier.getLine()); } return new AssignmentProperty(identifier, initialiser); } /** * <strong>[12.7] The <code>continue</code> Statement</strong> * * <pre> * ContinueStatement : * continue ; * continue [no <i>LineTerminator</i> here] Identifier ; * </pre> */ private ContinueStatement continueStatement() { String label; consume(Token.CONTINUE); if (noLineTerminator() && isIdentifier(token())) { label = identifier(); } else { label = null; } semicolon(); LabelContext target = findContinueTarget(label); if (target == null && label == null) { reportSyntaxError(Messages.Key.InvalidContinueTarget); } if (target == null && label != null) { reportSyntaxError(Messages.Key.LabelTargetNotFound, label); } if (target.type != StatementType.Iteration) { reportSyntaxError(Messages.Key.InvalidContinueTarget); } target.mark(Abrupt.Continue); return new ContinueStatement(label); } /** * <strong>[12.8] The <code>break</code> Statement</strong> * * <pre> * BreakStatement : * break ; * break [no <i>LineTerminator</i> here] Identifier ; * </pre> */ private BreakStatement breakStatement() { String label; consume(Token.BREAK); if (noLineTerminator() && isIdentifier(token())) { label = identifier(); } else { label = null; } semicolon(); LabelContext target = findBreakTarget(label); if (target == null && label == null) { reportSyntaxError(Messages.Key.InvalidBreakTarget); } if (target == null && label != null) { reportSyntaxError(Messages.Key.LabelTargetNotFound, label); } target.mark(Abrupt.Break); return new BreakStatement(label); } /** * <strong>[12.9] The <code>return</code> Statement</strong> * * <pre> * ReturnStatement : * return ; * return [no <i>LineTerminator</i> here] Expression ; * </pre> */ private ReturnStatement returnStatement() { if (context.kind == ContextKind.Script) { reportSyntaxError(Messages.Key.InvalidReturnStatement); } Expression expr = null; consume(Token.RETURN); if (noLineTerminator() && !(token() == Token.SEMI || token() == Token.RC)) { expr = expression(true); } semicolon(); return new ReturnStatement(expr); } /** * <strong>[12.10] The <code>with</code> Statement</strong> * * <pre> * WithStatement : * with ( Expression ) Statement * </pre> */ private WithStatement withStatement() { reportStrictModeSyntaxError(Messages.Key.StrictModeWithStatement); consume(Token.WITH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); BlockContext scope = enterWithContext(); Statement stmt = statement(); exitWithContext(); WithStatement withStatement = new WithStatement(scope, expr, stmt); scope.node = withStatement; return withStatement; } /** * <strong>[12.11] The <code>switch</code> Statement</strong> * * <pre> * SwitchStatement : * switch ( Expression ) CaseBlock * CaseBlock : * { CaseClauses<sub>opt</sub> } * { CaseClauses<sub>opt</sub> DefaultClause CaseClauses<sub>opt</sub> } * CaseClauses : * CaseClause * CaseClauses CaseClause * CaseClause : * case Expression : StatementList<sub>opt</sub> * DefaultClause : * default : StatementList<sub>opt</sub> * </pre> */ private SwitchStatement switchStatement(Set<String> labelSet) { List<SwitchClause> clauses = newList(); consume(Token.SWITCH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); consume(Token.LC); LabelContext labelCx = enterBreakable(labelSet); BlockContext scope = enterBlockContext(); boolean hasDefault = false; for (;;) { Expression caseExpr; Token tok = token(); if (tok == Token.CASE) { consume(Token.CASE); caseExpr = expression(true); consume(Token.COLON); } else if (tok == Token.DEFAULT && !hasDefault) { hasDefault = true; consume(Token.DEFAULT); consume(Token.COLON); caseExpr = null; } else { break; } List<StatementListItem> list = newList(); statementlist: for (;;) { switch (token()) { case CASE: case DEFAULT: case RC: break statementlist; default: list.add(statementListItem()); } } clauses.add(new SwitchClause(caseExpr, list)); } exitBlockContext(); exitBreakable(); consume(Token.RC); SwitchStatement switchStatement = new SwitchStatement(scope, labelCx.abrupts, labelCx.labelSet, expr, clauses); scope.node = switchStatement; return switchStatement; } /** * <strong>[12.12] Labelled Statements</strong> * * <pre> * LabelledStatement : * Identifier : Statement * </pre> */ private Statement labelledStatement() { HashSet<String> labelSet = new HashSet<>(4); labels: for (;;) { switch (token()) { case FOR: return forStatement(labelSet); case WHILE: return whileStatement(labelSet); case DO: return doWhileStatement(labelSet); case SWITCH: return switchStatement(labelSet); case NAME: if (LOOKAHEAD(Token.COLON)) { String name = identifier(); consume(Token.COLON); labelSet.add(name); break; } case LC: case VAR: case SEMI: case IF: case CONTINUE: case BREAK: case RETURN: case WITH: case THROW: case TRY: case DEBUGGER: default: break labels; } } assert !labelSet.isEmpty(); LabelContext labelCx = enterLabelled(StatementType.Statement, labelSet); Statement stmt = statement(); exitLabelled(); return new LabelledStatement(labelCx.abrupts, labelCx.labelSet, stmt); } /** * <strong>[12.13] The <code>throw</code> Statement</strong> * * <pre> * ThrowStatement : * throw [no <i>LineTerminator</i> here] Expression ; * </pre> */ private ThrowStatement throwStatement() { consume(Token.THROW); if (!noLineTerminator()) { reportSyntaxError(Messages.Key.UnexpectedEndOfLine); } Expression expr = expression(true); semicolon(); return new ThrowStatement(expr); } /** * <strong>[12.14] The <code>try</code> Statement</strong> * * <pre> * TryStatement : * try Block Catch * try Block Finally * try Block Catch Finally * Catch : * catch ( CatchParameter ) Block * Finally : * finally Block * CatchParameter : * BindingIdentifier * BindingPattern * </pre> */ private TryStatement tryStatement() { BlockStatement tryBlock, finallyBlock = null; CatchNode catchNode = null; consume(Token.TRY); tryBlock = block(NO_INHERITED_BINDING); Token tok = token(); if (tok == Token.CATCH) { consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); consume(Token.RP); // catch-block receives a blacklist of forbidden lexical declarable names BlockStatement catchBlock = block(catchParameter); removeLexDeclaredName((ScopeContext) catchBlock.getScope(), catchParameter); exitBlockContext(); catchNode = new CatchNode(catchScope, catchParameter, catchBlock); catchScope.node = catchNode; if (token() == Token.FINALLY) { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } } else { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } return new TryStatement(tryBlock, catchNode, finallyBlock); } /** * <strong>[12.15] The <code>debugger</code> Statement</strong> * * <pre> * DebuggerStatement : * debugger ; * </pre> */ private DebuggerStatement debuggerStatement() { consume(Token.DEBUGGER); semicolon(); return new DebuggerStatement(); } /** * <strong>[11.1] Primary Expressions</strong> * * <pre> * PrimaryExpresion : * this * Identifier * Literal * ArrayInitialiser * ObjectLiteral * FunctionExpression * ClassExpression * GeneratorExpression * GeneratorComprehension * [Lexical goal <i>InputElementRegExp</i>] RegularExpressionLiteral * TemplateLiteral * CoverParenthesizedExpressionAndArrowParameterList * Literal : * NullLiteral * ValueLiteral * ValueLiteral : * BooleanLiteral * NumericLiteral * StringLiteral * </pre> */ private Expression primaryExpression() { Token tok = token(); switch (tok) { case THIS: consume(tok); return new ThisExpression(); case NULL: consume(tok); return new NullLiteral(); case FALSE: case TRUE: consume(tok); return new BooleanLiteral(tok == Token.TRUE); case NUMBER: double number = ts.getNumber(); consume(tok); return new NumericLiteral(number); case STRING: String string = ts.getString(); consume(tok); return new StringLiteral(string); case DIV: case ASSIGN_DIV: String[] re = ts.readRegularExpression(tok); consume(tok); return new RegularExpressionLiteral(re[0], re[1]); case LB: return arrayInitialiser(); case LC: return objectLiteral(); case FUNCTION: if (LOOKAHEAD(Token.MUL)) { return generatorExpression(); } else { return functionExpression(); } case CLASS: return classExpression(); case LP: if (LOOKAHEAD(Token.FOR)) { return generatorComprehension(); } else { return coverParenthesizedExpressionAndArrowParameterList(); } case TEMPLATE: return templateLiteral(false); default: return new Identifier(identifier()); } } /** * <strong>[11.1] Primary Expressions</strong> * * <pre> * CoverParenthesizedExpressionAndArrowParameterList : * ( Expression ) * ( ) * ( ... Identifier ) * ( Expression , ... Identifier) * </pre> */ private Expression coverParenthesizedExpressionAndArrowParameterList() { consume(Token.LP); Expression expr; if (token() == Token.RP) { expr = arrowFunctionEmptyParameters(); } else if (token() == Token.TRIPLE_DOT) { expr = arrowFunctionRestParameter(); } else { // inlined `expression(true)` expr = assignmentExpression(true); if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); if (token() == Token.TRIPLE_DOT) { list.add(arrowFunctionRestParameter()); break; } expr = assignmentExpression(true); list.add(expr); } expr = new CommaExpression(list); } } expr.addParentheses(); consume(Token.RP); return expr; } private EmptyExpression arrowFunctionEmptyParameters() { if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(Messages.Key.EmptyParenthesisedExpression); } return new EmptyExpression(); } private SpreadElement arrowFunctionRestParameter() { consume(Token.TRIPLE_DOT); SpreadElement spread = new SpreadElement(new Identifier(identifier())); if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(Messages.Key.InvalidSpreadExpression); } return spread; } /** * <strong>[11.1.4] Array Initialiser</strong> * * <pre> * ArrayInitialiser : * ArrayLiteral * ArrayComprehension * </pre> */ private ArrayInitialiser arrayInitialiser() { if (LOOKAHEAD(Token.FOR)) { return arrayComprehension(); } else { return arrayLiteral(); } } /** * <strong>[11.1.4] Array Initialiser</strong> * * <pre> * ArrayLiteral : * [ Elision<sub>opt</sub> ] * [ ElementList ] * [ ElementList , Elision<sub>opt</sub> ] * ElementList : * Elision<sub>opt</sub> AssignmentExpression * Elision<sub>opt</sub> SpreadElement * ElementList , Elision<sub>opt</sub> AssignmentExpression * ElementList , Elision<sub>opt</sub> SpreadElement * Elision : * , * Elision , * SpreadElement : * ... AssignmentExpression * </pre> */ private ArrayInitialiser arrayLiteral() { consume(Token.LB); List<Expression> list = newList(); boolean needComma = false; for (Token tok; (tok = token()) != Token.RB;) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new Elision()); } else if (tok == Token.TRIPLE_DOT) { consume(Token.TRIPLE_DOT); list.add(new SpreadElement(assignmentExpression(true))); needComma = true; } else { list.add(assignmentExpression(true)); needComma = true; } } consume(Token.RB); return new ArrayLiteral(list); } /** * <strong>[11.1.4.2] Array Comprehension</strong> * * <pre> * ArrayComprehension : * [ Comprehension ] * </pre> */ private ArrayComprehension arrayComprehension() { consume(Token.LB); Comprehension comprehension = comprehension(); consume(Token.RB); return new ArrayComprehension(comprehension); } /** * <strong>[11.1.4.2] Array Comprehension</strong> * * <pre> * Comprehension : * ComprehensionQualification AssignmentExpression * ComprehensionQualification : * ComprehensionFor ComprehensionQualifierList<sub>opt</sub> * ComprehensionQualifierList : * ComprehensionQualifier * ComprehensionQualifierList ComprehensionQualifier * ComprehensionQualifier : * ComprehensionFor * ComprehensionIf * </pre> */ private Comprehension comprehension() { assert token() == Token.FOR; List<ComprehensionQualifier> list = newSmallList(); int scopes = 0; for (;;) { ComprehensionQualifier qualifier; if (token() == Token.FOR) { scopes += 1; qualifier = comprehensionFor(); } else if (token() == Token.IF) { qualifier = comprehensionIf(); } else { break; } list.add(qualifier); } Expression expression = assignmentExpression(true); while (scopes exitBlockContext(); } return new Comprehension(list, expression); } /** * <strong>[11.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionFor : * for ( ForBinding of AssignmentExpression ) * ForBinding : * BindingIdentifier * BindingPattern * </pre> */ private ComprehensionFor comprehensionFor() { consume(Token.FOR); consume(Token.LP); BlockContext scope = enterBlockContext(); Binding b = binding(); addLexDeclaredName(b); consume("of"); Expression expression = assignmentExpression(true); consume(Token.RP); return new ComprehensionFor(scope, b, expression); } /** * <strong>[11.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionIf : * if ( AssignmentExpression ) * </pre> */ private ComprehensionIf comprehensionIf() { consume(Token.IF); consume(Token.LP); Expression expression = assignmentExpression(true); consume(Token.RP); return new ComprehensionIf(expression); } /** * <strong>[11.1.5] Object Initialiser</strong> * * <pre> * ObjectLiteral : * { } * { PropertyDefinitionList } * { PropertyDefinitionList , } * PropertyDefinitionList : * PropertyDefinition * PropertyDefinitionList , PropertyDefinition * </pre> */ private ObjectLiteral objectLiteral() { List<PropertyDefinition> defs = newList(); consume(Token.LC); while (token() != Token.RC) { defs.add(propertyDefinition()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); return new ObjectLiteral(defs); } /** * <strong>[11.1.5] Object Initialiser</strong> * * <pre> * PropertyDefinition : * IdentifierName * CoverInitialisedName * PropertyName : AssignmentExpression * MethodDefinition * CoverInitialisedName : * IdentifierName Initialiser * </pre> */ private PropertyDefinition propertyDefinition() { if (LOOKAHEAD(Token.COLON)) { PropertyName propertyName = propertyName(); consume(Token.COLON); Expression propertyValue = assignmentExpression(true); return new PropertyValueDefinition(propertyName, propertyValue); } if (LOOKAHEAD(Token.COMMA) || LOOKAHEAD(Token.RC)) { // Static Semantics: It is a Syntax Error if IdentifierName is a // ReservedWord. return new PropertyNameDefinition(new Identifier(identifier())); } if (LOOKAHEAD(Token.ASSIGN)) { Identifier identifier = new Identifier(identifier()); consume(Token.ASSIGN); Expression initialiser = assignmentExpression(true); return new CoverInitialisedName(identifier, initialiser); } return methodDefinition(); } /** * <strong>[11.1.5] Object Initialiser</strong> * * <pre> * PropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private PropertyName propertyName() { switch (token()) { case STRING: String string = ts.getString(); consume(Token.STRING); return new StringLiteral(string); case NUMBER: double number = ts.getNumber(); consume(Token.NUMBER); return new NumericLiteral(number); default: return new Identifier(identifierName()); } } /** * <strong>[11.1.7] Generator Comprehensions</strong> * * <pre> * GeneratorComprehension : * ( Comprehension ) * </pre> */ private GeneratorComprehension generatorComprehension() { consume(Token.LP); Comprehension comprehension = comprehension(); consume(Token.RP); return new GeneratorComprehension(comprehension); } /** * <strong>[11.1.9] Template Literals</strong> * * <pre> * TemplateLiteral : * NoSubstitutionTemplate * TemplateHead Expression [Lexical goal <i>InputElementTemplateTail</i>] TemplateSpans * TemplateSpans : * TemplateTail * TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateTail * TemplateMiddleList : * TemplateMiddle Expression * TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateMiddle Expression * </pre> */ private TemplateLiteral templateLiteral(boolean tagged) { List<Expression> elements = newList(); String[] values = ts.readTemplateLiteral(Token.TEMPLATE); elements.add(new TemplateCharacters(values[0], values[1])); while (token() == Token.LC) { consume(Token.LC); elements.add(expression(true)); values = ts.readTemplateLiteral(Token.RC); elements.add(new TemplateCharacters(values[0], values[1])); } consume(Token.TEMPLATE); return new TemplateLiteral(tagged, elements); } /** * <strong>[11.2] Left-Hand-Side Expressions</strong> * * <pre> * MemberExpression : * PrimaryExpression * MemberExpression [ Expression ] * MemberExpression . IdentifierName * MemberExpression QuasiLiteral * super [ Expression ] * super . IdentifierName * new MemberExpression Arguments * NewExpression : * MemberExpression * new NewExpression * CallExpression : * MemberExpression Arguments * super Arguments * CallExpression Arguments * CallExpression [ Expression ] * CallExpression . IdentifierName * CallExpression QuasiLiteral * LeftHandSideExpression : * NewExpression * CallExpression * </pre> */ private Expression leftHandSideExpression(boolean allowCall) { Expression lhs; if (token() == Token.NEW) { consume(Token.NEW); Expression expr = leftHandSideExpression(false); List<Expression> args = null; if (token() == Token.LP) { args = arguments(); } else { args = emptyList(); } lhs = new NewExpression(expr, args); } else if (token() == Token.SUPER) { if (context.kind == ContextKind.Script && !options.contains(Option.FunctionCode)) { reportSyntaxError(Messages.Key.InvalidSuperExpression); } context.setReferencesSuper(); consume(Token.SUPER); switch (token()) { case DOT: consume(Token.DOT); String name = identifierName(); lhs = new SuperExpression(name); break; case LB: consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new SuperExpression(expr); break; case LP: if (!allowCall) { lhs = new SuperExpression(); } else { List<Expression> args = arguments(); lhs = new SuperExpression(args); } break; case TEMPLATE: // handle "new super``" case throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); default: if (!allowCall) { lhs = new SuperExpression(); } else { throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } break; } } else { lhs = primaryExpression(); } lhs.setLine(ts.getLine()); for (;;) { switch (token()) { case DOT: consume(Token.DOT); String name = identifierName(); lhs = new PropertyAccessor(lhs, name); lhs.setLine(ts.getLine()); break; case LB: consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new ElementAccessor(lhs, expr); lhs.setLine(ts.getLine()); break; case LP: if (!allowCall) { return lhs; } if (lhs instanceof Identifier && "eval".equals(((Identifier) lhs).getName())) { context.funContext.directEval = true; } List<Expression> args = arguments(); lhs = new CallExpression(lhs, args); lhs.setLine(ts.getLine()); break; case TEMPLATE: TemplateLiteral templ = templateLiteral(true); lhs = new TemplateCallExpression(lhs, templ); lhs.setLine(ts.getLine()); break; default: return lhs; } } } /** * <strong>[11.2] Left-Hand-Side Expressions</strong> * * <pre> * Arguments : * () * ( ArgumentList ) * ArgumentList : * AssignmentExpression * ... AssignmentExpression * ArgumentList , AssignmentExpression * ArgumentList , ... AssignmentExpression * </pre> */ private List<Expression> arguments() { List<Expression> args = newSmallList(); boolean needComma = false; consume(Token.LP); while (token() != Token.RP) { if (needComma) { consume(Token.COMMA); needComma = false; } else { Expression expr; if (token() == Token.TRIPLE_DOT) { consume(Token.TRIPLE_DOT); expr = new SpreadElement(assignmentExpression(true)); } else { expr = assignmentExpression(true); } args.add(expr); needComma = true; } } consume(Token.RP); return args; } /** * <strong>[11.3] Postfix Expressions</strong><br> * <strong>[11.4] Unary Operators</strong> * * <pre> * PostfixExpression : * LeftHandSideExpression * LeftHandSideExpression [no <i>LineTerminator</i> here] ++ * LeftHandSideExpression [no <i>LineTerminator</i> here] -- * UnaryExpression : * PostfixExpression * delete UnaryExpression * void UnaryExpression * typeof UnaryExpression * ++ UnaryExpression * -- UnaryExpression * + UnaryExpression * - UnaryExpression * ~ UnaryExpression * ! UnaryExpression * </pre> */ private Expression unaryExpression() { Token tok = token(); switch (tok) { case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: consume(tok); UnaryExpression unary = new UnaryExpression(unaryOp(tok, false), unaryExpression()); unary.setLine(ts.getLine()); if (tok == Token.INC || tok == Token.DEC) { if (validateSimpleAssignment(unary.getOperand()) == null) { reportReferenceError(Messages.Key.InvalidIncDecTarget); } } if (tok == Token.DELETE) { Expression operand = unary.getOperand(); if (operand instanceof Identifier) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidDeleteOperand); } } return unary; default: Expression lhs = leftHandSideExpression(true); if (noLineTerminator()) { tok = token(); if (tok == Token.INC || tok == Token.DEC) { if (validateSimpleAssignment(lhs) == null) { reportReferenceError(Messages.Key.InvalidIncDecTarget); } consume(tok); return new UnaryExpression(unaryOp(tok, true), lhs); } } return lhs; } } private static UnaryExpression.Operator unaryOp(Token tok, boolean postfix) { switch (tok) { case DELETE: return UnaryExpression.Operator.DELETE; case VOID: return UnaryExpression.Operator.VOID; case TYPEOF: return UnaryExpression.Operator.TYPEOF; case INC: return postfix ? UnaryExpression.Operator.POST_INC : UnaryExpression.Operator.PRE_INC; case DEC: return postfix ? UnaryExpression.Operator.POST_DEC : UnaryExpression.Operator.PRE_DEC; case ADD: return UnaryExpression.Operator.POS; case SUB: return UnaryExpression.Operator.NEG; case BITNOT: return UnaryExpression.Operator.BITNOT; case NOT: return UnaryExpression.Operator.NOT; default: return null; } } private Expression binaryExpression(boolean allowIn) { Expression lhs = unaryExpression(); return binaryExpression(allowIn, lhs, BinaryExpression.Operator.OR.getPrecedence()); } private Expression binaryExpression(boolean allowIn, Expression lhs, int minpred) { // Recursive-descent parsers require multiple levels of recursion to // parse binary expressions, to avoid this we're using precedence // climbing here for (;;) { Token tok = token(); if (tok == Token.IN && !allowIn) { break; } BinaryExpression.Operator op = binaryOp(tok); int pred = (op != null ? op.getPrecedence() : -1); if (pred < minpred) { break; } consume(tok); Expression rhs = unaryExpression(); for (;;) { BinaryExpression.Operator op2 = binaryOp(token()); int pred2 = (op2 != null ? op2.getPrecedence() : -1); if (pred2 <= pred) { break; } rhs = binaryExpression(allowIn, rhs, pred2); } lhs = new BinaryExpression(op, lhs, rhs); } return lhs; } private static BinaryExpression.Operator binaryOp(Token token) { switch (token) { case OR: return BinaryExpression.Operator.OR; case AND: return BinaryExpression.Operator.AND; case BITOR: return BinaryExpression.Operator.BITOR; case BITXOR: return BinaryExpression.Operator.BITXOR; case BITAND: return BinaryExpression.Operator.BITAND; case EQ: return BinaryExpression.Operator.EQ; case NE: return BinaryExpression.Operator.NE; case SHEQ: return BinaryExpression.Operator.SHEQ; case SHNE: return BinaryExpression.Operator.SHNE; case LT: return BinaryExpression.Operator.LT; case LE: return BinaryExpression.Operator.LE; case GT: return BinaryExpression.Operator.GT; case GE: return BinaryExpression.Operator.GE; case IN: return BinaryExpression.Operator.IN; case INSTANCEOF: return BinaryExpression.Operator.INSTANCEOF; case SHL: return BinaryExpression.Operator.SHL; case SHR: return BinaryExpression.Operator.SHR; case USHR: return BinaryExpression.Operator.USHR; case ADD: return BinaryExpression.Operator.ADD; case SUB: return BinaryExpression.Operator.SUB; case MUL: return BinaryExpression.Operator.MUL; case DIV: return BinaryExpression.Operator.DIV; case MOD: return BinaryExpression.Operator.MOD; default: return null; } } /** * <strong>[11.12] Conditional Operator</strong><br> * <strong>[11.13] Assignment Operators</strong> * * <pre> * ConditionalExpression : * LogicalORExpression * LogicalORExpression ? AssignmentExpression : AssignmentExpression * ConditionalExpressionNoIn : * LogicalORExpressionNoIn * LogicalORExpressionNoIn ? AssignmentExpression : AssignmentExpressionNoIn * AssignmentExpression : * ConditionalExpression * YieldExpression * ArrowFunction * LeftHandSideExpression = AssignmentExpression * LeftHandSideExpression AssignmentOperator AssignmentExpression * AssignmentExpressionNoIn : * ConditionalExpressionNoIn * YieldExpression * ArrowFunction * LeftHandSideExpression = AssignmentExpressionNoIn * LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn * </pre> */ private Expression assignmentExpression(boolean allowIn) { // TODO: this may need to be changed... if (token() == Token.YIELD) { return yieldExpression(); } long marker = ts.marker(); Expression left = binaryExpression(allowIn); Token tok = token(); if (tok == Token.HOOK) { consume(Token.HOOK); Expression then = assignmentExpression(true); consume(Token.COLON); Expression otherwise = assignmentExpression(allowIn); return new ConditionalExpression(left, then, otherwise); } else if (tok == Token.ARROW) { ts.reset(marker); // return arrowFunctionTail(left); return arrowFunction(); } else if (tok == Token.ASSIGN) { LeftHandSideExpression lhs = validateAssignment(left); if (lhs == null) { reportReferenceError(Messages.Key.InvalidAssignmentTarget); } consume(Token.ASSIGN); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else if (isAssignmentOperator(tok)) { LeftHandSideExpression lhs = validateSimpleAssignment(left); if (lhs == null) { reportReferenceError(Messages.Key.InvalidAssignmentTarget); } consume(tok); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else { return left; } } private static AssignmentExpression.Operator assignmentOp(Token token) { switch (token) { case ASSIGN: return AssignmentExpression.Operator.ASSIGN; case ASSIGN_ADD: return AssignmentExpression.Operator.ASSIGN_ADD; case ASSIGN_SUB: return AssignmentExpression.Operator.ASSIGN_SUB; case ASSIGN_MUL: return AssignmentExpression.Operator.ASSIGN_MUL; case ASSIGN_DIV: return AssignmentExpression.Operator.ASSIGN_DIV; case ASSIGN_MOD: return AssignmentExpression.Operator.ASSIGN_MOD; case ASSIGN_SHL: return AssignmentExpression.Operator.ASSIGN_SHL; case ASSIGN_SHR: return AssignmentExpression.Operator.ASSIGN_SHR; case ASSIGN_USHR: return AssignmentExpression.Operator.ASSIGN_USHR; case ASSIGN_BITAND: return AssignmentExpression.Operator.ASSIGN_BITAND; case ASSIGN_BITOR: return AssignmentExpression.Operator.ASSIGN_BITOR; case ASSIGN_BITXOR: return AssignmentExpression.Operator.ASSIGN_BITXOR; default: return null; } } /** * <strong>[11.13] Assignment Operators</strong> * * <pre> * AssignmentOperator : <b>one of</b> * *= /= %= += -= <<= >>= >>>= &= ^= |= * </pre> */ private boolean isAssignmentOperator(Token tok) { switch (tok) { case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: return true; default: return false; } } /** * <strong>[11.14] Comma Operator</strong> * * <pre> * Expression : * AssignmentExpression * Expression , AssignmentExpression * ExpressionNoIn : * AssignmentExpressionNoIn * ExpressionNoIn , AssignmentExpressionNoIn * </pre> */ private Expression expression(boolean allowIn) { Expression expr = assignmentExpression(allowIn); if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); expr = assignmentExpression(allowIn); list.add(expr); } return new CommaExpression(list); } return expr; } /** * <strong>[7.9] Automatic Semicolon Insertion</strong> * * <pre> * </pre> */ private void semicolon() { switch (token()) { case SEMI: consume(Token.SEMI); case RC: case EOF: break; default: if (noLineTerminator()) { reportSyntaxError(Messages.Key.MissingSemicolon); } } } /** * Peek next token and check for line-terminator */ private boolean noLineTerminator() { return !ts.hasCurrentLineTerminator(); } /** * Return token name */ private String getName(Token tok) { if (tok == Token.NAME) { return ts.getString(); } return tok.getName(); } /** * <strong>[7.6] Identifier Names and Identifiers</strong> * * <pre> * Identifier :: * IdentifierName but not ReservedWord * ReservedWord :: * Keyword * FutureReservedWord * NullLiteral * BooleanLiteral * </pre> */ private String identifier() { Token tok = token(); if (!isIdentifier(tok)) { reportTokenMismatch("<identifier>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[7.6] Identifier Names and Identifiers</strong> */ private boolean isIdentifier(Token tok) { return isIdentifier(tok, context.strictMode); } /** * <strong>[7.6] Identifier Names and Identifiers</strong> */ private boolean isIdentifier(Token tok, StrictMode strictMode) { switch (tok) { case NAME: return true; case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: // TODO: otherwise cannot parse YieldExpression, context dependent syntax restriction? // case YIELD: if (strictMode != StrictMode.NonStrict) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); } return (strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[7.6] Identifier Names and Identifiers</strong> */ private String identifierName() { Token tok = token(); if (!isIdentifierName(tok)) { reportTokenMismatch("<identifier-name>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[7.6] Identifier Names and Identifiers</strong> */ private static boolean isIdentifierName(Token tok) { switch (tok) { case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case ENUM: case EXPORT: case EXTENDS: case FALSE: case FINALLY: case FOR: case FUNCTION: case IF: case IMPLEMENTS: case IMPORT: case IN: case INSTANCEOF: case INTERFACE: case LET: case NAME: case NEW: case NULL: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case RETURN: case STATIC: case SUPER: case SWITCH: case THIS: case THROW: case TRUE: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: case YIELD: return true; default: return false; } } }
package com.github.ansell.csvsum; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Stream; import com.fasterxml.jackson.databind.SequenceWriter; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.github.ansell.jdefaultdict.JDefaultDict; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; /** * Summarises CSV files to easily debug and identify likely parse issues before * pushing them through a more heavy tool or process. * * @author Peter Ansell p_ansell@yahoo.com */ public final class CSVSummariser { /** * The default number of samples to include for each field in the summarised * CSV. */ private static final int DEFAULT_SAMPLE_COUNT = 20; /** * Private constructor for static only class */ private CSVSummariser() { } public static void main(String... args) throws Exception { final OptionParser parser = new OptionParser(); final OptionSpec<Void> help = parser.accepts("help").forHelp(); final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input CSV file to be summarised."); final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class) .describedAs("The output file, or the console if not specified."); final OptionSpec<Integer> samplesToShow = parser.accepts("samples").withRequiredArg().ofType(Integer.class) .defaultsTo(DEFAULT_SAMPLE_COUNT).describedAs( "The maximum number of sample values for each field to include in the output, or -1 to dump all sample values for each field."); OptionSet options = null; try { options = parser.parse(args); } catch (final OptionException e) { System.out.println(e.getMessage()); parser.printHelpOn(System.out); throw e; } if (options.has(help)) { parser.printHelpOn(System.out); return; } final Path inputPath = input.value(options).toPath(); if (!Files.exists(inputPath)) { throw new FileNotFoundException("Could not find input CSV file: " + inputPath.toString()); } final Writer writer; if (options.has(output)) { writer = Files.newBufferedWriter(output.value(options).toPath()); } else { writer = new BufferedWriter(new OutputStreamWriter(System.out)); } runSummarise(Files.newBufferedReader(inputPath), writer, samplesToShow.value(options)); } /** * Summarise the CSV file from the input {@link Reader} and emit the summary * CSV file to the output {@link Writer}, including the default maximum * number of sample values in the summary for each field. * * @param input * The input CSV file, as a {@link Reader}. * @param output * The output CSV file as a {@link Writer}. * @throws IOException * If there is an error reading or writing. */ public static void runSummarise(Reader input, Writer output) throws IOException { runSummarise(input, output, DEFAULT_SAMPLE_COUNT); } /** * Summarise the CSV file from the input {@link Reader} and emit the summary * CSV file to the output {@link Writer}, including the given maximum number * of sample values in the summary for each field. * * @param input * The input CSV file, as a {@link Reader}. * @param output * The output CSV file as a {@link Writer}. * @param maxSampleCount * THe maximum number of sample values in the summary for each * field. Set to -1 to include all unique values for each field. * @throws IOException * If there is an error reading or writing. */ public static void runSummarise(Reader input, Writer output, int maxSampleCount) throws IOException { final JDefaultDict<String, AtomicInteger> emptyCounts = new JDefaultDict<>(k -> new AtomicInteger()); final JDefaultDict<String, AtomicInteger> nonEmptyCounts = new JDefaultDict<>(k -> new AtomicInteger()); final JDefaultDict<String, AtomicBoolean> possibleIntegerFields = new JDefaultDict<>( k -> new AtomicBoolean(true)); final JDefaultDict<String, AtomicBoolean> possibleDoubleFields = new JDefaultDict<>( k -> new AtomicBoolean(true)); final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts = new JDefaultDict<String, JDefaultDict<String, AtomicInteger>>( k -> new JDefaultDict<>(l -> new AtomicInteger())); final List<String> headers = new ArrayList<String>(); final AtomicInteger rowCount = new AtomicInteger(); CSVUtil.streamCSV(input, h -> headers.addAll(h), (h, l) -> { rowCount.incrementAndGet(); for (int i = 0; i < h.size(); i++) { if (l.get(i).trim().isEmpty()) { emptyCounts.get(h.get(i)).incrementAndGet(); } else { nonEmptyCounts.get(h.get(i)).incrementAndGet(); valueCounts.get(h.get(i)).get(l.get(i)).incrementAndGet(); try { Integer.parseInt(l.get(i)); } catch (NumberFormatException nfe) { possibleIntegerFields.get(h.get(i)).set(false); } try { Double.parseDouble(l.get(i)); } catch (NumberFormatException nfe) { possibleDoubleFields.get(h.get(i)).set(false); } } } return l; } , l -> { // We are a streaming summariser, and do not store the raw original // lines. Only unique, non-empty, values are stored in the // valueCounts map for uniqueness summaries }); final CsvSchema schema = CsvSchema.builder().addColumn("fieldName") .addColumn("emptyCount", CsvSchema.ColumnType.NUMBER) .addColumn("nonEmptyCount", CsvSchema.ColumnType.NUMBER) .addColumn("uniqueValueCount", CsvSchema.ColumnType.NUMBER) .addColumn("possiblePrimaryKey", CsvSchema.ColumnType.BOOLEAN) .addColumn("possiblyInteger", CsvSchema.ColumnType.BOOLEAN) .addColumn("possiblyFloatingPoint", CsvSchema.ColumnType.BOOLEAN).addColumn("sampleValues") .setUseHeader(true).build(); final StringBuilder sampleValue = new StringBuilder(); final Consumer<? super String> sampleHandler = s -> { if (sampleValue.length() > 0) { sampleValue.append(", "); } sampleValue.append(s); }; try (final SequenceWriter csvWriter = CSVUtil.newCSVWriter(output, schema);) { headers.forEach(h -> { final int emptyCount = emptyCounts.get(h).get(); final int nonEmptyCount = nonEmptyCounts.get(h).get(); final int valueCount = valueCounts.get(h).keySet().size(); final boolean possiblePrimaryKey = valueCount == nonEmptyCount && valueCount == rowCount.get(); boolean possiblyInteger = false; boolean possiblyDouble = false; // Only expose our numeric type guess if non-empty values found if (nonEmptyCount > 0) { possiblyInteger = possibleIntegerFields.get(h).get(); possiblyDouble = possibleDoubleFields.get(h).get(); } final Stream<String> stream = valueCounts.get(h).keySet().stream(); if (maxSampleCount >= 0) { stream.limit(maxSampleCount).sorted().forEach(sampleHandler); if (valueCount > maxSampleCount) { sampleValue.append(", ..."); } } else { stream.sorted().forEach(sampleHandler); } try { csvWriter.write(Arrays.asList(h, emptyCount, nonEmptyCount, valueCount, possiblePrimaryKey, possiblyInteger, possiblyDouble, sampleValue)); } catch (Exception e) { throw new RuntimeException(e); } finally { sampleValue.setLength(0); } }); } } }
package com.gentics.mesh.server; import java.io.File; import com.gentics.mesh.Mesh; import com.gentics.mesh.OptionsLoader; import com.gentics.mesh.context.impl.LoggingConfigurator; import com.gentics.mesh.dagger.MeshInternal; import com.gentics.mesh.etc.config.MeshOptions; import com.gentics.mesh.graphdb.MissingOrientCredentialFixer; import com.gentics.mesh.search.verticle.ElasticsearchHeadVerticle; import com.gentics.mesh.util.DeploymentUtil; import com.gentics.mesh.verticle.admin.AdminGUIVerticle; import io.vertx.core.json.JsonObject; /** * Main runner that is used to deploy a preconfigured set of verticles. */ public class ServerRunner { static { System.setProperty("vertx.httpServiceFactory.cacheDir", "data" + File.separator + "tmp"); System.setProperty("vertx.cacheDirBase", "data" + File.separator + "tmp"); System.setProperty("storage.trackChangedRecordsInWAL", "true"); } public static void main(String[] args) throws Exception { LoggingConfigurator.init(); MeshOptions options = OptionsLoader.createOrloadOptions(args); MissingOrientCredentialFixer.fix(options); Mesh mesh = Mesh.mesh(options); mesh.setCustomLoader((vertx) -> { JsonObject config = new JsonObject(); config.put("port", options.getHttpServerOptions().getPort()); // Add admin ui AdminGUIVerticle adminVerticle = new AdminGUIVerticle(MeshInternal.get().routerStorage()); DeploymentUtil.deployAndWait(vertx, config, adminVerticle, false); // Add elastichead if (options.getSearchOptions().isHttpEnabled()) { ElasticsearchHeadVerticle headVerticle = new ElasticsearchHeadVerticle(MeshInternal.get().routerStorage()); DeploymentUtil.deployAndWait(vertx, config, headVerticle, false); } }); mesh.run(); } }
package io.druid.segment.indexing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.api.client.util.Sets; import io.druid.data.input.impl.InputRowParser; import io.druid.query.aggregation.AggregatorFactory; import io.druid.segment.indexing.granularity.GranularitySpec; import io.druid.segment.indexing.granularity.UniformGranularitySpec; import java.util.Set; public class DataSchema { private final String dataSource; private final InputRowParser parser; private final AggregatorFactory[] aggregators; private final GranularitySpec granularitySpec; @JsonCreator public DataSchema( @JsonProperty("dataSource") String dataSource, @JsonProperty("parser") InputRowParser parser, @JsonProperty("metricsSpec") AggregatorFactory[] aggregators, @JsonProperty("granularitySpec") GranularitySpec granularitySpec ) { this.dataSource = dataSource; final Set<String> dimensionExclusions = Sets.newHashSet(); for (AggregatorFactory aggregator : aggregators) { dimensionExclusions.add(aggregator.getName()); } if (parser != null && parser.getParseSpec() != null && parser.getParseSpec().getTimestampSpec() != null) { dimensionExclusions.add(parser.getParseSpec().getTimestampSpec().getTimestampColumn()); if (parser.getParseSpec().getDimensionsSpec() != null) { this.parser = parser.withParseSpec( parser.getParseSpec() .withDimensionsSpec( parser.getParseSpec() .getDimensionsSpec() .withDimensionExclusions(dimensionExclusions) ) ); } else { this.parser = parser; } } else { this.parser = parser; } this.aggregators = aggregators; this.granularitySpec = granularitySpec == null ? new UniformGranularitySpec(null, null, null, null) : granularitySpec; } @JsonProperty public String getDataSource() { return dataSource; } @JsonProperty public InputRowParser getParser() { return parser; } @JsonProperty("metricsSpec") public AggregatorFactory[] getAggregators() { return aggregators; } @JsonProperty public GranularitySpec getGranularitySpec() { return granularitySpec; } public DataSchema withGranularitySpec(GranularitySpec granularitySpec) { return new DataSchema(dataSource, parser, aggregators, granularitySpec); } }
package com.github.onsdigital.data; import com.github.onsdigital.content.DirectoryListing; import com.github.onsdigital.content.page.base.Page; import com.github.onsdigital.content.service.ContentNotFoundException; import com.github.onsdigital.content.util.ContentUtil; import com.github.onsdigital.data.zebedee.ZebedeeDataService; import com.github.onsdigital.data.zebedee.ZebedeeRequest; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; /** * Route data requests to zebedee if required, else read from the local filesystem. */ public class DataService { private static DataService instance = new DataService(); private DataService() { } public static DataService getInstance() { return instance; } public InputStream readData(String uri, boolean resolveReferences, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException, IOException { if (zebedeeRequest != null) { return ZebedeeDataService.getInstance().readData(uri, zebedeeRequest, resolveReferences); } if (resolveReferences) { try { Page page = readAsPage(uri, true, zebedeeRequest); return IOUtils.toInputStream(page.toJson()); } catch (IOException e) { e.printStackTrace(); } } else { return LocalFileDataService.getInstance().readData(uri); } throw new DataNotFoundException(uri); } public Page readAsPage(String uri, boolean resolveReferences, ZebedeeRequest zebedeeRequest) throws IOException, ContentNotFoundException { if (zebedeeRequest != null) { return ContentUtil.deserialisePage(ZebedeeDataService.getInstance().readData(uri, zebedeeRequest, resolveReferences)); } else { Page page = ContentUtil.deserialisePage(LocalFileDataService.getInstance().readData(uri)); if (resolveReferences) { page.loadReferences(LocalFileDataService.getInstance()); } return page; } } public DirectoryListing readDirectory(String uri, ZebedeeRequest zebedeeRequest) throws ContentNotFoundException { if (zebedeeRequest != null) { return ZebedeeDataService.getInstance().readDirectory(uri, zebedeeRequest); } return LocalFileDataService.getInstance().readDirectory(uri); } }
package io.spine.server.entity; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import io.spine.core.Event; import java.util.Deque; import java.util.Iterator; import java.util.Objects; import static com.google.common.collect.Queues.newArrayDeque; /** * Recent history of an {@linkplain io.spine.server.entity.EventPlayingEntity event-sourced entity}. * * @author Mykhailo Drachuk * @author Alexander Yevsyukov */ public final class RecentHistory { /** * Holds the history of all events which happened to the aggregate since the last snapshot. * * <p>Most recent event come first. * * @see #iterator() */ private final Deque<Event> history = newArrayDeque(); /** * Creates new instance. */ RecentHistory() { super(); } /** * Returns {@code true} if there are no events in the recent history, {@code false} otherwise. */ public boolean isEmpty() { return history.isEmpty(); } /** * Removes all events from the recent history. */ public void clear() { history.clear(); } /** * Creates a new iterator over the recent history items. * * <p>The iterator returns events in the reverse chronological order. That is, most recent * event would be returned first. * * @return an events iterator */ public Iterator<Event> iterator() { final ImmutableList<Event> events = ImmutableList.copyOf(history); return events.iterator(); } /** * Adds events to the aggregate history. * * @param events events in the chronological order */ void addAll(Iterable<Event> events) { for (Event event : events) { history.addFirst(event); } } @Override public int hashCode() { return Objects.hash(history); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final RecentHistory other = (RecentHistory) obj; return Objects.equals(this.history, other.history); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("history", history) .toString(); } }
package org.gluu.oxtrust.action; import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import org.gluu.jsf2.service.FacesService; import org.gluu.oxtrust.security.Identity; import org.gluu.oxtrust.security.OauthData; import org.gluu.oxtrust.service.OpenIdService; import org.gluu.oxtrust.util.OxTrustConstants; import org.jboss.resteasy.client.ClientRequest; import org.slf4j.Logger; import org.xdi.config.oxtrust.AppConfiguration; import org.xdi.util.StringHelper; @Named("logoutAction") @RequestScoped public class LogoutAction implements Serializable { private static final long serialVersionUID = -1887682170119210113L; @Inject private Logger log; @Inject private Identity identity; @Inject private FacesService facesService; @Inject private OpenIdService openIdService; @Inject private AppConfiguration appConfiguration; public void processLogout() throws Exception { opLogout(); identity.logout(); } public void processSsoLogout() throws Exception { identity.logout(); } public String postLogout() { identity.logout(); return OxTrustConstants.RESULT_SUCCESS; } protected void opLogout() throws Exception { OauthData oauthData = identity.getOauthData(); ClientRequest clientRequest = new ClientRequest(openIdService.getOpenIdConfiguration().getEndSessionEndpoint()); if (oauthData.getSessionState() != null) { clientRequest.queryParameter(OxTrustConstants.OXAUTH_SESSION_STATE, oauthData.getSessionState()); } if (oauthData.getIdToken() != null) { clientRequest.queryParameter(OxTrustConstants.OXAUTH_ID_TOKEN_HINT, oauthData.getIdToken()); } clientRequest.queryParameter(OxTrustConstants.OXAUTH_POST_LOGOUT_REDIRECT_URI, appConfiguration.getLogoutRedirectUrl()); facesService.redirectToExternalURL(clientRequest.getUri()); } }
package com.gmail.favorlock.bonesqlib; import com.jolbox.bonecp.BoneCP; import com.jolbox.bonecp.BoneCPConfig; import sun.jdbc.odbc.ee.ConnectionPool; import java.sql.*; import java.util.logging.Logger; /** * @author Evan Lindsay * @date 8/23/13 * @time 1:34 AM */ public abstract class Database { /** * Logger to log errors to. */ protected Logger log; /** * Plugin prefix to display during errors. */ protected final String PREFIX; /** * Database prefix to display after the plugin prefix. */ protected final String DATABASE_PREFIX; /** * Whether the Database is connected or not. */ protected boolean connected; /** * The Database connection pool. */ protected BoneCP connectionPool; /** * The Database connection pool configuration. */ protected BoneCPConfig config; /** * Holder for the last update count by a query. */ public int lastUpdate; /** * Constructor used in child class super(). * * @param log the Logger used by the plugin. * @param prefix the prefix of the plugin. * @param dp the prefix of the database. */ public Database(Logger log, String prefix, String dp) { if (log == null) { // TODO DatabaseException } if (prefix == null || prefix.length() == 0) { // TODO DatabaseException } this.log = log; this.PREFIX = prefix; this.DATABASE_PREFIX = dp; this.connected = false; } /** * Writes information to the console. * * @param message the {@link java.lang.String}. * of content to write to the console. */ protected final String prefix(String message) { return this.PREFIX + this.DATABASE_PREFIX + message; } /** * Writes information to the console. * * @param toWrite the {@link java.lang.String}. * of content to write to the console. */ public final void writeInfo(String toWrite) { if (toWrite != null) { this.log.info(prefix(toWrite)); } } /** * Writes either errors or warnings to the console. * * @param toWrite the {@link java.lang.String}. * written to the console. * @param severe whether console output should appear as an error or warning. */ public final void writeError(String toWrite, boolean severe) { if (toWrite != null) { if (severe) { this.log.severe(prefix(toWrite)); } else { this.log.warning(prefix(toWrite)); } } } /** * Used to check whether the class for the SQL engine is installed. */ protected abstract boolean initialize(); /** * Used to initialize the connection pool using the specified configuration. * @param config the configuration used by the connection pool. */ protected boolean initCP(BoneCPConfig config) throws SQLException { connectionPool = new BoneCP(config); Connection connection = this.getConnection(); if (connection == null) { return false; } else { connected = true; connection.close(); return true; } } /** * Opens a connection pool with the database. */ public abstract boolean open(); /** * Closes the connection pool with the database. */ public final boolean close() { this.connected = false; if (connectionPool != null) { connectionPool.close(); return true; } else { return false; } } /** * Specifies whether the connection pool is connected or not. */ public final boolean isConnected() { return this.connected; } /** * Gets the connection pool variable. */ public final BoneCP getConnectionPool() { return this.connectionPool; } /** * Initializes the connection pool configuration. */ public final void initConfig() { this.config = new BoneCPConfig(); } /** * Gets the connection pool configuration variable. */ public final BoneCPConfig getConfig() { return this.config; } /** * Gets a connection from the connection pool. */ public final Connection getConnection() throws SQLException { return this.getConnectionPool().getConnection(); } /** * Gets the last update count from the last execution. * * @return the last update count. */ public final int getLastUpdateCount() { return this.lastUpdate; } /** * Sends a query to the SQL database. * * @param query the SQL query to send to the database. * @return the table of results from the query. */ public final ResultSet query(String query) throws SQLException { Connection connection = this.getConnection(); Statement statement = connection.createStatement(); ResultSet rs; if (statement.execute(query)) { rs = statement.getResultSet(); connection.close(); return rs; } else { int uc = statement.getUpdateCount(); this.lastUpdate = uc; rs = connection.createStatement().executeQuery("SELECT " + uc); connection.close(); return rs; } } }
package com.iservport.config; import java.io.Serializable; import java.util.Arrays; import javax.inject.Inject; import javax.naming.NamingException; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.helianto.config.AbstractRootContextConfig; import org.helianto.core.config.HeliantoServiceConfig; import org.helianto.core.internal.KeyNameAdapter; import org.helianto.network.service.KeyNameAdapterArray; import org.helianto.user.repository.UserKeyNameAdapterArray; import org.hibernate.ejb.HibernatePersistence; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.jndi.JndiObjectFactoryBean; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration @EnableWebMvc @Import({HeliantoServiceConfig.class}) @ComponentScan( basePackages = { "com.iservport.*.repository" , "com.iservport.*.service" , "com.iservport.*.controller" , "org.helianto.*.controller" , "com.iservport.*.sender" }) @EnableJpaRepositories( basePackages={ "com.iservport.*.repository", "org.helianto.*.repository" }) public class RootContextConfig extends AbstractRootContextConfig { protected String[] getPacakgesToScan() { return new String[] {"org.helianto.*.domain", "com.iservport.*.domain"}; } @Inject private DataSource dataSource; @Inject private JpaVendorAdapter vendorAdapter; @Bean public EntityManagerFactory entityManagerFactory() { LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean(); bean.setDataSource(dataSource); bean.setPackagesToScan(getPacakgesToScan()); bean.setJpaVendorAdapter(vendorAdapter); bean.setPersistenceProvider(new HibernatePersistence()); bean.afterPropertiesSet(); return bean.getObject(); } @Bean public Object jndiObjectFactoryBean() throws IllegalArgumentException, NamingException { JndiObjectFactoryBean jndiFactory = new JndiObjectFactoryBean(); jndiFactory.setJndiName("jdbc/iservportDB"); jndiFactory.setResourceRef(true); jndiFactory.afterPropertiesSet(); return jndiFactory.getObject(); } @Bean public KeyNameAdapterArray keyNameAdapterArray() { return new KeyNameAdapterArray() { @Override public KeyNameAdapter[] values() { return InternalEntityType.values(); } }; } @Bean public UserKeyNameAdapterArray userKeyNameAdapterArray() { return new UserKeyNameAdapterArray() { @Override public KeyNameAdapter[] values() { return InternalUserType.values(); } }; } /** * Internal entity types. * * @author mauriciofernandesdecastro */ static enum InternalEntityType implements KeyNameAdapter { CUSTOMER('C', "Clientes") , AGENT('A', "Agentes"); private char value; private String desc; /** * Constructor. * * @param value */ private InternalEntityType(char value, String desc) { this.value = value; this.desc = desc; } public Serializable getKey() { return this.value; } @Override public String getCode() { return value+""; } @Override public String getName() { return desc; } } /** * Internal user types. * * @author mauriciofernandesdecastro */ static enum InternalUserType implements KeyNameAdapter { USER('A', "Usuários") , ADMIN('G', "Administradores"); private char value; private String desc; /** * Constructor. * * @param value */ private InternalUserType(char value, String desc) { this.value = value; this.desc = desc; } public Serializable getKey() { return this.value; } @Override public String getCode() { return value+""; } @Override public String getName() { return desc; } } @Bean public RestOperations restOperations() { RestTemplate rest = new RestTemplate(); //this is crucial! rest.getMessageConverters().add(0, mappingJackson2HttpMessageConverter()); rest.getMessageConverters().add(1, new ClassFormHttpMessageConverter()); return rest; } @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); converter.setObjectMapper(mapper); converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,APPLICATION_JSON_UTF8)); return converter; } private HttpMessageConverter<Object> createXmlHttpMessageConverter() { MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); return xmlConverter; } public ClassFormHttpMessageConverter() { this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA); this.partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); this.partConverters.add(stringHttpMessageConverter); this.partConverters.add(new ResourceHttpMessageConverter()); } }
package com.lothrazar.samscontent; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemSoup; import net.minecraft.item.ItemStack; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.potion.Potion; import net.minecraftforge.fml.common.registry.GameRegistry; import com.lothrazar.samscontent.item.*; import com.lothrazar.samscontent.item.ItemFoodTeleport.TeleportType; import com.lothrazar.samscontent.potion.PotionRegistry; import com.lothrazar.util.Reference; public class ItemRegistry { public static ItemEnderBook itemEnderBook = null; public static ItemWandBuilding wandBuilding; public static ItemChestSackEmpty wandChest; public static ItemChestSack itemChestSack; public static ItemWandHarvest wandHarvest; public static ItemWandTransform wandTransform; public static ItemWandLivestock wandLivestock; public static ItemWandProspect wandProspect; public static ItemFoodAppleMagic apple_emerald; public static ItemFoodAppleMagic apple_emerald_rich; public static ItemFoodAppleMagic apple_diamond; public static ItemFoodAppleMagic apple_lapis; public static ItemFoodAppleMagic apple_lapis_rich; public static ItemFoodAppleMagic apple_chocolate; public static ItemFoodAppleMagic apple_chocolate_rich; public static ItemFoodAppleMagic apple_nether_star; public static ItemWandFire wandFire; public static ItemWandCopyPaste wandCopy; public static ItemBaseWand baseWand; //public static ItemToolFlint flintTool; public static ItemFoodAppleMagic apple_diamond_rich; public static ItemFoodAppleMagic apple_ender; public static ItemWandWater wandWater; public static ItemWandLightning wandLightning; public static Item beetrootSeed ; public static Item beetrootItem; public static Item beetrootSoup; public static ArrayList<Item> items = new ArrayList<Item>(); public static ItemWandFireball wandFireball; public static ItemWandSnowball wandSnowball; private static ItemFoodTeleport foodBed; private static ItemFoodTeleport foodSpawn; private static ItemFoodTeleport foodSky; public static void registerItem(Item item, String name) { item.setUnlocalizedName(name); GameRegistry.registerItem(item, name); items.add(item); } public static void registerItems() { //needed for all wands; no config. ItemRegistry.baseWand = new ItemBaseWand(); ItemRegistry.registerItem(ItemRegistry.baseWand, "base_wand" ); ItemBaseWand.addRecipe(); ItemRegistry.foodBed = new ItemFoodTeleport(2, TeleportType.BEDHOME); ItemRegistry.registerItem(foodBed, "tpfood_bed"); ItemRegistry.foodSky = new ItemFoodTeleport(2, TeleportType.WORLDHEIGHT); ItemRegistry.registerItem(foodSky, "tpfood_sky"); ItemRegistry.foodSpawn = new ItemFoodTeleport(2, TeleportType.WORLDSPAWN); ItemRegistry.registerItem(foodSpawn, "tpfood_spawn"); if(ModSamsContent.configSettings.beetroot) { beetrootSeed = new ItemSeeds(BlockRegistry.beetrootCrop, Blocks.farmland).setCreativeTab(ModSamsContent.tabSamsContent); ItemRegistry.registerItem(beetrootSeed, "beetroot_seed"); beetrootItem = new ItemFood(3, false).setCreativeTab(ModSamsContent.tabSamsContent); ItemRegistry.registerItem(beetrootItem, "beetroot_item"); beetrootSoup = new ItemSoup(8).setCreativeTab(ModSamsContent.tabSamsContent); ItemRegistry.registerItem(beetrootSoup, "beetroot_soup"); } if(ModSamsContent.configSettings.wandFireball) { ItemRegistry.wandFireball = new ItemWandFireball(); registerItem(ItemRegistry.wandFireball, "wand_fireball"); ItemWandFire.addRecipe(); } if(ModSamsContent.configSettings.wandSnowball) { ItemRegistry.wandSnowball = new ItemWandSnowball(); registerItem(ItemRegistry.wandSnowball, "wand_snowball"); ItemWandSnowball.addRecipe(); } if(ModSamsContent.configSettings.wandFire) { ItemRegistry.wandFire = new ItemWandFire(); registerItem(ItemRegistry.wandFire, "wand_fire"); ItemWandFire.addRecipe(); } if(ModSamsContent.configSettings.wandWater) { ItemRegistry.wandWater = new ItemWandWater(); ItemRegistry.registerItem(ItemRegistry.wandWater, "wand_water"); ItemWandWater.addRecipe(); } if(ModSamsContent.configSettings.wandLightning) { ItemRegistry.wandLightning = new ItemWandLightning(); ItemRegistry.registerItem(ItemRegistry.wandLightning, "wand_lightning"); ItemWandLightning.addRecipe(); } if(ModSamsContent.configSettings.wandCopy) { ItemRegistry.wandCopy = new ItemWandCopyPaste(); ItemRegistry.registerItem(ItemRegistry.wandCopy, "wand_copy"); ItemWandCopyPaste.addRecipe(); } if(ModSamsContent.configSettings.wandBuilding) { ItemRegistry.wandBuilding = new ItemWandBuilding(); ItemRegistry.registerItem(ItemRegistry.wandBuilding, "wand_building" ); ItemWandBuilding.addRecipe(); } if(ModSamsContent.configSettings.wandChest) { ItemRegistry.itemChestSack = new ItemChestSack(); ItemRegistry.registerItem(ItemRegistry.itemChestSack, "chest_sack"); ItemRegistry.wandChest = new ItemChestSackEmpty(); ItemRegistry.registerItem(ItemRegistry.wandChest, "chest_sack_empty"); ItemChestSackEmpty.addRecipe(); } if(ModSamsContent.configSettings.wandTransform) { ItemRegistry.wandTransform = new ItemWandTransform(); ItemRegistry.registerItem(ItemRegistry.wandTransform, "wand_transform"); ItemWandTransform.addRecipe(); } if(ModSamsContent.configSettings.wandHarvest) { ItemRegistry.wandHarvest = new ItemWandHarvest(); ItemRegistry.registerItem(ItemRegistry.wandHarvest, "wand_harvest"); ItemWandHarvest.addRecipe(); } if(ModSamsContent.configSettings.wandLivestock) { ItemRegistry.wandLivestock = new ItemWandLivestock(); ItemRegistry.registerItem(ItemRegistry.wandLivestock, "wand_livestock"); ItemWandLivestock.addRecipe(); } if(ModSamsContent.configSettings.wandProspect) { ItemRegistry.wandProspect = new ItemWandProspect(); ItemRegistry.registerItem(ItemRegistry.wandProspect, "wand_prospect"); ItemWandProspect.addRecipe(); } if(ModSamsContent.configSettings.enderBook) { ItemRegistry.itemEnderBook = new ItemEnderBook(); ItemRegistry.registerItem(ItemRegistry.itemEnderBook, "book_ender"); ItemEnderBook.addRecipe(); } if(ModSamsContent.configSettings.appleEmerald) { ItemRegistry.apple_emerald = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, false); ItemRegistry.apple_emerald.addEffect(PotionRegistry.slowfall.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.apple_emerald.addEffect(Potion.jump.id, ItemFoodAppleMagic.timeShort, PotionRegistry.V); //TERSTING ONLY //ItemRegistry.apple_emerald.addEffect(PotionRegistry.frozen.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_emerald, "apple_emerald"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_emerald,new ItemStack(Items.emerald)); ItemRegistry.apple_emerald_rich = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, true); ItemRegistry.apple_emerald_rich.addEffect(PotionRegistry.slowfall.id, ItemFoodAppleMagic.timeLong, PotionRegistry.I); ItemRegistry.apple_emerald_rich.addEffect(Potion.jump.id, ItemFoodAppleMagic.timeShort, PotionRegistry.V); ItemRegistry.registerItem(ItemRegistry.apple_emerald_rich, "apple_emerald_rich"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_emerald,new ItemStack(Blocks.emerald_block)); } if(ModSamsContent.configSettings.appleDiamond) { ItemRegistry.apple_diamond = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, false); ItemRegistry.apple_diamond.addEffect(PotionRegistry.flying.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.apple_diamond.addEffect(Potion.resistance.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.apple_diamond.addEffect(Potion.absorption.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_diamond, "apple_diamond"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_diamond,new ItemStack(Items.diamond)); ItemRegistry.apple_diamond_rich = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, true); ItemRegistry.apple_diamond_rich.addEffect(PotionRegistry.flying.id, ItemFoodAppleMagic.timeLong, PotionRegistry.I); ItemRegistry.apple_diamond_rich.addEffect(Potion.resistance.id, ItemFoodAppleMagic.timeLong, PotionRegistry.I); ItemRegistry.apple_diamond_rich.addEffect(Potion.absorption.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_diamond_rich, "apple_diamond_rich"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_diamond_rich,new ItemStack(Blocks.diamond_block)); } if(ModSamsContent.configSettings.appleLapis) { ItemRegistry.apple_lapis = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, false); ItemRegistry.apple_lapis.addEffect(PotionRegistry.waterwalk.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_lapis, "apple_lapis"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_lapis,new ItemStack(Items.dye, 1, Reference.dye_lapis) ); ItemRegistry.apple_lapis_rich = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, true); ItemRegistry.apple_lapis_rich.addEffect(PotionRegistry.waterwalk.id, ItemFoodAppleMagic.timeLong,PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_lapis_rich, "apple_lapis_rich"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_lapis_rich,new ItemStack(Blocks.lapis_block)); } if(ModSamsContent.configSettings.appleChocolate) { ItemRegistry.apple_chocolate = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, false); ItemRegistry.apple_chocolate.addEffect(Potion.digSpeed.id, ItemFoodAppleMagic.timeShort, PotionRegistry.I + 1); ItemRegistry.registerItem(ItemRegistry.apple_chocolate, "apple_chocolate"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_chocolate, new ItemStack(Items.dye, 1, Reference.dye_cocoa) ); ItemRegistry.apple_chocolate_rich = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerLarge, true); ItemRegistry.apple_chocolate_rich.addEffect(Potion.digSpeed.id, ItemFoodAppleMagic.timeLong, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_chocolate_rich, "apple_chocolate_rich"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_chocolate_rich, new ItemStack(Items.cookie)); } if(ModSamsContent.configSettings.appleNetherStar) { ItemRegistry.apple_nether_star = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerSmall, true); ItemRegistry.apple_nether_star.addEffect( PotionRegistry.lavawalk.id, ItemFoodAppleMagic.timeLong, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_nether_star, "apple_nether_star"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_nether_star,new ItemStack(Items.nether_wart)); } if(ModSamsContent.configSettings.appleNetherStar)//TODO: apple ender in config { ItemRegistry.apple_ender = new ItemFoodAppleMagic(ItemFoodAppleMagic.hungerLarge, false); ItemRegistry.apple_ender.addEffect(PotionRegistry.ender.id, ItemFoodAppleMagic.timeLong, PotionRegistry.I); ItemRegistry.registerItem(ItemRegistry.apple_ender, "apple_ender"); ItemFoodAppleMagic.addRecipe(ItemRegistry.apple_ender,new ItemStack(Items.ender_pearl)) ; } } }
package com.metacodestudio.hotsuploader; import com.metacodestudio.hotsuploader.files.FileHandler; import com.metacodestudio.hotsuploader.utils.SimpleHttpClient; import com.metacodestudio.hotsuploader.utils.StormHandler; import com.metacodestudio.hotsuploader.versions.ReleaseManager; import com.metacodestudio.hotsuploader.window.HomeController; import io.datafx.controller.flow.Flow; import io.datafx.controller.flow.FlowHandler; import io.datafx.controller.flow.container.DefaultFlowContainer; import io.datafx.controller.flow.context.ViewFlowContext; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import java.awt.*; import java.io.IOException; import java.net.URL; public class Client extends Application { public static void main(String[] args) { Application.launch(Client.class, args); } @Override public void start(final Stage primaryStage) throws Exception { ClassLoader loader = ClassLoader.getSystemClassLoader(); URL logo = loader.getResource("images/logo-desktop.png"); assert logo != null; Image image = new Image(logo.toString()); primaryStage.getIcons().add(image); primaryStage.setResizable(false); primaryStage.setTitle("HotSLogs UploaderFX"); addToTray(logo, primaryStage); Flow flow = new Flow(HomeController.class); FlowHandler flowHandler = flow.createHandler(new ViewFlowContext()); ViewFlowContext flowContext = flowHandler.getFlowContext(); StormHandler stormHandler = new StormHandler(); SimpleHttpClient httpClient = new SimpleHttpClient(); ReleaseManager releaseManager = new ReleaseManager(httpClient); registerInContext(flowContext, stormHandler, releaseManager, setupFileHandler(stormHandler), httpClient); DefaultFlowContainer container = new DefaultFlowContainer(); releaseManager.verifyLocalVersion(stormHandler); StackPane pane = flowHandler.start(container); primaryStage.setScene(new Scene(pane)); primaryStage.show(); } private FileHandler setupFileHandler(final StormHandler stormHandler) throws IOException { FileHandler fileHandler = new FileHandler(stormHandler); fileHandler.cleanup(); fileHandler.registerInitial(); return fileHandler; } private void registerInContext(ViewFlowContext context, Object... itemsToAdd) { for (final Object itemToAdd : itemsToAdd) { context.register(itemToAdd); } } private void addToTray(final URL imageURL, Stage primaryStage) { if (SystemTray.isSupported()) { Platform.setImplicitExit(false); primaryStage.setOnCloseRequest(value -> { primaryStage.hide(); value.consume(); }); SystemTray tray = SystemTray.getSystemTray(); java.awt.Image image = Toolkit.getDefaultToolkit().getImage(imageURL); PopupMenu popup = new PopupMenu(); MenuItem item = new MenuItem("Exit"); popup.add(item); TrayIcon trayIcon = new TrayIcon(image, StormHandler.getApplicationName(), popup); trayIcon.setImageAutoSize(true); trayIcon.addActionListener(event -> Platform.runLater(primaryStage::show)); item.addActionListener(event -> { Platform.exit(); System.exit(0); }); try { tray.add(trayIcon); } catch (AWTException e) { e.printStackTrace(); } } } }
package com.pearson.statspoller.drivers; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.util.StatusPrinter; import com.pearson.statspoller.internal_metric_collectors.statspoller_native.StatsPollerNativeCollectorsThread; import java.io.File; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.pearson.statspoller.globals.ApplicationConfiguration; import com.pearson.statspoller.external_metric_collectors.ExternalMetricCollectorExecuterThread; import com.pearson.statspoller.output.OutputMetricsInvokerThread; import com.pearson.statspoller.external_metric_collectors.ReadMetricsFromFileThread; import com.pearson.statspoller.external_metric_collectors.ExternalMetricCollector; import com.pearson.statspoller.internal_metric_collectors.apache_http.ApacheHttpMetricCollector; import com.pearson.statspoller.internal_metric_collectors.file_counter.FileCounterMetricCollector; import com.pearson.statspoller.internal_metric_collectors.jmx.JmxJvmShutdownHook; import com.pearson.statspoller.internal_metric_collectors.jmx.JmxMetricCollector; import com.pearson.statspoller.internal_metric_collectors.linux.Connections.ConnectionsCollector; import com.pearson.statspoller.internal_metric_collectors.linux.Cpu.CpuCollector; import com.pearson.statspoller.internal_metric_collectors.linux.DiskIo.DiskIoCollector; import com.pearson.statspoller.internal_metric_collectors.linux.FileSystem.FileSystemCollector; import com.pearson.statspoller.internal_metric_collectors.linux.Memory.MemoryCollector; import com.pearson.statspoller.internal_metric_collectors.linux.Network.NetworkBandwidthCollector; import com.pearson.statspoller.internal_metric_collectors.linux.ProcessCounter.ProcessCounterMetricCollector; import com.pearson.statspoller.internal_metric_collectors.linux.Uptime.UptimeCollector; import com.pearson.statspoller.internal_metric_collectors.mongo.MongoMetricCollector; import com.pearson.statspoller.internal_metric_collectors.mysql.MysqlMetricCollector; import com.pearson.statspoller.utilities.FileIo; import com.pearson.statspoller.utilities.StackTrace; import com.pearson.statspoller.utilities.Threads; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ public class Driver { private static final Logger logger = LoggerFactory.getLogger(Driver.class.getName()); private static final ExecutorService threadExecutor_ = Executors.newCachedThreadPool(); public static void main(String[] args) { // 2 second startup delay -- helps to make sure that old metric data isn't output Threads.sleepSeconds(2); boolean initializeSuccess = initializeApplication(); if (!initializeSuccess) { String errorOutput = "An error occurred during application initialization. Shutting down application @ " + new Date(); System.out.println(errorOutput); logger.error(errorOutput); System.exit(-1); } else { String successOutput = "Application successfully initialized @ " + new Date(); System.out.println(successOutput); logger.error(successOutput); } launchStatsPollerCollector(); launchLinuxCollectors(); launchFileCountCollectors(); launchJmxCollectors(); launchApacheCollectors(); launchMongoCollectors(); launchMysqlCollectors(); launchExternalMetricCollectors(); // start the 'output metrics' invoker thread Thread outputMetricsInvokerThread = new Thread(new OutputMetricsInvokerThread(ApplicationConfiguration.getOutputInterval())); outputMetricsInvokerThread.start(); while(true) { Threads.sleepSeconds(1000); } } private static boolean initializeApplication() { boolean doesDevLogConfExist = FileIo.doesFileExist(System.getProperty("user.dir") + File.separator + "conf" + File.separator + "logback_config_dev.xml"); boolean isLogbackSuccess; if (doesDevLogConfExist) isLogbackSuccess = readAndSetLogbackConfiguration(System.getProperty("user.dir") + File.separator + "conf", "logback_config_dev.xml"); else isLogbackSuccess = readAndSetLogbackConfiguration(System.getProperty("user.dir") + File.separator + "conf", "logback_config.xml"); boolean doesDevAppConfExist = FileIo.doesFileExist(System.getProperty("user.dir") + File.separator + "conf" + File.separator + "application_dev.properties"); boolean isApplicationConfigSuccess; if (doesDevAppConfExist) isApplicationConfigSuccess = ApplicationConfiguration.initialize(System.getProperty("user.dir") + File.separator + "conf" + File.separator + "application_dev.properties", true); else isApplicationConfigSuccess = ApplicationConfiguration.initialize(System.getProperty("user.dir") + File.separator + "conf" + File.separator + "application.properties", true); try { File optionalConfigurationFiles_Directory = new File(System.getProperty("user.dir") + File.separator + "conf" + File.separator + "optional"); if (optionalConfigurationFiles_Directory.exists()) { File[] optionalConfigurationFiles = optionalConfigurationFiles_Directory.listFiles(); for (File optionalConfigurationFile : optionalConfigurationFiles) { if (optionalConfigurationFile.getName().endsWith(".properties")) { ApplicationConfiguration.initialize(System.getProperty("user.dir") + File.separator + "conf" + File.separator + "optional" + File.separator + optionalConfigurationFile.getName(), false); } } } } catch (Exception e) { logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } if (!isApplicationConfigSuccess || !isLogbackSuccess) { logger.error("An error during application initialization. Exiting..."); return false; } logger.info("Finish - Initialize application"); return true; } private static boolean readAndSetLogbackConfiguration(String filePath, String fileName) { boolean doesConfigFileExist = FileIo.doesFileExist(filePath, fileName); if (doesConfigFileExist) { File logggerConfigFile = new File(filePath + File.separator + fileName); LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(logggerConfigFile); StatusPrinter.printInCaseOfErrorsOrWarnings(context); return true; } catch (Exception e) { StatusPrinter.printInCaseOfErrorsOrWarnings(context); return false; } } else { return false; } } private static void launchStatsPollerCollector() { // start StatsPoller's built-in metric collectors Thread statsPollerCollectorsThread = new Thread(new StatsPollerNativeCollectorsThread( ApplicationConfiguration.isStatsPollerEnableJavaMetricCollector(), ApplicationConfiguration.getStatspollerJavaMetricCollectorCollectionInterval(), ApplicationConfiguration.getStatspollerMetricCollectorPrefix(), "./output/statspoller_native.out", ApplicationConfiguration.isOutputInternalMetricsToDisk(), Version.getProjectVersion())); threadExecutor_.execute(statsPollerCollectorsThread); } private static void launchFileCountCollectors() { for (FileCounterMetricCollector fileCounterMetricCollector : ApplicationConfiguration.getFileCounterMetricCollectors()) { threadExecutor_.execute(fileCounterMetricCollector); } } private static void launchLinuxCollectors() { // start StatsPoller's built-in linux metric collectors Thread linuxConnectionsCollectorThread = new Thread(new ConnectionsCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.Connections", "./output/linux_connections.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxConnectionsCollectorThread); Thread linuxCpuCollectorThread = new Thread(new CpuCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.Cpu", "./output/linux_cpu.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxCpuCollectorThread); Thread linuxNetworkCollectorThread = new Thread(new NetworkBandwidthCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.Network-Bandwidth", "./output/linux_network_bandwidth.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxNetworkCollectorThread); Thread linuxMemoryCollectorThread = new Thread(new MemoryCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.Memory", "./output/linux_memory.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxMemoryCollectorThread); Thread linuxUptimeCollectorThread = new Thread(new UptimeCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.Uptime", "./output/linux_uptime.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxUptimeCollectorThread); Thread linuxFileSystemCollectorThread = new Thread(new FileSystemCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.FileSystem", "./output/linux_filesystem.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxFileSystemCollectorThread); Thread linuxDiskIoCollectorThread = new Thread(new DiskIoCollector(ApplicationConfiguration.isLinuxMetricCollectorEnable(), ApplicationConfiguration.getLinuxMetricCollectorCollectionInterval(), "Linux.DiskIO", "./output/linux_disk_io.out", ApplicationConfiguration.isOutputInternalMetricsToDisk())); threadExecutor_.execute(linuxDiskIoCollectorThread); Thread processCounterCollectorThread = new Thread(new ProcessCounterMetricCollector(true, ApplicationConfiguration.getProcessCounterMetricCollectorCollectionInterval(), "ProcessCounter", "./output/linux_process_counter.out", ApplicationConfiguration.isOutputInternalMetricsToDisk(), ApplicationConfiguration.getProcessCounterPrefixesAndRegexes())); threadExecutor_.execute(processCounterCollectorThread); } private static void launchJmxCollectors() { // start 'jmx metric collector' threads for (JmxMetricCollector jmxMetricCollector : ApplicationConfiguration.getJmxMetricCollectors()) { threadExecutor_.execute(jmxMetricCollector); } // jvm shutdown hook for jmx -- makes sure that jmx connections get closed before this program is terminated if (!ApplicationConfiguration.getJmxMetricCollectors().isEmpty()) { JmxJvmShutdownHook jmxJvmShutdownHook = new JmxJvmShutdownHook(); Runtime.getRuntime().addShutdownHook(jmxJvmShutdownHook); } } private static void launchApacheCollectors() { for (ApacheHttpMetricCollector apacheHttpMetricCollector : ApplicationConfiguration.getApacheHttpMetricCollectors()) { threadExecutor_.execute(apacheHttpMetricCollector); Threads.sleepSeconds(1); } } private static void launchMongoCollectors() { for (MongoMetricCollector mongoMetricCollector : ApplicationConfiguration.getMongoMetricCollectors()) { threadExecutor_.execute(mongoMetricCollector); } } private static void launchMysqlCollectors() { for (MysqlMetricCollector mysqlMetricCollector : ApplicationConfiguration.getMysqlMetricCollectors()) { threadExecutor_.execute(mysqlMetricCollector); } } private static void launchExternalMetricCollectors() { // start 'metric collector' threads & the corresponding 'read from output file' threads for (ExternalMetricCollector metricCollector : ApplicationConfiguration.getExternalMetricCollectors()) { logger.info("Message=\"Starting metric collector\", Collector=\"" + metricCollector.getMetricPrefix() + "\""); Thread metricCollectorExecuterThread = new Thread(new ExternalMetricCollectorExecuterThread(metricCollector)); threadExecutor_.execute(metricCollectorExecuterThread); Threads.sleepMilliseconds(500); Thread readMetricsFromFileThread = new Thread(new ReadMetricsFromFileThread(metricCollector.getFileFromOutputPathAndFilename(), ApplicationConfiguration.getCheckOutputFilesInterval(), metricCollector.getMetricPrefix())); threadExecutor_.execute(readMetricsFromFileThread); Threads.sleepSeconds(1); } } }