lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
54fdce170cf6f77e54ce3a8a965f7954e5656b84
0
marcrh/gwt-material,guibertjulien/gwt-material,GwtMaterialDesign/gwt-material,marcrh/gwt-material,marcrh/gwt-material,GwtMaterialDesign/gwt-material,guibertjulien/gwt-material,guibertjulien/gwt-material,GwtMaterialDesign/gwt-material
package gwt.material.design.client.base.mixin; /* * #%L * GwtMaterial * %% * Copyright (C) 2015 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import gwt.material.design.client.base.MaterialWidget; import gwt.material.design.client.base.helper.StyleHelper; import gwt.material.design.client.base.mixin.AbstractMixin; /** * @author Ben Dol * @author kevzlou7979 */ public class EnabledMixin<T extends Widget & HasEnabled> extends AbstractMixin<T> implements HasEnabled { private static final String DISABLED = "disabled"; private HandlerRegistration handler; public EnabledMixin(final T widget) { super(widget); } @Override public boolean isEnabled() { return !StyleHelper.containsStyle(uiObject.getStyleName(), "disabled"); } @Override public void setEnabled(boolean enabled) { if(!uiObject.isAttached() && handler == null) { handler = uiObject.addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if(event.isAttached()) { applyEnabled(enabled, uiObject); } else if(handler != null) { handler.removeHandler(); handler = null; } } }); } else { applyEnabled(enabled, uiObject); } } public void setEnabled(MaterialWidget widget, boolean enabled) { for(Widget child : widget.getChildren()) { if(child instanceof MaterialWidget) { ((MaterialWidget) child).setEnabled(enabled); setEnabled((MaterialWidget) child, enabled); } } } private void applyEnabled(boolean enabled, UIObject obj) { if(enabled) { obj.removeStyleName("disabled"); obj.getElement().removeAttribute(DISABLED); } else { obj.addStyleName("disabled"); obj.getElement().setAttribute(DISABLED, ""); } } }
gwt-material/src/main/java/gwt/material/design/client/base/mixin/EnabledMixin.java
package gwt.material.design.client.base.mixin; /* * #%L * GwtMaterial * %% * Copyright (C) 2015 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import gwt.material.design.client.base.MaterialWidget; import gwt.material.design.client.base.helper.StyleHelper; /** * @author Ben Dol * @author kevzlou7979 */ public class EnabledMixin<T extends Widget & HasEnabled> extends AbstractMixin<T> implements HasEnabled { private static final String DISABLED = "disabled"; private HandlerRegistration handler; public EnabledMixin(final T widget) { super(widget); } @Override public boolean isEnabled() { return !StyleHelper.containsStyle(uiObject.getStyleName(), "disabled"); } @Override public void setEnabled(boolean enabled) { if(!uiObject.isAttached() && handler == null) { handler = uiObject.addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if(event.isAttached()) { applyEnabled(enabled, uiObject); } else if(handler != null) { handler.removeHandler(); handler = null; } } }); } else { applyEnabled(enabled, uiObject); } } public void setEnabled(MaterialWidget widget, boolean enabled) { for(Widget child : widget.getChildren()) { if(child instanceof HasEnabled) { ((HasEnabled) child).setEnabled(enabled); setEnabled((MaterialWidget) child, enabled); } } } private void applyEnabled(boolean enabled, UIObject obj) { if(enabled) { obj.removeStyleName("disabled"); obj.getElement().removeAttribute(DISABLED); } else { obj.addStyleName("disabled"); obj.getElement().setAttribute(DISABLED, ""); } } }
Fixed enabled mixin.
gwt-material/src/main/java/gwt/material/design/client/base/mixin/EnabledMixin.java
Fixed enabled mixin.
<ide><path>wt-material/src/main/java/gwt/material/design/client/base/mixin/EnabledMixin.java <ide> import com.google.gwt.user.client.ui.Widget; <ide> import gwt.material.design.client.base.MaterialWidget; <ide> import gwt.material.design.client.base.helper.StyleHelper; <add>import gwt.material.design.client.base.mixin.AbstractMixin; <ide> <ide> /** <ide> * @author Ben Dol <ide> <ide> public void setEnabled(MaterialWidget widget, boolean enabled) { <ide> for(Widget child : widget.getChildren()) { <del> if(child instanceof HasEnabled) { <del> ((HasEnabled) child).setEnabled(enabled); <add> if(child instanceof MaterialWidget) { <add> ((MaterialWidget) child).setEnabled(enabled); <ide> setEnabled((MaterialWidget) child, enabled); <ide> } <ide> }
Java
apache-2.0
d44dc2c00b2474c82caacf21dabd94dba5d6f08b
0
san-tak/alien4cloud,alien4cloud/alien4cloud,alien4cloud/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud,san-tak/alien4cloud,san-tak/alien4cloud,alien4cloud/alien4cloud
package org.alien4cloud.server; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.inject.Inject; import org.alien4cloud.server.MaintenanceModeState.MaintenanceLog; import org.springframework.stereotype.Service; import com.google.common.collect.Lists; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.exception.AlreadyExistException; import alien4cloud.exception.NotFoundException; import alien4cloud.webconfiguration.MaintenanceFilter; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * Service that manage maintenance mode enablement. */ @Slf4j @Service public class MaintenanceModeService { @Resource(name = "alien-es-dao") private IGenericSearchDAO dao; @Inject private MaintenanceFilter maintenanceFilter; @Getter private MaintenanceModeState maintenanceModeState = null; @PostConstruct public void init() { // Load the maintenance mode state from elasticsearch if any maintenanceFilter.setMaintenanceModeService(this); maintenanceModeState = dao.findById(MaintenanceModeState.class, MaintenanceModeState.MMS_ID); if (maintenanceModeState != null) { log.info("Maintenance mode is enabled"); } } @PreDestroy public void destroy() { maintenanceFilter.setMaintenanceModeService(null); } public boolean isMaintenanceModeEnabled() { return maintenanceModeState != null; } /** * Enable the maintenance mode. * * @param user Name of the user that enabled the maintenance mode. */ public synchronized void enable(String user) { doEnable(user, true); } /** * Let an internal process enable the maintenance mode. * * @param process Name of the process that enabled the maintenance mode. */ public synchronized void internalEnable(String process) { doEnable(process, false); } private void doEnable(String ownerName, boolean isUser) { if (isMaintenanceModeEnabled()) { throw new AlreadyExistException("Maintenance mode is already enabled."); } log.info("Maintenance mode is enabled"); this.maintenanceModeState = new MaintenanceModeState(); this.maintenanceModeState.setUser(ownerName); this.maintenanceModeState.setUserTriggered(isUser); this.maintenanceModeState.setProgressPercent(1); this.maintenanceModeState.setLog(Lists.newArrayList(new MaintenanceLog(ownerName, "Maintenance operation started on alien4cloud."))); this.dao.save(maintenanceModeState); } /** * Update the current state of the maintenance mode. * * @param user Name of the user that performed the update. * @param message A message to update the maintenance. * @param progressPercentage The new percentage of the maintenance. */ public synchronized void update(String user, String message, Integer progressPercentage) { if (maintenanceModeState == null) { throw new NotFoundException("Maintenance mode is not enabled."); } if (!maintenanceModeState.isUserTriggered()) { throw new IllegalAccessError("Maintenance mode has not been enabled by a user, you are not allowed to update it."); } } /** * Let an internal process update the current state of the maintenance. * * @param process Name of the process. * @param message A message to update the maintenance. * @param progressPercentage The new percentage of the maintenance. */ public synchronized void internalUpdate(String process, String message, Integer progressPercentage) { if (maintenanceModeState == null) { throw new NotFoundException("Maintenance mode is not enabled."); } doUpdate(process, message, progressPercentage); } private void doUpdate(String user, String message, Integer progressPercentage) { if (message != null) { this.maintenanceModeState.getLog().add(new MaintenanceLog(user, message)); } if (progressPercentage != null) { this.maintenanceModeState.setProgressPercent(progressPercentage); } this.dao.save(maintenanceModeState); } /** * Disable a maintenance started by a user. */ public synchronized void disable() { if (maintenanceModeState == null) { throw new NotFoundException("Maintenance mode is not enabled."); } if (!maintenanceModeState.isUserTriggered()) { throw new IllegalAccessError("Maintenance mode has not been enabled by a user, you are not allowed to disable it."); } internalDisable(); } /** * Let internal process disable maintenance mode. */ public synchronized void internalDisable() { if (maintenanceModeState == null) { return; } this.dao.delete(MaintenanceModeState.class, maintenanceModeState.getId()); this.maintenanceModeState = null; log.info("Maintenance mode is disabled"); } }
alien4cloud-rest-api/src/main/java/org/alien4cloud/server/MaintenanceModeService.java
package org.alien4cloud.server; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.inject.Inject; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.alien4cloud.server.MaintenanceModeState.MaintenanceLog; import org.springframework.stereotype.Service; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.exception.AlreadyExistException; import alien4cloud.exception.NotFoundException; import alien4cloud.webconfiguration.MaintenanceFilter; import lombok.Getter; /** * Service that manage maintenance mode enablement. */ @Slf4j @Service public class MaintenanceModeService { @Resource(name = "alien-es-dao") private IGenericSearchDAO dao; @Inject private MaintenanceFilter maintenanceFilter; @Getter private MaintenanceModeState maintenanceModeState = null; @PostConstruct public void init() { // Load the maintenance mode state from elasticsearch if any maintenanceFilter.setMaintenanceModeService(this); maintenanceModeState = dao.findById(MaintenanceModeState.class, MaintenanceModeState.MMS_ID); if (maintenanceModeState != null) { log.info("Maintenance mode is enabled"); } } @PreDestroy public void destroy() { maintenanceFilter.setMaintenanceModeService(null); } public boolean isMaintenanceModeEnabled() { return maintenanceModeState != null; } /** * Enable the maintenance mode. * * @param user Name of the user that enabled the maintenance mode. */ public synchronized void enable(String user) { if (isMaintenanceModeEnabled()) { throw new AlreadyExistException("Maintenance mode is already enabled."); } log.info("Maintenance mode is enabled"); this.maintenanceModeState = new MaintenanceModeState(); this.maintenanceModeState.setUser(user); this.maintenanceModeState.setUserTriggered(true); this.maintenanceModeState.setProgressPercent(1); this.maintenanceModeState.setLog(Lists.newArrayList(new MaintenanceLog(user, "Maintenance operation started on alien4cloud."))); this.dao.save(maintenanceModeState); } /** * Update the current state of the maintenance mode. * * @param user Name of the user that performed the update. * @param message A message to update the maintenance. * @param progressPercentage The new percentage of the maintenance. */ public synchronized void update(String user, String message, Integer progressPercentage) { if (maintenanceModeState == null) { throw new NotFoundException("Maintenance mode is not enabled."); } this.maintenanceModeState.getLog().add(new MaintenanceLog(user, message)); if (progressPercentage != null) { this.maintenanceModeState.setProgressPercent(progressPercentage); } this.dao.save(maintenanceModeState); } /** * Disable maintenance mode. */ public synchronized void disable() { if (maintenanceModeState == null) { throw new NotFoundException("Maintenance mode is not enabled."); } this.dao.delete(MaintenanceModeState.class, maintenanceModeState.getId()); this.maintenanceModeState = null; log.info("Maintenance mode is disabled"); } }
Add operations for internal maintenance management (process managed maintenance). Prevent user from updating/disabling process managed maintenance.
alien4cloud-rest-api/src/main/java/org/alien4cloud/server/MaintenanceModeService.java
Add operations for internal maintenance management (process managed maintenance). Prevent user from updating/disabling process managed maintenance.
<ide><path>lien4cloud-rest-api/src/main/java/org/alien4cloud/server/MaintenanceModeService.java <ide> import javax.annotation.Resource; <ide> import javax.inject.Inject; <ide> <del>import com.google.common.collect.Lists; <del>import lombok.extern.slf4j.Slf4j; <ide> import org.alien4cloud.server.MaintenanceModeState.MaintenanceLog; <ide> import org.springframework.stereotype.Service; <add> <add>import com.google.common.collect.Lists; <ide> <ide> import alien4cloud.dao.IGenericSearchDAO; <ide> import alien4cloud.exception.AlreadyExistException; <ide> import alien4cloud.exception.NotFoundException; <ide> import alien4cloud.webconfiguration.MaintenanceFilter; <ide> import lombok.Getter; <add>import lombok.extern.slf4j.Slf4j; <ide> <ide> /** <ide> * Service that manage maintenance mode enablement. <ide> * @param user Name of the user that enabled the maintenance mode. <ide> */ <ide> public synchronized void enable(String user) { <add> doEnable(user, true); <add> } <add> <add> /** <add> * Let an internal process enable the maintenance mode. <add> * <add> * @param process Name of the process that enabled the maintenance mode. <add> */ <add> public synchronized void internalEnable(String process) { <add> doEnable(process, false); <add> } <add> <add> private void doEnable(String ownerName, boolean isUser) { <ide> if (isMaintenanceModeEnabled()) { <ide> throw new AlreadyExistException("Maintenance mode is already enabled."); <ide> } <ide> log.info("Maintenance mode is enabled"); <ide> <ide> this.maintenanceModeState = new MaintenanceModeState(); <del> this.maintenanceModeState.setUser(user); <del> this.maintenanceModeState.setUserTriggered(true); <add> this.maintenanceModeState.setUser(ownerName); <add> this.maintenanceModeState.setUserTriggered(isUser); <ide> this.maintenanceModeState.setProgressPercent(1); <del> this.maintenanceModeState.setLog(Lists.newArrayList(new MaintenanceLog(user, "Maintenance operation started on alien4cloud."))); <add> this.maintenanceModeState.setLog(Lists.newArrayList(new MaintenanceLog(ownerName, "Maintenance operation started on alien4cloud."))); <ide> <ide> this.dao.save(maintenanceModeState); <ide> } <ide> if (maintenanceModeState == null) { <ide> throw new NotFoundException("Maintenance mode is not enabled."); <ide> } <add> if (!maintenanceModeState.isUserTriggered()) { <add> throw new IllegalAccessError("Maintenance mode has not been enabled by a user, you are not allowed to update it."); <add> } <ide> <del> this.maintenanceModeState.getLog().add(new MaintenanceLog(user, message)); <add> } <add> <add> /** <add> * Let an internal process update the current state of the maintenance. <add> * <add> * @param process Name of the process. <add> * @param message A message to update the maintenance. <add> * @param progressPercentage The new percentage of the maintenance. <add> */ <add> public synchronized void internalUpdate(String process, String message, Integer progressPercentage) { <add> if (maintenanceModeState == null) { <add> throw new NotFoundException("Maintenance mode is not enabled."); <add> } <add> <add> doUpdate(process, message, progressPercentage); <add> } <add> <add> private void doUpdate(String user, String message, Integer progressPercentage) { <add> if (message != null) { <add> this.maintenanceModeState.getLog().add(new MaintenanceLog(user, message)); <add> } <ide> if (progressPercentage != null) { <ide> this.maintenanceModeState.setProgressPercent(progressPercentage); <ide> } <ide> } <ide> <ide> /** <del> * Disable maintenance mode. <add> * Disable a maintenance started by a user. <ide> */ <ide> public synchronized void disable() { <ide> if (maintenanceModeState == null) { <ide> throw new NotFoundException("Maintenance mode is not enabled."); <add> } <add> if (!maintenanceModeState.isUserTriggered()) { <add> throw new IllegalAccessError("Maintenance mode has not been enabled by a user, you are not allowed to disable it."); <add> } <add> <add> internalDisable(); <add> } <add> <add> /** <add> * Let internal process disable maintenance mode. <add> */ <add> public synchronized void internalDisable() { <add> if (maintenanceModeState == null) { <add> return; <ide> } <ide> <ide> this.dao.delete(MaintenanceModeState.class, maintenanceModeState.getId());
Java
mit
54cfdb9424fa0097dd642b3a0d4166fe6bb3c624
0
KJ4IPS/KaBan
package guru.haun.kaban.persistance; import java.util.Date; import java.util.UUID; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.avaje.ebean.validation.Length; import com.avaje.ebean.validation.NotEmpty; import com.avaje.ebean.validation.NotNull; @Entity() @Table(name = "ActiveBans") public class ActiveBansDBO { public ActiveBansDBO(long id, UUID banned, String bannedName, Date bannedTime, Date expireTime, UUID banner, String bannerName, String reason){ this.id = id; this.setBanned(banned); this.setBannedName(bannedName); this.setBannedTime(bannedTime); this.setExpireTime(expireTime); this.setBanner(banner); this.setBannerName(bannerName); this.setReason(reason); } public UUID getBanned() { return banned; } public void setBanned(UUID banned) { this.banned = banned; } public String getBannedName() { return bannedName; } public void setBannedName(String bannedName) { this.bannedName = bannedName; } public Date getBannedTime() { return bannedTime; } public void setBannedTime(Date bannedTime) { this.bannedTime = bannedTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } public UUID getBanner() { return banner; } public void setBanner(UUID banner) { this.banner = banner; } public String getBannerName() { return bannerName; } public void setBannerName(String bannerName) { this.bannerName = bannerName; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } @Id private long id; @NotNull private UUID banned; @Length(max=17) @NotEmpty private String bannedName; @NotNull private Date bannedTime; @NotNull private Date expireTime; @Basic private String reason; @Basic private UUID banner; @Length(max=17) private String bannerName; }
src/main/java/guru/haun/kaban/persistance/ActiveBansDBO.java
package guru.haun.kaban.persistance; import java.util.Date; import java.util.UUID; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.avaje.ebean.validation.Length; import com.avaje.ebean.validation.NotEmpty; import com.avaje.ebean.validation.NotNull; @Entity() @Table(name = "ActiveBans") public class ActiveBansDBO { public ActiveBansDBO(long id, UUID banned, String bannedName, Date bannedTime, Date expireTime, UUID banner, String bannerName, String reason){ this.id = id; this.setBanned(banned); this.setBannedName(bannedName); this.setBannedTime(bannedTime); this.setExpireTime(expireTime); this.setBanner(banner); this.setBannerName(bannerName); this.setReason(reason); } public UUID getBanned() { return banned; } public void setBanned(UUID banned) { this.banned = banned; } public String getBannedName() { return bannedName; } public void setBannedName(String bannedName) { this.bannedName = bannedName; } public Date getBannedTime() { return bannedTime; } public void setBannedTime(Date bannedTime) { this.bannedTime = bannedTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } public UUID getBanner() { return banner; } public void setBanner(UUID banner) { this.banner = banner; } public String getBannerName() { return bannerName; } public void setBannerName(String bannerName) { this.bannerName = bannerName; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } @Id private long id; @NotNull private UUID banned; @Length(max=17) @NotEmpty private String bannedName; @NotEmpty private Date bannedTime; @NotEmpty private Date expireTime; @Basic private String reason; @Basic private UUID banner; @Length(max=17) private String bannerName; }
Changed DATE's to NotNull
src/main/java/guru/haun/kaban/persistance/ActiveBansDBO.java
Changed DATE's to NotNull
<ide><path>rc/main/java/guru/haun/kaban/persistance/ActiveBansDBO.java <ide> @NotEmpty <ide> private String bannedName; <ide> <del> @NotEmpty <add> @NotNull <ide> private Date bannedTime; <ide> <del> @NotEmpty <add> @NotNull <ide> private Date expireTime; <ide> <ide> @Basic
Java
apache-2.0
error: pathspec 'src/test/java/io/engagingspaces/vertx/dataloader/DataLoaderTest.java' did not match any file(s) known to git
58eab9e2a5ca01b64e7c353f3d6b6a8b6635c919
1
engagingspaces/vertx-dataloader,graphql-java/java-dataloader
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.engagingspaces.vertx.dataloader; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; /** * Tests for {@link DataLoader}. * <p> * The tests are a port of the existing tests in * the <a href="https://github.com/facebook/dataloader">facebook/dataloader</a> project. * <p> * Acknowledgments go to <a href="https://github.com/leebyron">Lee Byron</a> for providing excellent coverage. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @RunWith(VertxUnitRunner.class) public class DataLoaderTest { @Rule public RunTestOnContext rule = new RunTestOnContext(); DataLoader<Integer, Integer> identityLoader; @Before public void setUp() { identityLoader = idLoader(new DataLoaderOptions(), new ArrayList<>()); } @Test public void should_Build_a_really_really_simple_data_loader() { AtomicBoolean success = new AtomicBoolean(); DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keys -> CompositeFuture.all(keys.stream() .map(Future::succeededFuture) .collect(Collectors.toCollection(ArrayList::new)))); Future<Integer> future1 = identityLoader.load(1); future1.setHandler(rh -> { assertThat(rh.result(), equalTo(1)); success.set(rh.succeeded()); }); identityLoader.dispatch(); await().untilAtomic(success, is(true)); } @Test public void should_Support_loading_multiple_keys_in_one_call() { AtomicBoolean success = new AtomicBoolean(); DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keys -> CompositeFuture.all(keys.stream() .map(Future::succeededFuture) .collect(Collectors.toCollection(ArrayList::new)))); CompositeFuture futureAll = identityLoader.loadMany(Arrays.asList(1, 2)); futureAll.setHandler(rh -> { assertThat(rh.result().size(), is(2)); success.set(rh.succeeded()); }); identityLoader.dispatch(); await().untilAtomic(success, is(true)); assertThat(futureAll.list(), equalTo(Arrays.asList(1, 2))); } @Test public void should_Resolve_to_empty_list_when_no_keys_supplied() { AtomicBoolean success = new AtomicBoolean(); CompositeFuture futureEmpty = identityLoader.loadMany(Collections.emptyList()); futureEmpty.setHandler(rh -> { assertThat(rh.result().size(), is(0)); success.set(rh.succeeded()); }); identityLoader.dispatch(); await().untilAtomic(success, is(true)); assertThat(futureEmpty.list(), empty()); } @Test public void should_Batch_multiple_requests() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); Future<Integer> future1 = identityLoader.load(1); Future<Integer> future2 = identityLoader.load(2); identityLoader.dispatch(); await().until(() -> future1.isComplete() && future2.isComplete()); assertThat(future1.result(), equalTo(1)); assertThat(future2.result(), equalTo(2)); assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList(1, 2)))); } @Test public void should_Coalesce_identical_requests() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); Future<Integer> future1a = identityLoader.load(1); Future<Integer> future1b = identityLoader.load(1); assertThat(future1a, equalTo(future1b)); identityLoader.dispatch(); await().until(future1a::isComplete); assertThat(future1a.result(), equalTo(1)); assertThat(future1b.result(), equalTo(1)); assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList(1)))); } @Test public void should_Cache_repeated_requests() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); Future<String> future1 = identityLoader.load("A"); Future<String> future2 = identityLoader.load("B"); identityLoader.dispatch(); await().until(() -> future1.isComplete() && future2.isComplete()); assertThat(future1.result(), equalTo("A")); assertThat(future2.result(), equalTo("B")); assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList("A", "B")))); Future<String> future1a = identityLoader.load("A"); Future<String> future3 = identityLoader.load("C"); identityLoader.dispatch(); await().until(() -> future1a.isComplete() && future3.isComplete()); assertThat(future1a.result(), equalTo("A")); assertThat(future3.result(), equalTo("C")); assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Collections.singletonList("C")))); Future<String> future1b = identityLoader.load("A"); Future<String> future2a = identityLoader.load("B"); Future<String> future3a = identityLoader.load("C"); identityLoader.dispatch(); await().until(() -> future1b.isComplete() && future2a.isComplete() && future3a.isComplete()); assertThat(future1b.result(), equalTo("A")); assertThat(future2a.result(), equalTo("B")); assertThat(future3a.result(), equalTo("C")); assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Collections.singletonList("C")))); } @Test public void should_Clear_single_value_in_loader() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); Future<String> future1 = identityLoader.load("A"); Future<String> future2 = identityLoader.load("B"); identityLoader.dispatch(); await().until(() -> future1.isComplete() && future2.isComplete()); assertThat(future1.result(), equalTo("A")); assertThat(future2.result(), equalTo("B")); assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList("A", "B")))); identityLoader.clear("A"); Future<String> future1a = identityLoader.load("A"); Future<String> future2a = identityLoader.load("B"); identityLoader.dispatch(); await().until(() -> future1a.isComplete() && future2a.isComplete()); assertThat(future1a.result(), equalTo("A")); assertThat(future2a.result(), equalTo("B")); assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Collections.singletonList("A")))); } @Test public void should_Clear_all_values_in_loader() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); Future<String> future1 = identityLoader.load("A"); Future<String> future2 = identityLoader.load("B"); identityLoader.dispatch(); await().until(() -> future1.isComplete() && future2.isComplete()); assertThat(future1.result(), equalTo("A")); assertThat(future2.result(), equalTo("B")); assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList("A", "B")))); identityLoader.clearAll(); Future<String> future1a = identityLoader.load("A"); Future<String> future2a = identityLoader.load("B"); identityLoader.dispatch(); await().until(() -> future1a.isComplete() && future2a.isComplete()); assertThat(future1a.result(), equalTo("A")); assertThat(future2a.result(), equalTo("B")); assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Arrays.asList("A", "B")))); } @Test public void should_Allow_priming_the_cache() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); identityLoader.prime("A", "A"); Future<String> future1 = identityLoader.load("A"); Future<String> future2 = identityLoader.load("B"); identityLoader.dispatch(); await().until(() -> future1.isComplete() && future2.isComplete()); assertThat(future1.result(), equalTo("A")); assertThat(future2.result(), equalTo("B")); assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList("B")))); } @Test public void should_Not_prime_keys_that_already_exist() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); identityLoader.prime("A", "X"); Future<String> future1 = identityLoader.load("A"); Future<String> future2 = identityLoader.load("B"); CompositeFuture composite = identityLoader.dispatch(); await().until((Callable<Boolean>) composite::succeeded); assertThat(future1.result(), equalTo("X")); assertThat(future2.result(), equalTo("B")); identityLoader.prime("A", "Y"); identityLoader.prime("B", "Y"); Future<String> future1a = identityLoader.load("A"); Future<String> future2a = identityLoader.load("B"); CompositeFuture composite2 = identityLoader.dispatch(); await().until((Callable<Boolean>) composite2::succeeded); assertThat(future1a.result(), equalTo("X")); assertThat(future2a.result(), equalTo("B")); assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList("B")))); } @Test public void should_Allow_to_forcefully_prime_the_cache() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); identityLoader.prime("A", "X"); Future<String> future1 = identityLoader.load("A"); Future<String> future2 = identityLoader.load("B"); CompositeFuture composite = identityLoader.dispatch(); await().until((Callable<Boolean>) composite::succeeded); assertThat(future1.result(), equalTo("X")); assertThat(future2.result(), equalTo("B")); identityLoader.clear("A").prime("A", "Y"); identityLoader.clear("B").prime("B", "Y"); Future<String> future1a = identityLoader.load("A"); Future<String> future2a = identityLoader.load("B"); CompositeFuture composite2 = identityLoader.dispatch(); await().until((Callable<Boolean>) composite2::succeeded); assertThat(future1a.result(), equalTo("Y")); assertThat(future2a.result(), equalTo("Y")); assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList("B")))); } @Test public void should_Resolve_to_error_to_indicate_failure() { ArrayList<Collection> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> evenLoader = idLoaderWithErrors(new DataLoaderOptions(), loadCalls); Future<Integer> future1 = evenLoader.load(1); evenLoader.dispatch(); await().until(future1::isComplete); assertThat(future1.failed(), is(true)); assertThat(future1.cause(), instanceOf(IllegalStateException.class)); Future<Integer> future2 = evenLoader.load(2); evenLoader.dispatch(); await().until(future2::isComplete); assertThat(future2.result(), equalTo(2)); assertThat(loadCalls, equalTo(Arrays.asList(Collections.singletonList(1), Collections.singletonList(2)))); } @SuppressWarnings("unchecked") private static <K, V> DataLoader<K, V> idLoader(DataLoaderOptions options, List<Collection> loadCalls) { return new DataLoader<>(keys -> { loadCalls.add(new ArrayList(keys)); List<Future> futures = keys.stream().map(Future::succeededFuture).collect(Collectors.toList()); return CompositeFuture.all(futures); }, options); } @SuppressWarnings("unchecked") private static DataLoader<Integer, Integer> idLoaderWithErrors( DataLoaderOptions options, List<Collection> loadCalls) { return new DataLoader<>(keys -> { loadCalls.add(new ArrayList(keys)); List<Future> futures = keys.stream() .map(key -> key % 2 == 0 ? Future.succeededFuture(key) : Future.failedFuture(new IllegalStateException("Error"))) .collect(Collectors.toList()); return CompositeFuture.all(futures); }, options); } }
src/test/java/io/engagingspaces/vertx/dataloader/DataLoaderTest.java
Unit tests for DataLoader (partially complete)
src/test/java/io/engagingspaces/vertx/dataloader/DataLoaderTest.java
Unit tests for DataLoader (partially complete)
<ide><path>rc/test/java/io/engagingspaces/vertx/dataloader/DataLoaderTest.java <add>/* <add> * Copyright (c) 2016 The original author or authors <add> * <add> * All rights reserved. This program and the accompanying materials <add> * are made available under the terms of the Eclipse Public License v1.0 <add> * and Apache License v2.0 which accompanies this distribution. <add> * <add> * The Eclipse Public License is available at <add> * http://www.eclipse.org/legal/epl-v10.html <add> * <add> * The Apache License v2.0 is available at <add> * http://www.opensource.org/licenses/apache2.0.php <add> * <add> * You may elect to redistribute this code under either of these licenses. <add> */ <add> <add>package io.engagingspaces.vertx.dataloader; <add> <add>import io.vertx.core.CompositeFuture; <add>import io.vertx.core.Future; <add>import io.vertx.ext.unit.junit.RunTestOnContext; <add>import io.vertx.ext.unit.junit.VertxUnitRunner; <add>import org.junit.Before; <add>import org.junit.Rule; <add>import org.junit.Test; <add>import org.junit.runner.RunWith; <add> <add>import java.util.*; <add>import java.util.concurrent.Callable; <add>import java.util.concurrent.atomic.AtomicBoolean; <add>import java.util.stream.Collectors; <add> <add>import static org.awaitility.Awaitility.await; <add>import static org.hamcrest.Matchers.*; <add>import static org.junit.Assert.assertThat; <add> <add>/** <add> * Tests for {@link DataLoader}. <add> * <p> <add> * The tests are a port of the existing tests in <add> * the <a href="https://github.com/facebook/dataloader">facebook/dataloader</a> project. <add> * <p> <add> * Acknowledgments go to <a href="https://github.com/leebyron">Lee Byron</a> for providing excellent coverage. <add> * <add> * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> <add> */ <add>@RunWith(VertxUnitRunner.class) <add>public class DataLoaderTest { <add> <add> @Rule <add> public RunTestOnContext rule = new RunTestOnContext(); <add> <add> DataLoader<Integer, Integer> identityLoader; <add> <add> @Before <add> public void setUp() { <add> identityLoader = idLoader(new DataLoaderOptions(), new ArrayList<>()); <add> } <add> <add> @Test <add> public void should_Build_a_really_really_simple_data_loader() { <add> AtomicBoolean success = new AtomicBoolean(); <add> DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keys -> <add> CompositeFuture.all(keys.stream() <add> .map(Future::succeededFuture) <add> .collect(Collectors.toCollection(ArrayList::new)))); <add> <add> Future<Integer> future1 = identityLoader.load(1); <add> future1.setHandler(rh -> { <add> assertThat(rh.result(), equalTo(1)); <add> success.set(rh.succeeded()); <add> }); <add> identityLoader.dispatch(); <add> await().untilAtomic(success, is(true)); <add> } <add> <add> @Test <add> public void should_Support_loading_multiple_keys_in_one_call() { <add> AtomicBoolean success = new AtomicBoolean(); <add> DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keys -> <add> CompositeFuture.all(keys.stream() <add> .map(Future::succeededFuture) <add> .collect(Collectors.toCollection(ArrayList::new)))); <add> <add> CompositeFuture futureAll = identityLoader.loadMany(Arrays.asList(1, 2)); <add> futureAll.setHandler(rh -> { <add> assertThat(rh.result().size(), is(2)); <add> success.set(rh.succeeded()); <add> }); <add> identityLoader.dispatch(); <add> await().untilAtomic(success, is(true)); <add> assertThat(futureAll.list(), equalTo(Arrays.asList(1, 2))); <add> } <add> <add> @Test <add> public void should_Resolve_to_empty_list_when_no_keys_supplied() { <add> AtomicBoolean success = new AtomicBoolean(); <add> CompositeFuture futureEmpty = identityLoader.loadMany(Collections.emptyList()); <add> futureEmpty.setHandler(rh -> { <add> assertThat(rh.result().size(), is(0)); <add> success.set(rh.succeeded()); <add> }); <add> identityLoader.dispatch(); <add> await().untilAtomic(success, is(true)); <add> assertThat(futureEmpty.list(), empty()); <add> } <add> <add> @Test <add> public void should_Batch_multiple_requests() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<Integer, Integer> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> Future<Integer> future1 = identityLoader.load(1); <add> Future<Integer> future2 = identityLoader.load(2); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1.isComplete() && future2.isComplete()); <add> assertThat(future1.result(), equalTo(1)); <add> assertThat(future2.result(), equalTo(2)); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList(1, 2)))); <add> } <add> <add> @Test <add> public void should_Coalesce_identical_requests() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<Integer, Integer> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> Future<Integer> future1a = identityLoader.load(1); <add> Future<Integer> future1b = identityLoader.load(1); <add> assertThat(future1a, equalTo(future1b)); <add> identityLoader.dispatch(); <add> <add> await().until(future1a::isComplete); <add> assertThat(future1a.result(), equalTo(1)); <add> assertThat(future1b.result(), equalTo(1)); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList(1)))); <add> } <add> <add> @Test <add> public void should_Cache_repeated_requests() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> Future<String> future1 = identityLoader.load("A"); <add> Future<String> future2 = identityLoader.load("B"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1.isComplete() && future2.isComplete()); <add> assertThat(future1.result(), equalTo("A")); <add> assertThat(future2.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList("A", "B")))); <add> <add> Future<String> future1a = identityLoader.load("A"); <add> Future<String> future3 = identityLoader.load("C"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1a.isComplete() && future3.isComplete()); <add> assertThat(future1a.result(), equalTo("A")); <add> assertThat(future3.result(), equalTo("C")); <add> assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Collections.singletonList("C")))); <add> <add> Future<String> future1b = identityLoader.load("A"); <add> Future<String> future2a = identityLoader.load("B"); <add> Future<String> future3a = identityLoader.load("C"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1b.isComplete() && future2a.isComplete() && future3a.isComplete()); <add> assertThat(future1b.result(), equalTo("A")); <add> assertThat(future2a.result(), equalTo("B")); <add> assertThat(future3a.result(), equalTo("C")); <add> assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Collections.singletonList("C")))); <add> } <add> <add> @Test <add> public void should_Clear_single_value_in_loader() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> Future<String> future1 = identityLoader.load("A"); <add> Future<String> future2 = identityLoader.load("B"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1.isComplete() && future2.isComplete()); <add> assertThat(future1.result(), equalTo("A")); <add> assertThat(future2.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList("A", "B")))); <add> <add> identityLoader.clear("A"); <add> <add> Future<String> future1a = identityLoader.load("A"); <add> Future<String> future2a = identityLoader.load("B"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1a.isComplete() && future2a.isComplete()); <add> assertThat(future1a.result(), equalTo("A")); <add> assertThat(future2a.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Collections.singletonList("A")))); <add> } <add> <add> @Test <add> public void should_Clear_all_values_in_loader() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> Future<String> future1 = identityLoader.load("A"); <add> Future<String> future2 = identityLoader.load("B"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1.isComplete() && future2.isComplete()); <add> assertThat(future1.result(), equalTo("A")); <add> assertThat(future2.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Arrays.asList("A", "B")))); <add> <add> identityLoader.clearAll(); <add> <add> Future<String> future1a = identityLoader.load("A"); <add> Future<String> future2a = identityLoader.load("B"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1a.isComplete() && future2a.isComplete()); <add> assertThat(future1a.result(), equalTo("A")); <add> assertThat(future2a.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Arrays.asList(Arrays.asList("A", "B"), Arrays.asList("A", "B")))); <add> } <add> <add> @Test <add> public void should_Allow_priming_the_cache() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> identityLoader.prime("A", "A"); <add> <add> Future<String> future1 = identityLoader.load("A"); <add> Future<String> future2 = identityLoader.load("B"); <add> identityLoader.dispatch(); <add> <add> await().until(() -> future1.isComplete() && future2.isComplete()); <add> assertThat(future1.result(), equalTo("A")); <add> assertThat(future2.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList("B")))); <add> } <add> <add> @Test <add> public void should_Not_prime_keys_that_already_exist() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> identityLoader.prime("A", "X"); <add> <add> Future<String> future1 = identityLoader.load("A"); <add> Future<String> future2 = identityLoader.load("B"); <add> CompositeFuture composite = identityLoader.dispatch(); <add> <add> await().until((Callable<Boolean>) composite::succeeded); <add> assertThat(future1.result(), equalTo("X")); <add> assertThat(future2.result(), equalTo("B")); <add> <add> identityLoader.prime("A", "Y"); <add> identityLoader.prime("B", "Y"); <add> <add> Future<String> future1a = identityLoader.load("A"); <add> Future<String> future2a = identityLoader.load("B"); <add> CompositeFuture composite2 = identityLoader.dispatch(); <add> <add> await().until((Callable<Boolean>) composite2::succeeded); <add> assertThat(future1a.result(), equalTo("X")); <add> assertThat(future2a.result(), equalTo("B")); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList("B")))); <add> } <add> <add> @Test <add> public void should_Allow_to_forcefully_prime_the_cache() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<String, String> identityLoader = idLoader(new DataLoaderOptions(), loadCalls); <add> <add> identityLoader.prime("A", "X"); <add> <add> Future<String> future1 = identityLoader.load("A"); <add> Future<String> future2 = identityLoader.load("B"); <add> CompositeFuture composite = identityLoader.dispatch(); <add> <add> await().until((Callable<Boolean>) composite::succeeded); <add> assertThat(future1.result(), equalTo("X")); <add> assertThat(future2.result(), equalTo("B")); <add> <add> identityLoader.clear("A").prime("A", "Y"); <add> identityLoader.clear("B").prime("B", "Y"); <add> <add> Future<String> future1a = identityLoader.load("A"); <add> Future<String> future2a = identityLoader.load("B"); <add> CompositeFuture composite2 = identityLoader.dispatch(); <add> <add> await().until((Callable<Boolean>) composite2::succeeded); <add> assertThat(future1a.result(), equalTo("Y")); <add> assertThat(future2a.result(), equalTo("Y")); <add> assertThat(loadCalls, equalTo(Collections.singletonList(Collections.singletonList("B")))); <add> } <add> <add> @Test <add> public void should_Resolve_to_error_to_indicate_failure() { <add> ArrayList<Collection> loadCalls = new ArrayList<>(); <add> DataLoader<Integer, Integer> evenLoader = idLoaderWithErrors(new DataLoaderOptions(), loadCalls); <add> <add> Future<Integer> future1 = evenLoader.load(1); <add> evenLoader.dispatch(); <add> <add> await().until(future1::isComplete); <add> assertThat(future1.failed(), is(true)); <add> assertThat(future1.cause(), instanceOf(IllegalStateException.class)); <add> <add> Future<Integer> future2 = evenLoader.load(2); <add> evenLoader.dispatch(); <add> <add> await().until(future2::isComplete); <add> assertThat(future2.result(), equalTo(2)); <add> assertThat(loadCalls, equalTo(Arrays.asList(Collections.singletonList(1), Collections.singletonList(2)))); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private static <K, V> DataLoader<K, V> idLoader(DataLoaderOptions options, List<Collection> loadCalls) { <add> return new DataLoader<>(keys -> { <add> loadCalls.add(new ArrayList(keys)); <add> List<Future> futures = keys.stream().map(Future::succeededFuture).collect(Collectors.toList()); <add> return CompositeFuture.all(futures); <add> }, options); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private static DataLoader<Integer, Integer> idLoaderWithErrors( <add> DataLoaderOptions options, List<Collection> loadCalls) { <add> return new DataLoader<>(keys -> { <add> loadCalls.add(new ArrayList(keys)); <add> List<Future> futures = keys.stream() <add> .map(key -> key % 2 == 0 ? Future.succeededFuture(key) : <add> Future.failedFuture(new IllegalStateException("Error"))) <add> .collect(Collectors.toList()); <add> return CompositeFuture.all(futures); <add> }, options); <add> } <add>}
Java
mit
f8d1c1d284be6b559e7195f38d8289048abda3f4
0
tkob/yokohamaunit,tkob/yokohamaunit
package yokohama.unit.translator; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.tree.TerminalNode; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import yokohama.unit.ast.Assertion; import yokohama.unit.ast.Binding; import yokohama.unit.ast.Bindings; import yokohama.unit.ast.Copula; import yokohama.unit.ast.Definition; import yokohama.unit.ast.Execution; import yokohama.unit.ast.Expr; import yokohama.unit.ast.Fixture; import yokohama.unit.ast.FourPhaseTest; import yokohama.unit.ast.Group; import yokohama.unit.ast.LetBinding; import yokohama.unit.ast.LetBindings; import yokohama.unit.ast.Phase; import yokohama.unit.ast.Proposition; import yokohama.unit.ast.Row; import yokohama.unit.ast.Table; import yokohama.unit.ast.TableRef; import yokohama.unit.ast.TableType; import yokohama.unit.ast.VerifyPhase; import yokohama.unit.grammar.YokohamaUnitLexer; import yokohama.unit.grammar.YokohamaUnitParser; public class ParseTreeToAstVisitorTest { public static YokohamaUnitParser parser(String input) throws IOException { return parser(input, YokohamaUnitLexer.DEFAULT_MODE); } public static YokohamaUnitParser parser(String input, int mode) throws IOException { InputStream bais = new ByteArrayInputStream(input.getBytes()); CharStream stream = new ANTLRInputStream(bais); Lexer lex = new YokohamaUnitLexer(stream); lex.mode(mode); CommonTokenStream tokens = new CommonTokenStream(lex); YokohamaUnitParser parser = new YokohamaUnitParser(tokens); return parser; } @Test public void testVisitGroup() throws IOException { YokohamaUnitParser.GroupContext ctx = parser("Test: test name\nAssert `a` is `b`.").group(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Group result = instance.visitGroup(ctx); assertThat(result.getDefinitions().size(), is(1)); } @Test public void testVisitDefinition() throws IOException { YokohamaUnitParser.DefinitionContext ctx = parser("Test: test name\n Assert `a` is `b`.").definition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Definition result = instance.visitDefinition(ctx); assertThat(result, is(instanceOf(yokohama.unit.ast.Test.class))); } @Test public void testVisitDefinition2() throws IOException { YokohamaUnitParser.DefinitionContext ctx = parser("Table: table name\n|a|b\n----\n|1|2\n\n").definition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Definition result = instance.visitDefinition(ctx); assertThat(result, is(instanceOf(Table.class))); } @Test public void testVisitTest() { TerminalNode nameTerminalNode = mock(TerminalNode.class); YokohamaUnitParser.TestContext ctx = mock(YokohamaUnitParser.TestContext.class); when(nameTerminalNode.getText()).thenReturn("test name"); when(ctx.TestName()).thenReturn(nameTerminalNode); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); yokohama.unit.ast.Test result = instance.visitTest(ctx); assertEquals("test name", result.getName()); } @Test public void testVisitHash() throws IOException { YokohamaUnitParser.HashContext ctx = parser("#").hash(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Integer actual = instance.visitHash(ctx); Integer expected = 1; assertThat(actual, is(expected)); } @Test public void testVisitHash2() throws IOException { YokohamaUnitParser.HashContext ctx = parser("######").hash(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Integer actual = instance.visitHash(ctx); Integer expected = 6; assertThat(actual, is(expected)); } @Test public void testVisitAssertion() throws IOException { YokohamaUnitParser.AssertionContext ctx = parser("Assert `a` is `b`.").assertion(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Assertion actual = instance.visitAssertion(ctx); Assertion expected = new Assertion( Arrays.asList(new Proposition(new Expr("a"), Copula.IS, new Expr("b"))), Fixture.none()); assertThat(actual, is(expected)); } @Test public void testVisitAssertion2() throws IOException { YokohamaUnitParser.AssertionContext ctx = parser("Assert `a` is `b` where a = `1`.").assertion(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Assertion actual = instance.visitAssertion(ctx); Assertion expected = new Assertion( Arrays.asList(new Proposition(new Expr("a"), Copula.IS, new Expr("b"))), new Bindings(Arrays.asList(new Binding("a", new Expr("1"))))); assertThat(actual, is(expected)); } @Test public void testVisitCopula() { YokohamaUnitParser.CopulaContext ctx = mock(YokohamaUnitParser.CopulaContext.class); when(ctx.getText()).thenReturn("is"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Copula expResult = Copula.IS; Copula result = instance.visitCopula(ctx); assertEquals(expResult, result); } @Test public void testVisitCopula2() { YokohamaUnitParser.CopulaContext ctx = mock(YokohamaUnitParser.CopulaContext.class); when(ctx.getText()).thenReturn("throws"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Copula expResult = Copula.THROWS; Copula result = instance.visitCopula(ctx); assertEquals(expResult, result); } @Test public void testVisitCopula3() { YokohamaUnitParser.CopulaContext ctx = mock(YokohamaUnitParser.CopulaContext.class); when(ctx.getText()).thenReturn("isnot"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Copula expResult = Copula.IS_NOT; Copula result = instance.visitCopula(ctx); assertEquals(expResult, result); } @Test public void testVisitBindings() throws IOException { YokohamaUnitParser.BindingsContext ctx = parser("where a = `1`").bindings(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Bindings result = instance.visitBindings(ctx); assertThat(result.getBindings().size(), is(1)); } @Test public void testVisitBindings2() throws IOException { YokohamaUnitParser.BindingsContext ctx = parser("where a = `1` and b = `2`").bindings(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Bindings result = instance.visitBindings(ctx); assertThat(result.getBindings().size(), is(2)); } @Test public void testVisitBinding() throws IOException { YokohamaUnitParser.BindingContext ctx = parser("a = `1`").binding(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Binding result = instance.visitBinding(ctx); assertThat(result, is(new Binding("a", new Expr("1")))); } @Test public void testVisitCondition() throws IOException { YokohamaUnitParser.ConditionContext ctx = parser("according to Table \"table 1\"").condition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Fixture result = instance.visitCondition(ctx); assertThat(result, is(instanceOf(TableRef.class))); } @Test public void testVisitCondition2() throws IOException { YokohamaUnitParser.ConditionContext ctx = parser("where a = `1`").condition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Fixture result = instance.visitCondition(ctx); assertThat(result, is(instanceOf(Bindings.class))); } @Test public void testVisitTableRef() throws IOException { YokohamaUnitParser.TableRefContext ctx = parser("according to Table \"table name\"").tableRef(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); //Object expResult = null; TableRef result = instance.visitTableRef(ctx); assertEquals("table name", result.getName()); } @Test public void testVisitTableType() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("Table"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.INLINE; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitTableType2() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("CSV"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.CSV; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitTableType3() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("TSV"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.TSV; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitTableType4() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("Excel"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.EXCEL; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitPropositions() throws IOException { YokohamaUnitParser.PropositionsContext ctx = parser("`a` is `b`").propositions(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<Proposition> result = instance.visitPropositions(ctx); assertThat(result.size(), is(1)); } @Test public void testVisitPropositions2() throws IOException { YokohamaUnitParser.PropositionsContext ctx = parser("`a` is `b` and `c` is `d`").propositions(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<Proposition> result = instance.visitPropositions(ctx); assertThat(result.size(), is(2)); } @Test public void testVisitProposition() throws IOException { YokohamaUnitParser.PropositionContext ctx = parser("`a` is `b`").proposition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Proposition actual = instance.visitProposition(ctx); Proposition expected = new Proposition(new Expr("a"), Copula.IS, new Expr("b")); assertThat(actual, is(expected)); } @Test public void testVisitTableDef() throws IOException { YokohamaUnitParser.TableDefContext ctx = parser("Table: table name\n|a|b\n|1|2\n").tableDef(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Table actual = instance.visitTableDef(ctx); Table expected = new Table( "table name", Arrays.asList("a", "b"), Arrays.asList(new Row( Arrays.asList(new Expr("1"), new Expr("2"))))); assertThat(actual, is(expected)); } @Test public void testVisitHeader() throws IOException { YokohamaUnitParser.HeaderContext ctx = parser("|a|b\n").header(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<String> actual = instance.visitHeader(ctx); List<String> expected = Arrays.asList("a", "b"); assertThat(actual, is(expected)); } @Test public void testVisitRows() throws IOException { YokohamaUnitParser.RowsContext ctx = parser("|a|b|\n|c|d|\n", YokohamaUnitLexer.IN_TABLE_ONSET).rows(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<Row> actual = instance.visitRows(ctx); List<Row> expected = Arrays.asList( new Row(Arrays.asList(new Expr("a"), new Expr("b"))), new Row(Arrays.asList(new Expr("c"), new Expr("d")))); assertThat(actual, is(expected)); } @Test public void testVisitRow() throws IOException { YokohamaUnitParser.RowContext ctx = parser("|a|b\n", YokohamaUnitLexer.IN_TABLE_ONSET).row(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Row actual = instance.visitRow(ctx); Row expected = new Row(Arrays.asList(new Expr("a"), new Expr("b"))); assertThat(actual, is(expected)); } @Test public void testVisitFourPhaseTest() throws IOException { YokohamaUnitParser.FourPhaseTestContext ctx = parser("Test: Four phase test\nVerify\nAssert `x` is `1`.").fourPhaseTest(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); FourPhaseTest actual = instance.visitFourPhaseTest(ctx); FourPhaseTest expected = new FourPhaseTest( 0, "Four phase test", Optional.empty(), Optional.empty(), new VerifyPhase( 0, Optional.empty(), Arrays.asList( new Assertion( Arrays.asList( new Proposition(new Expr("x"), Copula.IS, new Expr("1"))), Fixture.none())) ), Optional.empty() ); assertThat(actual, is(expected)); } @Test public void testVisitFourPhaseTest2() throws IOException { YokohamaUnitParser.FourPhaseTestContext ctx = parser("# Test: Four phase test\n## Setup\nLet x be `1`.\n## Exercise\nDo `that`.\n## Verify: verification\nAssert that `x` is `1`.\n## Teardown: do that\nDo `this`. Do `that`. ").fourPhaseTest(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); FourPhaseTest actual = instance.visitFourPhaseTest(ctx); FourPhaseTest expected = new FourPhaseTest( 1, "Four phase test", Optional.of(new Phase( 2, Optional.empty(), Optional.of(new LetBindings(Arrays.asList(new LetBinding("x", new Expr("1"))))), Arrays.asList()) ), Optional.of(new Phase( 2, Optional.empty(), Optional.empty(), Arrays.asList(new Execution(Arrays.asList(new Expr("that"))))) ), new VerifyPhase( 2, Optional.of("verification"), Arrays.asList( new Assertion( Arrays.asList( new Proposition(new Expr("x"), Copula.IS, new Expr("1"))), Fixture.none())) ), Optional.of(new Phase( 2, Optional.of("do that"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) )) ) ); assertThat(actual, is(expected)); } @Test public void testVisitSetup() throws IOException { YokohamaUnitParser.SetupContext ctx = parser("Setup\nLet x be `1`.").setup(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitSetup(ctx); Phase expected = new Phase( 0, Optional.empty(), Optional.of(new LetBindings(Arrays.asList(new LetBinding("x", new Expr("1"))))), Arrays.asList() ); assertThat(actual, is(expected)); } @Test public void testVisitSetup2() throws IOException { YokohamaUnitParser.SetupContext ctx = parser("## Setup: x = 1\nDo `this`. Do `that`.").setup(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitSetup(ctx); Phase expected = new Phase( 2, Optional.of("x = 1"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitSetup3() throws IOException { YokohamaUnitParser.SetupContext ctx = parser("Setup\nLet x = `1`\nDo `that`.").setup(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitSetup(ctx); Phase expected = new Phase( 0, Optional.empty(), Optional.of(new LetBindings(Arrays.asList(new LetBinding("x", new Expr("1"))))), Arrays.asList(new Execution(Arrays.asList(new Expr("that")))) ); assertThat(actual, is(expected)); } @Test public void testVisitExercise() throws IOException { YokohamaUnitParser.ExerciseContext ctx = parser("Exercise: x = 1\nDo `this`. Do `that`.").exercise(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitExercise(ctx); Phase expected = new Phase( 0, Optional.of("x = 1"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitVerify() throws IOException { YokohamaUnitParser.VerifyContext ctx = parser("Verify\nAssert that `x` is `1`.").verify(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase expResult = null; VerifyPhase actual = instance.visitVerify(ctx); VerifyPhase expected = new VerifyPhase( 0, Optional.empty(), Arrays.asList( new Assertion( Arrays.asList(new Proposition(new Expr("x"), Copula.IS, new Expr("1"))), Fixture.none())) ); assertThat(actual, is(expected)); } @Test public void testVisitTeardown() throws IOException { YokohamaUnitParser.TeardownContext ctx = parser("## Teardown: do that\nDo `this`. Do `that`.").teardown(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitTeardown(ctx); Phase expected = new Phase( 2, Optional.of("do that"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitTeardown2() throws IOException { YokohamaUnitParser.TeardownContext ctx = parser("Teardown\nDo `this`.").teardown(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitTeardown(ctx); Phase expected = new Phase( 0, Optional.empty(), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitLetBindings() throws IOException { YokohamaUnitParser.LetBindingsContext ctx = parser("Let x be `1` and y = `2`.").letBindings(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); LetBindings actual = instance.visitLetBindings(ctx); LetBindings expected = new LetBindings(Arrays.asList( new LetBinding("x", new Expr("1")), new LetBinding("y", new Expr("2")) )); assertThat(actual, is(expected)); } @Test public void testVisitLetBinding() throws IOException { YokohamaUnitParser.LetBindingContext ctx = parser("x = `1`").letBinding(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); LetBinding actual = instance.visitLetBinding(ctx); LetBinding expected = new LetBinding("x", new Expr("1")); assertThat(actual, is(expected)); } @Test public void testVisitExecution() throws IOException { YokohamaUnitParser.ExecutionContext ctx = parser("Do `System.out.println(\"test\")`.").execution(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Execution actual = instance.visitExecution(ctx); Execution expected = new Execution(Arrays.asList(new Expr("System.out.println(\"test\")"))); assertThat(actual, is(expected)); } @Test public void testVisitExecution2() throws IOException { YokohamaUnitParser.ExecutionContext ctx = parser("Do `this` and `that`.").execution(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Execution actual = instance.visitExecution(ctx); Execution expected = new Execution(Arrays.asList(new Expr("this"), new Expr("that"))); assertThat(actual, is(expected)); } }
src/test/java/yokohama/unit/translator/ParseTreeToAstVisitorTest.java
package yokohama.unit.translator; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.tree.TerminalNode; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import yokohama.unit.ast.Assertion; import yokohama.unit.ast.Binding; import yokohama.unit.ast.Bindings; import yokohama.unit.ast.Copula; import yokohama.unit.ast.Definition; import yokohama.unit.ast.Execution; import yokohama.unit.ast.Expr; import yokohama.unit.ast.Fixture; import yokohama.unit.ast.FourPhaseTest; import yokohama.unit.ast.Group; import yokohama.unit.ast.LetBinding; import yokohama.unit.ast.LetBindings; import yokohama.unit.ast.Phase; import yokohama.unit.ast.Proposition; import yokohama.unit.ast.Row; import yokohama.unit.ast.Table; import yokohama.unit.ast.TableRef; import yokohama.unit.ast.TableType; import yokohama.unit.ast.VerifyPhase; import yokohama.unit.grammar.YokohamaUnitLexer; import yokohama.unit.grammar.YokohamaUnitParser; public class ParseTreeToAstVisitorTest { public static YokohamaUnitParser parser(String input) throws IOException { return parser(input, YokohamaUnitLexer.DEFAULT_MODE); } public static YokohamaUnitParser parser(String input, int mode) throws IOException { InputStream bais = new ByteArrayInputStream(input.getBytes()); CharStream stream = new ANTLRInputStream(bais); Lexer lex = new YokohamaUnitLexer(stream); lex.mode(mode); CommonTokenStream tokens = new CommonTokenStream(lex); YokohamaUnitParser parser = new YokohamaUnitParser(tokens); return parser; } @Test public void testVisitGroup() throws IOException { YokohamaUnitParser.GroupContext ctx = parser("Test: test name\nAssert `a` is `b`.").group(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Group result = instance.visitGroup(ctx); assertThat(result.getDefinitions().size(), is(1)); } @Test public void testVisitDefinition() throws IOException { YokohamaUnitParser.DefinitionContext ctx = parser("Test: test name\n Assert `a` is `b`.").definition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Definition result = instance.visitDefinition(ctx); assertThat(result, is(instanceOf(yokohama.unit.ast.Test.class))); } @Test public void testVisitDefinition2() throws IOException { YokohamaUnitParser.DefinitionContext ctx = parser("Table: table name\n|a|b\n----\n|1|2\n\n").definition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Definition result = instance.visitDefinition(ctx); assertThat(result, is(instanceOf(Table.class))); } @Test public void testVisitTest() { TerminalNode nameTerminalNode = mock(TerminalNode.class); YokohamaUnitParser.TestContext ctx = mock(YokohamaUnitParser.TestContext.class); when(nameTerminalNode.getText()).thenReturn("test name"); when(ctx.TestName()).thenReturn(nameTerminalNode); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); yokohama.unit.ast.Test result = instance.visitTest(ctx); assertEquals("test name", result.getName()); } @Test public void testVisitHash() throws IOException { YokohamaUnitParser.HashContext ctx = parser("#").hash(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Integer actual = instance.visitHash(ctx); Integer expected = 1; assertThat(actual, is(expected)); } @Test public void testVisitHash2() throws IOException { YokohamaUnitParser.HashContext ctx = parser("######").hash(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Integer actual = instance.visitHash(ctx); Integer expected = 6; assertThat(actual, is(expected)); } @Test public void testVisitAssertion() throws IOException { YokohamaUnitParser.AssertionContext ctx = parser("Assert `a` is `b`.").assertion(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Assertion actual = instance.visitAssertion(ctx); Assertion expected = new Assertion( Arrays.asList(new Proposition(new Expr("a"), Copula.IS, new Expr("b"))), Fixture.none()); assertThat(actual, is(expected)); } @Test public void testVisitAssertion2() throws IOException { YokohamaUnitParser.AssertionContext ctx = parser("Assert `a` is `b` where a = `1`.").assertion(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Assertion actual = instance.visitAssertion(ctx); Assertion expected = new Assertion( Arrays.asList(new Proposition(new Expr("a"), Copula.IS, new Expr("b"))), new Bindings(Arrays.asList(new Binding("a", new Expr("1"))))); assertThat(actual, is(expected)); } @Test public void testVisitCopula() { YokohamaUnitParser.CopulaContext ctx = mock(YokohamaUnitParser.CopulaContext.class); when(ctx.getText()).thenReturn("is"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Copula expResult = Copula.IS; Copula result = instance.visitCopula(ctx); assertEquals(expResult, result); } @Test public void testVisitCopula2() { YokohamaUnitParser.CopulaContext ctx = mock(YokohamaUnitParser.CopulaContext.class); when(ctx.getText()).thenReturn("throws"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Copula expResult = Copula.THROWS; Copula result = instance.visitCopula(ctx); assertEquals(expResult, result); } @Test public void testVisitCopula3() { YokohamaUnitParser.CopulaContext ctx = mock(YokohamaUnitParser.CopulaContext.class); when(ctx.getText()).thenReturn("isnot"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Copula expResult = Copula.IS_NOT; Copula result = instance.visitCopula(ctx); assertEquals(expResult, result); } @Test public void testVisitBindings() throws IOException { YokohamaUnitParser.BindingsContext ctx = parser("where a = `1`").bindings(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Bindings result = instance.visitBindings(ctx); assertThat(result.getBindings().size(), is(1)); } @Test public void testVisitBindings2() throws IOException { YokohamaUnitParser.BindingsContext ctx = parser("where a = `1` and b = `2`").bindings(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Bindings result = instance.visitBindings(ctx); assertThat(result.getBindings().size(), is(2)); } @Test public void testVisitBinding() throws IOException { YokohamaUnitParser.BindingContext ctx = parser("a = `1`").binding(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Binding result = instance.visitBinding(ctx); assertThat(result, is(new Binding("a", new Expr("1")))); } @Test public void testVisitCondition() throws IOException { YokohamaUnitParser.ConditionContext ctx = parser("according to Table \"table 1\"").condition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Fixture result = instance.visitCondition(ctx); assertThat(result, is(instanceOf(TableRef.class))); } @Test public void testVisitCondition2() throws IOException { YokohamaUnitParser.ConditionContext ctx = parser("where a = `1`").condition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Fixture result = instance.visitCondition(ctx); assertThat(result, is(instanceOf(Bindings.class))); } @Test public void testVisitTableRef() throws IOException { YokohamaUnitParser.TableRefContext ctx = parser("according to Table \"table name\"").tableRef(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); //Object expResult = null; TableRef result = instance.visitTableRef(ctx); assertEquals("table name", result.getName()); } @Test public void testVisitTableType() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("Table"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.INLINE; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitTableType2() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("CSV"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.CSV; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitTableType3() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("TSV"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.TSV; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitTableType4() { YokohamaUnitParser.TableTypeContext ctx = mock(YokohamaUnitParser.TableTypeContext.class); when(ctx.getText()).thenReturn("Excel"); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Object expResult = TableType.EXCEL; Object result = instance.visitTableType(ctx); assertEquals(expResult, result); } @Test public void testVisitPropositions() throws IOException { YokohamaUnitParser.PropositionsContext ctx = parser("`a` is `b`").propositions(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<Proposition> result = instance.visitPropositions(ctx); assertThat(result.size(), is(1)); } @Test public void testVisitPropositions2() throws IOException { YokohamaUnitParser.PropositionsContext ctx = parser("`a` is `b` and `c` is `d`").propositions(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<Proposition> result = instance.visitPropositions(ctx); assertThat(result.size(), is(2)); } @Test public void testVisitProposition() throws IOException { YokohamaUnitParser.PropositionContext ctx = parser("`a` is `b`").proposition(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Proposition actual = instance.visitProposition(ctx); Proposition expected = new Proposition(new Expr("a"), Copula.IS, new Expr("b")); assertThat(actual, is(expected)); } @Test public void testVisitTableDef() throws IOException { YokohamaUnitParser.TableDefContext ctx = parser("Table: table name\n|a|b\n|1|2\n").tableDef(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Table actual = instance.visitTableDef(ctx); Table expected = new Table( "table name", Arrays.asList("a", "b"), Arrays.asList(new Row( Arrays.asList(new Expr("1"), new Expr("2"))))); assertThat(actual, is(expected)); } @Test public void testVisitHeader() throws IOException { YokohamaUnitParser.HeaderContext ctx = parser("|a|b\n").header(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<String> actual = instance.visitHeader(ctx); List<String> expected = Arrays.asList("a", "b"); assertThat(actual, is(expected)); } @Test public void testVisitRows() throws IOException { YokohamaUnitParser.RowsContext ctx = parser("|a|b|\n|c|d|\n", YokohamaUnitLexer.IN_TABLE_ONSET).rows(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); List<Row> actual = instance.visitRows(ctx); List<Row> expected = Arrays.asList( new Row(Arrays.asList(new Expr("a"), new Expr("b"))), new Row(Arrays.asList(new Expr("c"), new Expr("d")))); assertThat(actual, is(expected)); } @Test public void testVisitRow() throws IOException { YokohamaUnitParser.RowContext ctx = parser("|a|b\n", YokohamaUnitLexer.IN_TABLE_ONSET).row(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Row actual = instance.visitRow(ctx); Row expected = new Row(Arrays.asList(new Expr("a"), new Expr("b"))); assertThat(actual, is(expected)); } @Test public void testVisitFourPhaseTest() throws IOException { YokohamaUnitParser.FourPhaseTestContext ctx = parser("Test: Four phase test\nVerify\nAssert `1` is `1`.").fourPhaseTest(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); FourPhaseTest actual = instance.visitFourPhaseTest(ctx); FourPhaseTest expected = new FourPhaseTest( 0, "Four phase test", Optional.empty(), Optional.empty(), new VerifyPhase( 0, Optional.empty(), Arrays.asList( new Assertion( Arrays.asList( new Proposition(new Expr("x"), Copula.IS, new Expr("1"))), Fixture.none())) ), Optional.empty() ); assertThat(actual, is(expected)); } @Test public void testVisitFourPhaseTest2() throws IOException { YokohamaUnitParser.FourPhaseTestContext ctx = parser("# Test: Four phase test\n## Setup\nLet x be `1`.\n## Exercise\nDo `that`.\n## Verify: verification\nAssert that `x` is `1`.\n## Teardown: do that\nDo `this`. Do `that`. ").fourPhaseTest(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); FourPhaseTest actual = instance.visitFourPhaseTest(ctx); FourPhaseTest expected = new FourPhaseTest( 1, "Four phase test", Optional.of(new Phase( 2, Optional.empty(), Optional.of(new LetBindings(Arrays.asList(new LetBinding("x", new Expr("1"))))), Arrays.asList()) ), Optional.of(new Phase( 2, Optional.empty(), Optional.empty(), Arrays.asList(new Execution(Arrays.asList(new Expr("that"))))) ), new VerifyPhase( 2, Optional.of("verification"), Arrays.asList( new Assertion( Arrays.asList( new Proposition(new Expr("x"), Copula.IS, new Expr("1"))), Fixture.none())) ), Optional.of(new Phase( 2, Optional.of("do that"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) )) ) ); assertThat(actual, is(expected)); } @Test public void testVisitSetup() throws IOException { YokohamaUnitParser.SetupContext ctx = parser("Setup\nLet x be `1`.").setup(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitSetup(ctx); Phase expected = new Phase( 0, Optional.empty(), Optional.of(new LetBindings(Arrays.asList(new LetBinding("x", new Expr("1"))))), Arrays.asList() ); assertThat(actual, is(expected)); } @Test public void testVisitSetup2() throws IOException { YokohamaUnitParser.SetupContext ctx = parser("## Setup: x = 1\nDo `this`. Do `that`.").setup(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitSetup(ctx); Phase expected = new Phase( 2, Optional.of("x = 1"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitSetup3() throws IOException { YokohamaUnitParser.SetupContext ctx = parser("Setup\nLet x = `1`\nDo `that`.").setup(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitSetup(ctx); Phase expected = new Phase( 0, Optional.empty(), Optional.of(new LetBindings(Arrays.asList(new LetBinding("x", new Expr("1"))))), Arrays.asList(new Execution(Arrays.asList(new Expr("that")))) ); assertThat(actual, is(expected)); } @Test public void testVisitExercise() throws IOException { YokohamaUnitParser.ExerciseContext ctx = parser("Exercise: x = 1\nDo `this`. Do `that`.").exercise(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitExercise(ctx); Phase expected = new Phase( 0, Optional.of("x = 1"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitVerify() throws IOException { YokohamaUnitParser.VerifyContext ctx = parser("Verify\nAssert that `x` is `1`.").verify(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase expResult = null; VerifyPhase actual = instance.visitVerify(ctx); VerifyPhase expected = new VerifyPhase( 0, Optional.empty(), Arrays.asList( new Assertion( Arrays.asList(new Proposition(new Expr("x"), Copula.IS, new Expr("1"))), Fixture.none())) ); assertThat(actual, is(expected)); } @Test public void testVisitTeardown() throws IOException { YokohamaUnitParser.TeardownContext ctx = parser("## Teardown: do that\nDo `this`. Do `that`.").teardown(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitTeardown(ctx); Phase expected = new Phase( 2, Optional.of("do that"), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))), new Execution(Arrays.asList(new Expr("that"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitTeardown2() throws IOException { YokohamaUnitParser.TeardownContext ctx = parser("Teardown\nDo `this`.").teardown(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Phase actual = instance.visitTeardown(ctx); Phase expected = new Phase( 0, Optional.empty(), Optional.empty(), Arrays.asList( new Execution(Arrays.asList(new Expr("this"))) ) ); assertThat(actual, is(expected)); } @Test public void testVisitLetBindings() throws IOException { YokohamaUnitParser.LetBindingsContext ctx = parser("Let x be `1` and y = `2`.").letBindings(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); LetBindings actual = instance.visitLetBindings(ctx); LetBindings expected = new LetBindings(Arrays.asList( new LetBinding("x", new Expr("1")), new LetBinding("y", new Expr("2")) )); assertThat(actual, is(expected)); } @Test public void testVisitLetBinding() throws IOException { YokohamaUnitParser.LetBindingContext ctx = parser("x = `1`").letBinding(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); LetBinding actual = instance.visitLetBinding(ctx); LetBinding expected = new LetBinding("x", new Expr("1")); assertThat(actual, is(expected)); } @Test public void testVisitExecution() throws IOException { YokohamaUnitParser.ExecutionContext ctx = parser("Do `System.out.println(\"test\")`.").execution(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Execution actual = instance.visitExecution(ctx); Execution expected = new Execution(Arrays.asList(new Expr("System.out.println(\"test\")"))); assertThat(actual, is(expected)); } @Test public void testVisitExecution2() throws IOException { YokohamaUnitParser.ExecutionContext ctx = parser("Do `this` and `that`.").execution(); ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); Execution actual = instance.visitExecution(ctx); Execution expected = new Execution(Arrays.asList(new Expr("this"), new Expr("that"))); assertThat(actual, is(expected)); } }
Fix test data
src/test/java/yokohama/unit/translator/ParseTreeToAstVisitorTest.java
Fix test data
<ide><path>rc/test/java/yokohama/unit/translator/ParseTreeToAstVisitorTest.java <ide> <ide> @Test <ide> public void testVisitFourPhaseTest() throws IOException { <del> YokohamaUnitParser.FourPhaseTestContext ctx = parser("Test: Four phase test\nVerify\nAssert `1` is `1`.").fourPhaseTest(); <add> YokohamaUnitParser.FourPhaseTestContext ctx = parser("Test: Four phase test\nVerify\nAssert `x` is `1`.").fourPhaseTest(); <ide> ParseTreeToAstVisitor instance = new ParseTreeToAstVisitor(); <ide> FourPhaseTest actual = instance.visitFourPhaseTest(ctx); <ide> FourPhaseTest expected = new FourPhaseTest(
Java
apache-2.0
e7e43386dfd4082351aa021958b63826d0c3bd80
0
mpetazzoni/ttorrent,JetBrains/ttorrent-lib,JetBrains/ttorrent-lib,mpetazzoni/ttorrent
package com.turn.ttorrent.client; import com.turn.ttorrent.TempFiles; import com.turn.ttorrent.WaitFor; import com.turn.ttorrent.client.peer.SharingPeer; import com.turn.ttorrent.common.Torrent; import com.turn.ttorrent.tracker.TrackedPeer; import com.turn.ttorrent.tracker.TrackedTorrent; import com.turn.ttorrent.tracker.Tracker; import org.apache.commons.io.FileUtils; import org.apache.log4j.*; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.*; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.CRC32; import java.util.zip.Checksum; import static org.testng.Assert.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * @author Sergey.Pak * Date: 7/26/13 * Time: 2:32 PM */ @Test public class ClientTest { private List<Client> clientList; private static final String TEST_RESOURCES = "src/test/resources"; private Tracker tracker; private TempFiles tempFiles; public ClientTest(){ if (Logger.getRootLogger().getAllAppenders().hasMoreElements()) return; BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("[%d{MMdd HH:mm:ss,SSS} %t] %6p - %20.20c - %m %n"))); Logger.getRootLogger().setLevel(Level.INFO); Torrent.setHashingThreadsCount(1); } @BeforeMethod public void setUp() throws IOException { tempFiles = new TempFiles(); clientList = new ArrayList<Client>(); startTracker(); } // @Test(invocationCount = 50) public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient(); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = Torrent.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); torrent.save(torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); SharedTorrent st1 = SharedTorrent.fromFile(torrentFile, f.getParentFile(), true); seeder.addTorrent(st1); } leech = createClient(); leech.start(InetAddress.getLocalHost()); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); SharedTorrent st2 = SharedTorrent.fromFile(torrentFile, downloadDir, true); leech.addTorrent(st2); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")){ count++; partItems.add(s); } } if (count < 5){ System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertTrue(listFileNames(downloadDir).equals(names)); } finally { leech.stop(true); seeder.stop(true); } } private Set<String> listFileNames(File downloadDir) { if (downloadDir == null) return Collections.emptySet(); Set<String> names = new HashSet<String>(); File[] files = downloadDir.listFiles(); if (files == null) return Collections.emptySet(); for (File f : files) { names.add(f.getName()); } return names; } // @Test(invocationCount = 50) public void large_file_download() throws IOException, URISyntaxException, NoSuchAlgorithmException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); File tempFile = tempFiles.createTempFile(201 * 1025 * 1024); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); Torrent torrent = Torrent.create(tempFile, announceURI, "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); torrent.save(torrentFile); Client seeder = createClient(); seeder.addTorrent(SharedTorrent.fromFile(torrentFile, tempFile.getParentFile(), true)); final File downloadDir = tempFiles.createTempDir(); Client leech = createClient(); leech.addTorrent(SharedTorrent.fromFile(torrentFile, downloadDir, true)); try { seeder.start(InetAddress.getLocalHost()); leech.start(InetAddress.getLocalHost()); waitForFileInDir(downloadDir, tempFile.getName()); assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName())); } finally { seeder.stop(true); leech.stop(true); } } public void more_than_one_seeder_for_same_torrent() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { this.tracker.setAcceptForeignTorrents(true); assertEquals(0, this.tracker.getTrackedTorrents().size()); int numSeeders = 5; List<Client> seeders = new ArrayList<Client>(); for (int i = 0; i < numSeeders; i++) { seeders.add(createClient()); } try { File tempFile = tempFiles.createTempFile(100 * 1024); Torrent torrent = Torrent.create(tempFile, this.tracker.getAnnounceURI(), "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); torrent.save(torrentFile); for (int i = 0; i < numSeeders; i++) { Client client = seeders.get(i); client.addTorrent(SharedTorrent.fromFile(torrentFile, tempFile.getParentFile(), false)); client.start(InetAddress.getLocalHost()); } waitForPeers(numSeeders); Collection<TrackedTorrent> torrents = this.tracker.getTrackedTorrents(); assertEquals(torrents.size(), 1); assertEquals(numSeeders, torrents.iterator().next().seeders()); } finally { for (Client client : seeders) { client.stop(); } } } public void no_full_seeder_test() throws IOException, URISyntaxException, InterruptedException, NoSuchAlgorithmException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48*1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders * 3 + 15; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File tempFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(tempFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(tempFile, md5); validateMultipleClientsResults(clientsList, md5, tempFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } public void testDelete() throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); final File downloadDir2 = tempFiles.createTempDir(); Client seeder = createClient(); seeder.start(InetAddress.getLocalHost()); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); File tempFile = tempFiles.createTempFile(513 * 1024); final File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = Torrent.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); torrent.save(torrentFile); names.add(srcFile.getName()); seeder.addTorrent(new SharedTorrent(torrent, srcFile.getParentFile(), false)); Client leech1 = createClient(); leech1.start(InetAddress.getLocalHost()); SharedTorrent sharedTorrent = SharedTorrent.fromFile(torrentFile, downloadDir, true); leech1.addTorrent(sharedTorrent); new WaitFor(15 * 1000) { @Override protected boolean condition() { return listFileNames(downloadDir).contains(srcFile.getName()); } }; assertTrue(listFileNames(downloadDir).contains(srcFile.getName())); leech1.stop(true); leech1=null; assertTrue(srcFile.delete()); Client leech2 = createClient(); leech2.start(InetAddress.getLocalHost()); SharedTorrent st2 = SharedTorrent.fromFile(torrentFile, downloadDir2, true); leech2.addTorrent(st2); Thread.sleep(10 * 1000); // the file no longer exists. Stop seeding and announce that to tracker final TrackedTorrent trackedTorrent = tracker.getTrackedTorrent(torrent.getHexInfoHash()); assertEquals(0, seeder.getTorrents().size()); for (SharingPeer peer : seeder.getPeers()) { assertFalse(trackedTorrent.getPeers().keySet().contains(peer.getTorrentHexInfoHash())); } } // @Test(invocationCount = 50) public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48*1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders +7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); Client firstClient = clientsList.get(0); final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount()-1){ return false; } } return true; } }; if (!waitFor.isMyResult()){ fail("All seeders didn't get their files"); } Thread.sleep(10*1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } public void corrupted_seeder() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48*1024; // lower piece size to reduce disk usage final int piecesCount = 35; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { final File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); final File badFile = tempFiles.createTempFile(piecesCount * pieceSize); final Client client2 = createAndStartClient(); final File client2Dir = tempFiles.createTempDir(); final File client2File = new File(client2Dir, baseFile.getName()); FileUtils.copyFile(badFile, client2File); final Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); client2.addTorrent(new SharedTorrent(torrent, client2Dir, false, true)); final String baseMD5 = getFileMD5(baseFile, md5); final Client leech = createAndStartClient(); final File leechDestDir = tempFiles.createTempDir(); final AtomicReference<Exception> thrownException = new AtomicReference<Exception>(); final Thread th = new Thread(new Runnable() { @Override public void run() { try { leech.downloadUninterruptibly(new SharedTorrent(torrent, leechDestDir, false), 7); } catch (Exception e) { thrownException.set(e); throw new RuntimeException(e); } } }); th.start(); final WaitFor waitFor = new WaitFor(30 * 1000) { @Override protected boolean condition() { return th.getState() == Thread.State.TERMINATED; } }; final Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) { System.out.printf("%s:%n", entry.getKey().getName()); for (StackTraceElement elem : entry.getValue()) { System.out.println(elem.toString()); } } assertTrue(waitFor.isMyResult()); assertNotNull(thrownException.get()); assertTrue(thrownException.get().getMessage().contains("Unable to download torrent completely")); } finally { for (Client client : clientsList) { client.stop(); } } } public void unlock_file_when_no_leechers() throws InterruptedException, NoSuchAlgorithmException, IOException { Client seeder = createClient(); tracker.setAcceptForeignTorrents(true); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); seeder.start(InetAddress.getLocalHost()); downloadAndStop(torrent, 15*1000, createClient()); Thread.sleep(2 * 1000); assertTrue(dwnlFile.exists() && dwnlFile.isFile()); final boolean delete = dwnlFile.delete(); assertTrue(delete && !dwnlFile.exists()); } public void download_many_times() throws InterruptedException, NoSuchAlgorithmException, IOException { Client seeder = createClient(); tracker.setAcceptForeignTorrents(true); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); seeder.start(InetAddress.getLocalHost()); for(int i=0; i<5; i++) { downloadAndStop(torrent, 250*1000, createClient()); Thread.sleep(3*1000); } } public void download_io_error() throws InterruptedException, NoSuchAlgorithmException, IOException{ tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); seeder.start(InetAddress.getLocalHost()); final AtomicInteger interrupts = new AtomicInteger(0); final Client leech = new Client(){ @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { super.handlePieceCompleted(peer, piece); if (piece.getIndex()%4==0 && interrupts.incrementAndGet() <= 2){ peer.getSocketChannel().close(); } } }; //manually add leech here for graceful shutdown. clientList.add(leech); downloadAndStop(torrent, 45 * 1000, leech); Thread.sleep(2*1000); } public void download_uninterruptibly_positive() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); leecher.downloadUninterruptibly(st, 10); assertTrue(st.getClientState()==ClientState.SEEDING); } public void download_uninterruptibly_negative() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); final AtomicInteger downloadedPiecesCount = new AtomicInteger(0); final Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); final Client leecher = new Client(){ @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { super.handlePieceCompleted(peer, piece); if (downloadedPiecesCount.incrementAndGet() > 10){ seeder.stop(); } } }; clientList.add(leecher); leecher.start(InetAddress.getLocalHost()); final File destDir = tempFiles.createTempDir(); final SharedTorrent st = new SharedTorrent(torrent, destDir, true); try { leecher.downloadUninterruptibly(st, 5); fail("Must fail, because file wasn't downloaded completely"); } catch (IOException ex){ assertEquals(st.getClientState(),ClientState.DONE); // ensure .part was deleted: assertEquals(0, destDir.list().length); } } public void download_uninterruptibly_timeout() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); final AtomicInteger piecesDownloaded = new AtomicInteger(0); Client leecher = new Client(){ @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { piecesDownloaded.incrementAndGet(); try { Thread.sleep(piecesDownloaded.get()*500); } catch (InterruptedException e) { } } }; clientList.add(leecher); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); try { leecher.downloadUninterruptibly(st, 5); fail("Must fail, because file wasn't downloaded completely"); } catch (IOException ex){ assertEquals(st.getClientState(),ClientState.DONE); } } public void peer_dies_during_download() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAnnounceInterval(5); final Client seed1 = createClient(); final Client seed2 = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 240); final Torrent torrent = Torrent.create(dwnlFile, tracker.getAnnounceURI(), "Test"); seed1.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true)); seed1.start(InetAddress.getLocalHost()); seed1.setAnnounceInterval(5); seed2.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true)); seed2.start(InetAddress.getLocalHost()); seed2.setAnnounceInterval(5); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); leecher.setAnnounceInterval(5); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); final ExecutorService service = Executors.newFixedThreadPool(1); service.submit(new Runnable() { @Override public void run() { try { Thread.sleep(5 * 1000); seed1.removeTorrent(torrent); Thread.sleep(3*1000); seed1.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true)); seed2.removeTorrent(torrent); } catch (InterruptedException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); leecher.downloadUninterruptibly(st, 60); /* seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); leecher.downloadUninterruptibly(st, 10); assertTrue(st.getClientState()==ClientState.SEEDING); */ } public void interrupt_download() throws IOException, InterruptedException, NoSuchAlgorithmException { tracker.setAcceptForeignTorrents(true); final Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 60); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); final Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); final AtomicBoolean interrupted = new AtomicBoolean(); final Thread th = new Thread(){ @Override public void run() { try { leecher.downloadUninterruptibly(st, 30); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { interrupted.set(true); return; } } }; th.start(); Thread.sleep(1000); th.interrupt(); new WaitFor(10*1000){ @Override protected boolean condition() { return !th.isAlive(); } }; assertTrue(st.getClientState() != ClientState.SEEDING); assertTrue(interrupted.get()); } public void test_connect_to_unknown_host() throws InterruptedException, NoSuchAlgorithmException, IOException { final File torrent = new File("src/test/resources/torrents/file1.jar.torrent"); final TrackedTorrent tt = TrackedTorrent.load(torrent); final Client seeder = createAndStartClient(); final Client leecher = createAndStartClient(); final TrackedTorrent announce = tracker.announce(tt); final Random random = new Random(); final File leechFolder = tempFiles.createTempDir(); for (int i=0; i<40; i++) { byte[] data = new byte[20]; random.nextBytes(data); announce.addPeer(new TrackedPeer(tt, "my_unknown_and_unreachablehost" + i, 6881, ByteBuffer.wrap(data))); } seeder.addTorrent(completeTorrent("file1.jar.torrent")); final SharedTorrent incompleteTorrent = incompleteTorrent("file1.jar.torrent", leechFolder); leecher.addTorrent(incompleteTorrent); new WaitFor(10*1000){ @Override protected boolean condition() { return incompleteTorrent.isComplete(); } }; } public void test_seeding_does_not_change_file_modification_date() throws IOException, InterruptedException, NoSuchAlgorithmException { File srcFile = tempFiles.createTempFile(1024); long time = srcFile.lastModified(); Thread.sleep(1000); Client seeder = createAndStartClient(); final Torrent torrent = Torrent.create(srcFile, null, tracker.getAnnounceURI(), "Test"); final SharedTorrent sharedTorrent = new SharedTorrent(torrent, srcFile.getParentFile(), true, true); seeder.addTorrent(sharedTorrent); assertEquals(time, srcFile.lastModified()); } private void downloadAndStop(Torrent torrent, long timeout, final Client leech) throws IOException, NoSuchAlgorithmException, InterruptedException { final File tempDir = tempFiles.createTempDir(); leech.addTorrent(new SharedTorrent(torrent, tempDir, false)); leech.start(InetAddress.getLocalHost()); final WaitFor waitFor = new WaitFor(timeout) { @Override protected boolean condition() { final SharedTorrent leechTorrent = leech.getTorrents().iterator().next(); if (leech.isRunning()) { return leechTorrent.getClientState() == ClientState.SEEDING; } else { return true; } } }; assertTrue(waitFor.isMyResult(), "File wasn't downloaded in time"); } private void validateMultipleClientsResults(final List<Client> clientsList, MessageDigest md5, File baseFile, String baseMD5) throws IOException { final WaitFor waitFor = new WaitFor(75 * 1000) { @Override protected boolean condition() { boolean retval = true; for (Client client : clientsList) { if (!retval) return false; final boolean torrentState = client.getTorrents().iterator().next().getClientState() == ClientState.SEEDING; retval = retval && torrentState; } return retval; } }; assertTrue(waitFor.isMyResult(), "All seeders didn't get their files"); // check file contents here: for (Client client : clientsList) { final SharedTorrent st = client.getTorrents().iterator().next(); final File file = new File(st.getParentFile(), st.getFilenames().get(0)); assertEquals(baseMD5, getFileMD5(file, md5), String.format("MD5 hash is invalid. C:%s, O:%s ", file.getAbsolutePath(), baseFile.getAbsolutePath())); } } private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders, List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount); FileInputStream fin = new FileInputStream(baseFile); for (int i=0; i<piecesCount; i++){ byte[] piece = new byte[pieceSize]; fin.read(piece); piecesList.add(piece); } fin.close(); final long torrentFileLength = baseFile.length(); Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent"); torrent.save(torrentFile); for (int i=0; i<numSeeders; i++){ final File baseDir = tempFiles.createTempDir(); final File seederPiecesFile = new File(baseDir, baseFile.getName()); RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw"); raf.setLength(torrentFileLength); for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){ raf.seek(pieceIdx*pieceSize); raf.write(piecesList.get(pieceIdx)); } Client client = createClient(); clientList.add(client); client.addTorrent(new SharedTorrent(torrent, baseDir, false)); client.start(InetAddress.getLocalHost()); } } private String getFileMD5(File file, MessageDigest digest) throws IOException { DigestInputStream dIn = new DigestInputStream(new FileInputStream(file), digest); while (dIn.read() >= 0); return dIn.getMessageDigest().toString(); } private void waitForSeeder(final byte[] torrentHash) { new WaitFor() { @Override protected boolean condition() { for (TrackedTorrent tt : tracker.getTrackedTorrents()) { if (tt.seeders() == 1 && tt.getHexInfoHash().equals(Torrent.byteArrayToHexString(torrentHash))) return true; } return false; } }; } private void waitForPeers(final int numPeers) { new WaitFor() { @Override protected boolean condition() { for (TrackedTorrent tt : tracker.getTrackedTorrents()) { if (tt.getPeers().size() == numPeers) return true; } return false; } }; } private void waitForFileInDir(final File downloadDir, final String fileName) { new WaitFor() { @Override protected boolean condition() { return new File(downloadDir, fileName).isFile(); } }; assertTrue(new File(downloadDir, fileName).isFile()); } @AfterMethod protected void tearDown() throws Exception { for (Client client : clientList) { client.stop(); } stopTracker(); tempFiles.cleanup(); } private void startTracker() throws IOException { this.tracker = new Tracker(6969); tracker.setAnnounceInterval(5); this.tracker.start(true); } private Client createAndStartClient() throws IOException, NoSuchAlgorithmException, InterruptedException { Client client = createClient(); client.start(InetAddress.getLocalHost()); return client; } private Client createClient() throws IOException, NoSuchAlgorithmException, InterruptedException { final Client client = new Client(); clientList.add(client); return client; } private SharedTorrent completeTorrent(String name) throws IOException, NoSuchAlgorithmException { File torrentFile = new File(TEST_RESOURCES + "/torrents", name); File parentFiles = new File(TEST_RESOURCES + "/parentFiles"); return SharedTorrent.fromFile(torrentFile, parentFiles, false); } private SharedTorrent incompleteTorrent(String name, File destDir) throws IOException, NoSuchAlgorithmException { File torrentFile = new File(TEST_RESOURCES + "/torrents", name); return SharedTorrent.fromFile(torrentFile, destDir, false); } private void stopTracker() { this.tracker.stop(); } private void assertFilesEqual(File f1, File f2) throws IOException { assertEquals(f1.length(), f2.length(), "Files sizes differ"); Checksum c1 = FileUtils.checksum(f1, new CRC32()); Checksum c2 = FileUtils.checksum(f2, new CRC32()); assertEquals(c1.getValue(), c2.getValue()); } }
src/test/java/com/turn/ttorrent/client/ClientTest.java
package com.turn.ttorrent.client; import com.turn.ttorrent.TempFiles; import com.turn.ttorrent.WaitFor; import com.turn.ttorrent.client.peer.SharingPeer; import com.turn.ttorrent.common.Torrent; import com.turn.ttorrent.tracker.TrackedPeer; import com.turn.ttorrent.tracker.TrackedTorrent; import com.turn.ttorrent.tracker.Tracker; import org.apache.commons.io.FileUtils; import org.apache.log4j.*; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.*; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.CRC32; import java.util.zip.Checksum; import static org.testng.Assert.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * @author Sergey.Pak * Date: 7/26/13 * Time: 2:32 PM */ @Test public class ClientTest { private List<Client> clientList; private static final String TEST_RESOURCES = "src/test/resources"; private Tracker tracker; private TempFiles tempFiles; public ClientTest(){ if (Logger.getRootLogger().getAllAppenders().hasMoreElements()) return; BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("[%d{MMdd HH:mm:ss,SSS} %t] %6p - %20.20c - %m %n"))); Logger.getRootLogger().setLevel(Level.INFO); Torrent.setHashingThreadsCount(1); } @BeforeMethod public void setUp() throws IOException { tempFiles = new TempFiles(); clientList = new ArrayList<Client>(); startTracker(); } // @Test(invocationCount = 50) public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient(); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = Torrent.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); torrent.save(torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); SharedTorrent st1 = SharedTorrent.fromFile(torrentFile, f.getParentFile(), true); seeder.addTorrent(st1); } leech = createClient(); leech.start(InetAddress.getLocalHost()); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); SharedTorrent st2 = SharedTorrent.fromFile(torrentFile, downloadDir, true); leech.addTorrent(st2); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")){ count++; partItems.add(s); } } if (count < 5){ System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertTrue(listFileNames(downloadDir).equals(names)); } finally { leech.stop(true); seeder.stop(true); } } private Set<String> listFileNames(File downloadDir) { if (downloadDir == null) return Collections.emptySet(); Set<String> names = new HashSet<String>(); File[] files = downloadDir.listFiles(); if (files == null) return Collections.emptySet(); for (File f : files) { names.add(f.getName()); } return names; } // @Test(invocationCount = 50) public void large_file_download() throws IOException, URISyntaxException, NoSuchAlgorithmException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); File tempFile = tempFiles.createTempFile(201 * 1025 * 1024); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); Torrent torrent = Torrent.create(tempFile, announceURI, "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); torrent.save(torrentFile); Client seeder = createClient(); seeder.addTorrent(SharedTorrent.fromFile(torrentFile, tempFile.getParentFile(), true)); final File downloadDir = tempFiles.createTempDir(); Client leech = createClient(); leech.addTorrent(SharedTorrent.fromFile(torrentFile, downloadDir, true)); try { seeder.start(InetAddress.getLocalHost()); leech.start(InetAddress.getLocalHost()); waitForFileInDir(downloadDir, tempFile.getName()); assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName())); } finally { seeder.stop(true); leech.stop(true); } } public void more_than_one_seeder_for_same_torrent() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { this.tracker.setAcceptForeignTorrents(true); assertEquals(0, this.tracker.getTrackedTorrents().size()); int numSeeders = 5; List<Client> seeders = new ArrayList<Client>(); for (int i = 0; i < numSeeders; i++) { seeders.add(createClient()); } try { File tempFile = tempFiles.createTempFile(100 * 1024); Torrent torrent = Torrent.create(tempFile, this.tracker.getAnnounceURI(), "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); torrent.save(torrentFile); for (int i = 0; i < numSeeders; i++) { Client client = seeders.get(i); client.addTorrent(SharedTorrent.fromFile(torrentFile, tempFile.getParentFile(), false)); client.start(InetAddress.getLocalHost()); } waitForPeers(numSeeders); Collection<TrackedTorrent> torrents = this.tracker.getTrackedTorrents(); assertEquals(torrents.size(), 1); assertEquals(numSeeders, torrents.iterator().next().seeders()); } finally { for (Client client : seeders) { client.stop(); } } } public void no_full_seeder_test() throws IOException, URISyntaxException, InterruptedException, NoSuchAlgorithmException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48*1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders * 3 + 15; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File tempFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(tempFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(tempFile, md5); validateMultipleClientsResults(clientsList, md5, tempFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } public void testDelete() throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); final File downloadDir2 = tempFiles.createTempDir(); Client seeder = createClient(); seeder.start(InetAddress.getLocalHost()); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); File tempFile = tempFiles.createTempFile(513 * 1024); final File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = Torrent.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); torrent.save(torrentFile); names.add(srcFile.getName()); seeder.addTorrent(new SharedTorrent(torrent, srcFile.getParentFile(), false)); Client leech1 = createClient(); leech1.start(InetAddress.getLocalHost()); SharedTorrent sharedTorrent = SharedTorrent.fromFile(torrentFile, downloadDir, true); leech1.addTorrent(sharedTorrent); new WaitFor(15 * 1000) { @Override protected boolean condition() { return listFileNames(downloadDir).contains(srcFile.getName()); } }; assertTrue(listFileNames(downloadDir).contains(srcFile.getName())); leech1.stop(true); leech1=null; assertTrue(srcFile.delete()); Client leech2 = createClient(); leech2.start(InetAddress.getLocalHost()); SharedTorrent st2 = SharedTorrent.fromFile(torrentFile, downloadDir2, true); leech2.addTorrent(st2); Thread.sleep(10 * 1000); // the file no longer exists. Stop seeding and announce that to tracker final TrackedTorrent trackedTorrent = tracker.getTrackedTorrent(torrent.getHexInfoHash()); assertEquals(0, seeder.getTorrents().size()); for (SharingPeer peer : seeder.getPeers()) { assertFalse(trackedTorrent.getPeers().keySet().contains(peer.getTorrentHexInfoHash())); } } // @Test(invocationCount = 50) public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48*1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders +7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); Client firstClient = clientsList.get(0); final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount()-1){ return false; } } return true; } }; if (!waitFor.isMyResult()){ fail("All seeders didn't get their files"); } Thread.sleep(10*1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } public void corrupted_seeder() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48*1024; // lower piece size to reduce disk usage final int piecesCount = 35; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { final File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); final File badFile = tempFiles.createTempFile(piecesCount * pieceSize); final Client client1 = createAndStartClient(); final Client client2 = createAndStartClient(); final File client2Dir = tempFiles.createTempDir(); final File client2File = new File(client2Dir, baseFile.getName()); FileUtils.copyFile(badFile, client2File); final Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); client1.addTorrent(new SharedTorrent(torrent, baseFile.getParentFile(), false, true)); client2.addTorrent(new SharedTorrent(torrent, client2Dir, false, true)); final String baseMD5 = getFileMD5(baseFile, md5); final Client leech = createAndStartClient(); final File leechDestDir = tempFiles.createTempDir(); final AtomicReference<Exception> thrownException = new AtomicReference<Exception>(); final Thread th = new Thread(new Runnable() { @Override public void run() { try { leech.downloadUninterruptibly(new SharedTorrent(torrent, leechDestDir, false), 7); } catch (Exception e) { thrownException.set(e); throw new RuntimeException(e); } } }); th.start(); final WaitFor waitFor = new WaitFor(30 * 1000) { @Override protected boolean condition() { return th.getState() == Thread.State.TERMINATED; } }; final Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) { System.out.printf("%s:%n", entry.getKey().getName()); for (StackTraceElement elem : entry.getValue()) { System.out.println(elem.toString()); } } assertTrue(waitFor.isMyResult()); assertNotNull(thrownException.get()); assertTrue(thrownException.get().getMessage().contains("Unable to download torrent completely")); } finally { for (Client client : clientsList) { client.stop(); } } } public void unlock_file_when_no_leechers() throws InterruptedException, NoSuchAlgorithmException, IOException { Client seeder = createClient(); tracker.setAcceptForeignTorrents(true); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); seeder.start(InetAddress.getLocalHost()); downloadAndStop(torrent, 15*1000, createClient()); Thread.sleep(2 * 1000); assertTrue(dwnlFile.exists() && dwnlFile.isFile()); final boolean delete = dwnlFile.delete(); assertTrue(delete && !dwnlFile.exists()); } public void download_many_times() throws InterruptedException, NoSuchAlgorithmException, IOException { Client seeder = createClient(); tracker.setAcceptForeignTorrents(true); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); seeder.start(InetAddress.getLocalHost()); for(int i=0; i<5; i++) { downloadAndStop(torrent, 250*1000, createClient()); Thread.sleep(3*1000); } } public void download_io_error() throws InterruptedException, NoSuchAlgorithmException, IOException{ tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); seeder.start(InetAddress.getLocalHost()); final AtomicInteger interrupts = new AtomicInteger(0); final Client leech = new Client(){ @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { super.handlePieceCompleted(peer, piece); if (piece.getIndex()%4==0 && interrupts.incrementAndGet() <= 2){ peer.getSocketChannel().close(); } } }; //manually add leech here for graceful shutdown. clientList.add(leech); downloadAndStop(torrent, 45 * 1000, leech); Thread.sleep(2*1000); } public void download_uninterruptibly_positive() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); leecher.downloadUninterruptibly(st, 10); assertTrue(st.getClientState()==ClientState.SEEDING); } public void download_uninterruptibly_negative() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); final AtomicInteger downloadedPiecesCount = new AtomicInteger(0); final Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); final Client leecher = new Client(){ @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { super.handlePieceCompleted(peer, piece); if (downloadedPiecesCount.incrementAndGet() > 10){ seeder.stop(); } } }; clientList.add(leecher); leecher.start(InetAddress.getLocalHost()); final File destDir = tempFiles.createTempDir(); final SharedTorrent st = new SharedTorrent(torrent, destDir, true); try { leecher.downloadUninterruptibly(st, 5); fail("Must fail, because file wasn't downloaded completely"); } catch (IOException ex){ assertEquals(st.getClientState(),ClientState.DONE); // ensure .part was deleted: assertEquals(0, destDir.list().length); } } public void download_uninterruptibly_timeout() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); final AtomicInteger piecesDownloaded = new AtomicInteger(0); Client leecher = new Client(){ @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { piecesDownloaded.incrementAndGet(); try { Thread.sleep(piecesDownloaded.get()*500); } catch (InterruptedException e) { } } }; clientList.add(leecher); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); try { leecher.downloadUninterruptibly(st, 5); fail("Must fail, because file wasn't downloaded completely"); } catch (IOException ex){ assertEquals(st.getClientState(),ClientState.DONE); } } public void peer_dies_during_download() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAnnounceInterval(5); final Client seed1 = createClient(); final Client seed2 = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 240); final Torrent torrent = Torrent.create(dwnlFile, tracker.getAnnounceURI(), "Test"); seed1.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true)); seed1.start(InetAddress.getLocalHost()); seed1.setAnnounceInterval(5); seed2.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true)); seed2.start(InetAddress.getLocalHost()); seed2.setAnnounceInterval(5); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); leecher.setAnnounceInterval(5); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); final ExecutorService service = Executors.newFixedThreadPool(1); service.submit(new Runnable() { @Override public void run() { try { Thread.sleep(5 * 1000); seed1.removeTorrent(torrent); Thread.sleep(3*1000); seed1.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true)); seed2.removeTorrent(torrent); } catch (InterruptedException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); leecher.downloadUninterruptibly(st, 60); /* seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); leecher.downloadUninterruptibly(st, 10); assertTrue(st.getClientState()==ClientState.SEEDING); */ } public void interrupt_download() throws IOException, InterruptedException, NoSuchAlgorithmException { tracker.setAcceptForeignTorrents(true); final Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 60); final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true)); final Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true); final AtomicBoolean interrupted = new AtomicBoolean(); final Thread th = new Thread(){ @Override public void run() { try { leecher.downloadUninterruptibly(st, 30); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { interrupted.set(true); return; } } }; th.start(); Thread.sleep(1000); th.interrupt(); new WaitFor(10*1000){ @Override protected boolean condition() { return !th.isAlive(); } }; assertTrue(st.getClientState() != ClientState.SEEDING); assertTrue(interrupted.get()); } public void test_connect_to_unknown_host() throws InterruptedException, NoSuchAlgorithmException, IOException { final File torrent = new File("src/test/resources/torrents/file1.jar.torrent"); final TrackedTorrent tt = TrackedTorrent.load(torrent); final Client seeder = createAndStartClient(); final Client leecher = createAndStartClient(); final TrackedTorrent announce = tracker.announce(tt); final Random random = new Random(); final File leechFolder = tempFiles.createTempDir(); for (int i=0; i<40; i++) { byte[] data = new byte[20]; random.nextBytes(data); announce.addPeer(new TrackedPeer(tt, "my_unknown_and_unreachablehost" + i, 6881, ByteBuffer.wrap(data))); } seeder.addTorrent(completeTorrent("file1.jar.torrent")); final SharedTorrent incompleteTorrent = incompleteTorrent("file1.jar.torrent", leechFolder); leecher.addTorrent(incompleteTorrent); new WaitFor(10*1000){ @Override protected boolean condition() { return incompleteTorrent.isComplete(); } }; } public void test_seeding_does_not_change_file_modification_date() throws IOException, InterruptedException, NoSuchAlgorithmException { File srcFile = tempFiles.createTempFile(1024); long time = srcFile.lastModified(); Thread.sleep(1000); Client seeder = createAndStartClient(); final Torrent torrent = Torrent.create(srcFile, null, tracker.getAnnounceURI(), "Test"); final SharedTorrent sharedTorrent = new SharedTorrent(torrent, srcFile.getParentFile(), true, true); seeder.addTorrent(sharedTorrent); assertEquals(time, srcFile.lastModified()); } private void downloadAndStop(Torrent torrent, long timeout, final Client leech) throws IOException, NoSuchAlgorithmException, InterruptedException { final File tempDir = tempFiles.createTempDir(); leech.addTorrent(new SharedTorrent(torrent, tempDir, false)); leech.start(InetAddress.getLocalHost()); final WaitFor waitFor = new WaitFor(timeout) { @Override protected boolean condition() { final SharedTorrent leechTorrent = leech.getTorrents().iterator().next(); if (leech.isRunning()) { return leechTorrent.getClientState() == ClientState.SEEDING; } else { return true; } } }; assertTrue(waitFor.isMyResult(), "File wasn't downloaded in time"); } private void validateMultipleClientsResults(final List<Client> clientsList, MessageDigest md5, File baseFile, String baseMD5) throws IOException { final WaitFor waitFor = new WaitFor(75 * 1000) { @Override protected boolean condition() { boolean retval = true; for (Client client : clientsList) { if (!retval) return false; final boolean torrentState = client.getTorrents().iterator().next().getClientState() == ClientState.SEEDING; retval = retval && torrentState; } return retval; } }; assertTrue(waitFor.isMyResult(), "All seeders didn't get their files"); // check file contents here: for (Client client : clientsList) { final SharedTorrent st = client.getTorrents().iterator().next(); final File file = new File(st.getParentFile(), st.getFilenames().get(0)); assertEquals(baseMD5, getFileMD5(file, md5), String.format("MD5 hash is invalid. C:%s, O:%s ", file.getAbsolutePath(), baseFile.getAbsolutePath())); } } private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders, List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount); FileInputStream fin = new FileInputStream(baseFile); for (int i=0; i<piecesCount; i++){ byte[] piece = new byte[pieceSize]; fin.read(piece); piecesList.add(piece); } fin.close(); final long torrentFileLength = baseFile.length(); Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent"); torrent.save(torrentFile); for (int i=0; i<numSeeders; i++){ final File baseDir = tempFiles.createTempDir(); final File seederPiecesFile = new File(baseDir, baseFile.getName()); RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw"); raf.setLength(torrentFileLength); for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){ raf.seek(pieceIdx*pieceSize); raf.write(piecesList.get(pieceIdx)); } Client client = createClient(); clientList.add(client); client.addTorrent(new SharedTorrent(torrent, baseDir, false)); client.start(InetAddress.getLocalHost()); } } private String getFileMD5(File file, MessageDigest digest) throws IOException { DigestInputStream dIn = new DigestInputStream(new FileInputStream(file), digest); while (dIn.read() >= 0); return dIn.getMessageDigest().toString(); } private void waitForSeeder(final byte[] torrentHash) { new WaitFor() { @Override protected boolean condition() { for (TrackedTorrent tt : tracker.getTrackedTorrents()) { if (tt.seeders() == 1 && tt.getHexInfoHash().equals(Torrent.byteArrayToHexString(torrentHash))) return true; } return false; } }; } private void waitForPeers(final int numPeers) { new WaitFor() { @Override protected boolean condition() { for (TrackedTorrent tt : tracker.getTrackedTorrents()) { if (tt.getPeers().size() == numPeers) return true; } return false; } }; } private void waitForFileInDir(final File downloadDir, final String fileName) { new WaitFor() { @Override protected boolean condition() { return new File(downloadDir, fileName).isFile(); } }; assertTrue(new File(downloadDir, fileName).isFile()); } @AfterMethod protected void tearDown() throws Exception { for (Client client : clientList) { client.stop(); } stopTracker(); tempFiles.cleanup(); } private void startTracker() throws IOException { this.tracker = new Tracker(6969); tracker.setAnnounceInterval(5); this.tracker.start(true); } private Client createAndStartClient() throws IOException, NoSuchAlgorithmException, InterruptedException { Client client = createClient(); client.start(InetAddress.getLocalHost()); return client; } private Client createClient() throws IOException, NoSuchAlgorithmException, InterruptedException { final Client client = new Client(); clientList.add(client); return client; } private SharedTorrent completeTorrent(String name) throws IOException, NoSuchAlgorithmException { File torrentFile = new File(TEST_RESOURCES + "/torrents", name); File parentFiles = new File(TEST_RESOURCES + "/parentFiles"); return SharedTorrent.fromFile(torrentFile, parentFiles, false); } private SharedTorrent incompleteTorrent(String name, File destDir) throws IOException, NoSuchAlgorithmException { File torrentFile = new File(TEST_RESOURCES + "/torrents", name); return SharedTorrent.fromFile(torrentFile, destDir, false); } private void stopTracker() { this.tracker.stop(); } private void assertFilesEqual(File f1, File f2) throws IOException { assertEquals(f1.length(), f2.length(), "Files sizes differ"); Checksum c1 = FileUtils.checksum(f1, new CRC32()); Checksum c2 = FileUtils.checksum(f2, new CRC32()); assertEquals(c1.getValue(), c2.getValue()); } }
removed one seeder from test because otherwise client can download all file from this seeder
src/test/java/com/turn/ttorrent/client/ClientTest.java
removed one seeder from test because otherwise client can download all file from this seeder
<ide><path>rc/test/java/com/turn/ttorrent/client/ClientTest.java <ide> final File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); <ide> final File badFile = tempFiles.createTempFile(piecesCount * pieceSize); <ide> <del> final Client client1 = createAndStartClient(); <ide> final Client client2 = createAndStartClient(); <ide> final File client2Dir = tempFiles.createTempDir(); <ide> final File client2File = new File(client2Dir, baseFile.getName()); <ide> FileUtils.copyFile(badFile, client2File); <ide> <ide> final Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); <del> client1.addTorrent(new SharedTorrent(torrent, baseFile.getParentFile(), false, true)); <ide> client2.addTorrent(new SharedTorrent(torrent, client2Dir, false, true)); <ide> <ide> final String baseMD5 = getFileMD5(baseFile, md5);
JavaScript
mit
72accd40fc59db5b2648f3a680f13bfa164d06e9
0
nico-hn/color-contrast-calc
"use strict"; const ColorUtils = require("./color-utils").ColorUtils; const Utils = ColorUtils; /** * Provides methods to calculate RGB colors. * An instance represents a RGB color. */ class ColorContrastCalc { /** * @param {string|Array<number, number, number>} rgb - RGB value represented as a string (hex code) or an array of numbers * @param {string} [name=null] - the value of this.name: if null, the value of this.hexCode is set to this.name instead */ constructor(rgb, name = null) { const ownClass = this.constructor; /** @property {Array<number, number, number>} rgb - RGB value repsented as an array of decimal numbers */ this.rgb = Utils.isString(rgb) ? Utils.hexCodeToDecimal(rgb) : rgb; /** @property {number} relativeLuminance - The relative luminance of the color */ this.relativeLuminance = ownClass.relativeLuminance(this.rgb); /** @property {string} name - If no name is explicitely given, the property is set to the value of this.hexCode */ this.name = name === null ? Utils.decimalToHexCode(this.rgb) : name; /** @property {string} hexCode - The RGB value in hex code notation */ this.hexCode = Utils.decimalToHexCode(this.rgb); this.freezeProperties(); } /** * @private */ static tristimulusValue(primaryColor, base = 255) { const s = primaryColor / base; if (s <= 0.03928) { return s / 12.92; } else { return Math.pow((s + 0.055) / 1.055, 2.4); } } /** * Calculate the relative luminance of a RGB color given as a string or an array of numbers * @param {string|Array<number, number, number>} rgb - RGB value represented as a string (hex code) or an array of numbers * @returns {number} Relative luminance */ static relativeLuminance(rgb = [255, 255, 255]) { if (Utils.isString(rgb)) { rgb = Utils.hexCodeToDecimal(rgb); } const [r, g, b] = rgb.map(c => this.tristimulusValue(c)); return r * 0.2126 + g * 0.7152 + b * 0.0722; } /** * Calculate the contrast ratio of given colors * @param {string|Array<number, number, number>} foreground - RGB value represented as a string (hex code) or an array of numbers * @param {string|Array<number, number, number>} background - RGB value represented as a string (hex code) or an array of numbers * @returns {number} Contrast ratio */ static contrastRatio(foreground, background) { const [l1, l2] = [foreground, background] .map(c => this.relativeLuminance(c)) .sort((f, b) => b - f); return (l1 + 0.05) / (l2 + 0.05); } /** * Returns an instance of ColorContrastCalc for a predefined color name. * @param {string} name - names are defined at https://www.w3.org/TR/SVG/types.html#ColorKeywords * @returns {ColorContrastCalc} */ static getByName(name) { return this.NAME_TO_COLOR.get(name); } /** * Returns an instance of ColorContrastCalc for a hex code * @param {string} code - RGB value in hex code * @returns {ColorContrastCalc} */ static getByHexCode(code) { const hexCode = Utils.normalizeHexCode(code); const registeredCode = this.HEX_TO_COLOR.get(hexCode); return registeredCode ? registeredCode : new ColorContrastCalc(hexCode); } /** * Returns a function to be used as a parameter of Array.prototype.sort() * @param {string} [colorOrder="rgb"] - A left side primary color has a higher sorting precedence * @param {string} [keyType="color"] - Type of keys used for sorting: "color", "hex" or "rgb" * @param {function} [keyMapper=null] - A function used to retrive key values from elements to be sorted * @returns {function} Function that compares given two colors */ static compareFunction(colorOrder = "rgb", keyType = "color", keyMapper = null) { return this.Sorter.compareFunction(colorOrder, keyType, keyMapper); } /** * Sorts colors in an array and returns the result as a new array * @param {ColorContrastCalc[]|String[]} colors - List of colors * @param {string} [colorOrder="rgb"] - A left side primary color has a higher sorting precedence * @param {function} [keyMapper=null] - A function used to retrive key values from elements to be sorted * @param {string} [mode="auto"] - If set to "hex", key values are handled as hex code strings * @returns {ColorContrastCalc[]} An array of sorted colors */ static sort(colors, colorOrder = "rgb", keyMapper = null, mode = "auto") { return this.Sorter.sort(colors, colorOrder, keyMapper, mode); } /** * Creates an instance of ColorContractCalc from an HSL value * @param {Array<number,number, number>} hsl - an array of numbers that represents an HSL value * @returns {ColorContrastCalc} An instance of ColorContrastCalc */ static newHslColor(hsl) { return this.getByHexCode(Utils.hslToHexCode(hsl)); } /** * @private */ static setup(colorKeywordsJSON) { this.loadColorKeywords(colorKeywordsJSON); this.assignColorConstants(); this.generateWebSafeColors(); Object.freeze(this); } /** * @private */ static loadColorKeywords(colorKeywordsJSON) { /** * Array of named colors defined at https://www.w3.org/TR/SVG/types.html#ColorKeywords * @property {ColorContrastCalc[]} NAMED_COLORS */ this.NAMED_COLORS = []; /** @private */ this.NAME_TO_COLOR = new Map(); /** @private */ this.HEX_TO_COLOR = new Map(); colorKeywordsJSON.forEach(color => { const [name, hex] = color; const calc = new ColorContrastCalc(hex, name); this.NAMED_COLORS.push(calc); this.NAME_TO_COLOR.set(name, calc); this.HEX_TO_COLOR.set(hex, calc); }); Object.freeze(this.NAMED_COLORS); } /** * @private */ static assignColorConstants() { /** @property {ColorContrastCalc} BLACK - an instance that represents #000000 */ this.BLACK = this.HEX_TO_COLOR.get("#000000"); /** @property {ColorContrastCalc} WHITE - an instance that represents #ffffff */ this.WHITE = this.HEX_TO_COLOR.get("#ffffff"); /** @property {ColorContrastCalc} GRAY - an instance that represents #808080 */ this.GRAY = this.NAME_TO_COLOR.get("gray"); this.prototype.BLACK = this.BLACK; this.prototype.WHITE = this.WHITE; this.prototype.GRAY = this.GRAY; } /** * @private */ static generateWebSafeColors() { /** * Array of web safe colors * @property {ColorContrastCalc[]} WEB_SAFE_COLORS */ this.WEB_SAFE_COLORS = []; for (let r = 0; r < 16; r += 3) { for (let g = 0; g < 16; g += 3) { for (let b = 0; b < 16; b += 3) { let hexCode = Utils.decimalToHexCode([r, g, b].map(c => c * 17)); let predefined = this.HEX_TO_COLOR.get(hexCode); let color = predefined ? predefined : new ColorContrastCalc(hexCode); this.WEB_SAFE_COLORS.push(color); } } } } /** * Calculate the contrast ratio against another color * @param {ColorContrastCalc|string|Array<number, number, number>} color - another instance of ColorContrastCalc or a RGB value * @returns {number} */ contrastRatioAgainst(color) { if (!(color instanceof ColorContrastCalc)) { return this.constructor.contrastRatio(this.rgb, color); } const [l1, l2] = [this.relativeLuminance, color.relativeLuminance] .sort((s, o) => o - s); return (l1 + 0.05) / (l2 + 0.05); } /** * Returns an array of named colors that satisfy a given level of contrast ratio * @param {string} [level="AA"] - A, AA or AAA * @returns {ColorContrastCalc[]} */ colorsWithSufficientContrast(level = "AA") { const ratio = this.levelToContrastRatio(level); return this.constructor.NAMED_COLORS.filter(combinedColor => { return this.contrastRatioAgainst(combinedColor) >= ratio; }); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newContrastColor(ratio, name = null) { return this.generateNewColor(Utils.ContrastCalc, ratio, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newBrightnessColor(ratio, name = null) { return this.generateNewColor(Utils.BrightnessCalc, ratio, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newInvertColor(ratio, name = null) { return this.generateNewColor(Utils.InvertCalc, ratio, name); } /** * @param {number} degree - Value in degree * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newHueRotateColor(degree, name = null) { return this.generateNewColor(Utils.HueRotateCalc, degree, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newSaturateColor(ratio, name = null) { return this.generateNewColor(Utils.SaturateCalc, ratio, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newGrayscaleColor(ratio, name = null) { return this.generateNewColor(Utils.GrayscaleCalc, ratio, name); } /** * Tries to find a color whose contrast against the base color is close to a given level. * * The returned color is gained by modifying the brightness of otherColor. * Even when a color that satisfies the level is not found, it returns a new color anyway. * @param {ColorContrastCalc} otherColor - The color before the modification of brightness * @param {string} [level="AA"] - A, AA or AAA * @returns {ColorContrastCalc} A color whose contrast against the base color is close to a specified level */ findBrightnessThreshold(otherColor, level = "AA") { const targetRatio = this.levelToContrastRatio(level); const criteria = this.brightnessThresholdCriteria(targetRatio, otherColor); const w = otherColor.calcUpperRatioLimit() / 2; const upperColor = otherColor.newBrightnessColor(w * 2); if (otherColor.isBrighterThan(this) && ! upperColor.hasSufficientContrast(this, level)) { return upperColor; } const [r, lastSufficentRatio] = this.calcBrightnessRatio(otherColor, targetRatio, criteria, w); const nearestColor = otherColor.newBrightnessColor(criteria.round(r)); if (lastSufficentRatio && nearestColor.contrastRatioAgainst(this) < targetRatio) { return otherColor.newBrightnessColor(criteria.round(lastSufficentRatio)); } return nearestColor; } /** * Tries to find a color whose contrast against the base color is close to a given level. * * The returned color is gained by modifying the lightness of otherColor. * Even when a color that satisfies the level is not found, it returns a new color anyway. * @param {ColorContrastCalc} otherColor - The color before the modification of lightness * @param {string} [level="AA"] - A, AA or AAA * @returns {ColorContrastCalc} A color whose contrast against the base color is close to a specified level */ findLightnessThreshold(otherColor, level = "AA") { const targetRatio = this.levelToContrastRatio(level); const criteria = this.brightnessThresholdCriteria(targetRatio, otherColor); const [h, s, initL] = Utils.rgbToHsl(otherColor.rgb); const [max, min] = this.shouldScanDarkerSide(otherColor) ? [initL, 0] : [100, initL]; const boundaryColor = this.lightnessBoundaryColor(max, min, level); if (boundaryColor) { return boundaryColor; } let l = (max + min) / 2; let lastSufficientLightness = null; for (let d of ColorContrastCalc.binarySearchWidth(max - min, 0.01)) { let newColor = Utils.hslToRgb([h, s, l]); let contrastRatio = this.contrastRatioAgainst(newColor); if (contrastRatio >= targetRatio) { lastSufficientLightness = l; } if (contrastRatio === targetRatio) { break; } l += criteria.incrementCondition(contrastRatio) ? d : -d; } const nearlestColor = ColorContrastCalc.newHslColor([h, s, l]); if (lastSufficientLightness && nearlestColor.contrastRatioAgainst(this) < targetRatio) { return ColorContrastCalc.newHslColor([h, s, lastSufficientLightness]); } return nearlestColor; } /** * @private */ shouldScanDarkerSide(otherColor) { if (this.isBrighterThan(otherColor) || this.isSameColor(otherColor) && this.isLightColor()) { return true; } return false; } /** * @private */ lightnessBoundaryColor(max, min, level) { if (min === 0 && ! this.hasSufficientContrast(this.BLACK, level)) { return this.BLACK; } if (max === 100 && ! this.hasSufficientContrast(this.WHITE, level)) { return this.WHITE; } return null; } /** * @param {ColorContrastCalc} otherColor * @returns {string} A, AA or AAA if the contrast ratio meets the criteria of WCAG 2.0, otherwise "-" */ contrastLevel(otherColor) { const ratio = this.contrastRatioAgainst(otherColor); if (ratio >= 7) { return "AAA"; } else if (ratio >= 4.5) { return "AA"; } else if (ratio >= 3) { return "A"; } return "-"; } /** * Checks if the contrast ratio between the base color and otherColor meets the requirement of WCAG 2.0 * @param {ColorContrastCalc} otherColor * @param {string} [level="AA"] - A, AA or AAA * @returns {boolean} */ hasSufficientContrast(otherColor, level = "AA") { const ratio = this.levelToContrastRatio(level); return this.contrastRatioAgainst(otherColor) >= ratio; } /** * Checks if the base color and otherColor have the same RGB value * @param {ColorContrastCalc} otherColor * @returns {boolean} */ isSameColor(otherColor) { return this.hexCode === otherColor.hexCode; } /** * @returns {boolean} true if each primary color of the base color is 0 or 255 */ isMaxContrast() { const limits = [0, 255]; return this.rgb.every(primaryColor => limits.includes(primaryColor)); } /** * @returns {boolean} true if the hex code of the color is #808080 */ isMinContrast() { return this.rgb.every((primaryColor, i) => { return this.GRAY.rgb[i] === primaryColor; }); } /** * Returns a string representation of the color. * When 16 is passed, it return the hex code, and when 10 is passed, it returns the value in RGB notation * Otherwise, it returns the color name or the hex code * @param {number|null} [base=16] - 16, 10 or null * @returns {string} */ toString(base = 16) { switch (base) { case 16: return this.hexCode; case 10: return `rgb(${this.rgb.join(",")})`; default: return this.name || this.hexCode; } } /** * @private */ levelToContrastRatio(level) { if (level === "A" || level === 1) { return 3.0; } else if (level === "AA" || level === 2) { return 4.5; } else if (level === "AAA" || level === 3) { return 7.0; } } /** * @private */ calcBrightnessRatio(otherColor, targetRatio, criteria, w) { let r = w; let lastSufficentRatio = null; for (let d of ColorContrastCalc.binarySearchWidth(w, 0.01)) { let newColor = otherColor.newBrightnessColor(r); let contrastRatio = newColor.contrastRatioAgainst(this); if (contrastRatio >= targetRatio) { lastSufficentRatio = r; } if (contrastRatio === targetRatio) { break; } r += criteria.incrementCondition(contrastRatio) ? d : -d; } return [r, lastSufficentRatio]; } /** * @private */ calcUpperRatioLimit() { if (this.isSameColor(this.BLACK)) { return 100; } const darkest = this.rgb .filter(c => c !== 0) .reduce((a, b) => Math.min(a, b)); return Math.ceil((255 / darkest) * 100); } /** * @private */ brightnessThresholdCriteria(targetRatio, otherColor) { const criteria = {}; if (this.isBrighterThan(otherColor) || this.hasSameLuminance(otherColor) && this.isLightColor()) { criteria.round = (r) => Math.floor(r * 10 ) / 10; criteria.incrementCondition = (contrastRatio) => contrastRatio > targetRatio; } else { criteria.round = (r) => Math.ceil(r * 10) / 10; criteria.incrementCondition = (contrastRatio) => targetRatio > contrastRatio; } return criteria; } /** * @param {ColorContrastCalc} otherColor * @returns {boolean} true if the relative luminance of the base color is greater than that of otherColor */ isBrighterThan(otherColor) { return this.relativeLuminance > otherColor.relativeLuminance; } /** * @param {ColorContrastCalc} otherColor * @returns {boolean} true if the relative luminance of the base color is equal to that of otherColor */ hasSameLuminance(otherColor) { return this.relativeLuminance === otherColor.relativeLuminance; } /** * @returns {boolean} true if the contrast ratio against white is qual to/ less than the ratio against black */ isLightColor() { return this.WHITE.contrastRatioAgainst(this) <= this.BLACK.contrastRatioAgainst(this); } /** * @private */ freezeProperties() { Object.freeze(this.rgb); Object.freeze(this.relativeLuminance); Object.freeze(this.name); Object.freeze(this.hexCode); } /** * @private */ generateNewColor(calc, ratio, name = null) { const newRgb = calc.calcRgb(this.rgb, ratio); return new ColorContrastCalc(newRgb, name); } } ColorContrastCalc.binarySearchWidth = function*(initWidth, min) { let i = 1; let d = initWidth / Math.pow(2, i); while (d > min) { yield d; i++; d = initWidth / Math.pow(2, i); } }; (function() { class Sorter { static sort(colors, colorOrder = "rgb", keyMapper = null, mode = "auto") { const keyType = this.guessKeyType(mode, colors[0], keyMapper); const compare = this.compareFunction(colorOrder, keyType, keyMapper); return colors.slice().sort(compare); } static compareFunction(colorOrder = "rgb", keyType = this.KEY_TYPE.COLOR, keyMapper = null) { let compare = null; if (keyType === this.KEY_TYPE.HEX) { compare = this.compareHexFunction(colorOrder); } else if (keyType === this.KEY_TYPE.RGB) { compare = this.compareRgbFunction(colorOrder); } else { compare = this.compareColorFunction(colorOrder); } return this.composeFunction(compare, keyMapper); } static composeFunction(compareFunc, keyMapper = null) { if (! keyMapper) { return compareFunc; } return function(color1, color2) { return compareFunc(keyMapper(color1), keyMapper(color2)); }; } static guessKeyType(mode, color, keyMapper) { if (mode === this.KEY_TYPE.HEX || mode === "auto" && this.isStringKey(color, keyMapper)) { return this.KEY_TYPE.HEX; } else if (mode === this.KEY_TYPE.RGB) { return this.KEY_TYPE.RGB; } else { return this.KEY_TYPE.COLOR; } } static isStringKey(color, keyMapper) { const keyType = keyMapper ? keyMapper(color) : color; return Utils.isString(keyType); } static compareColorFunction(colorOrder = "rgb") { const rgbPos = this.primaryColorPos(colorOrder); const compFuncs = this.chooseCompFunc(colorOrder); return function(color1, color2) { return Sorter.compareRgbVal(color1.rgb, color2.rgb, rgbPos, compFuncs); }; } static compareRgbFunction(colorOrder = "rgb") { const rgbPos = this.primaryColorPos(colorOrder); const compFuncs = this.chooseCompFunc(colorOrder); return function(rgb1, rgb2) { return Sorter.compareRgbVal(rgb1, rgb2, rgbPos, compFuncs); }; } static compareHexFunction(colorOrder = "rgb") { const rgbPos = this.primaryColorPos(colorOrder); const compFuncs = this.chooseCompFunc(colorOrder); const rgbCache = new Map(); return function(hex1, hex2) { return Sorter.compareHexVal(hex1, hex2, rgbPos, compFuncs, rgbCache); }; } static compareRgbVal(rgb1, rgb2, rgbPos = [0, 1, 2], compFuncs = this.defaultCompFuncs) { for (let i of rgbPos) { const result = compFuncs[i](rgb1[i], rgb2[i]); if (result !== 0) { return result; } } return 0; } static compareHexVal(hex1, hex2, rgbPos, compFuncs, rgbCache) { const rgb1 = rgbCache.get(hex1) || Utils.hexCodeToDecimal(hex1); const rgb2 = rgbCache.get(hex2) || Utils.hexCodeToDecimal(hex2); return this.compareRgbVal(rgb1, rgb2, rgbPos, compFuncs); } static primaryColorPos(colorOrder) { return colorOrder.toLowerCase().split("").map((primary) => { return this.RGB_IDENTIFIERS.indexOf(primary); }); } static ascendComp(primaryColor1, primaryColor2) { return primaryColor1 - primaryColor2; } static descendComp(primaryColor1, primaryColor2) { return primaryColor2 - primaryColor1; } static chooseCompFunc(colorOrder) { const primaryColors = colorOrder.split("") .sort(this.caseInsensitiveComp).reverse(); return primaryColors.map(primary => { if (Utils.isUpperCase(primary)) { return this.descendComp; } return this.ascendComp; }); } static caseInsensitiveComp(str1, str2) { const lStr1 = str1.toLowerCase(); const lStr2 = str2.toLowerCase(); if (lStr1 < lStr2) { return -1; } if (lStr1 > lStr2) { return 1; } return 0; } static setup() { this.RGB_IDENTIFIERS = ["r", "g", "b"]; this.defaultCompFuncs = [ Sorter.ascendComp, Sorter.ascendComp, Sorter.ascendComp ]; this.KEY_TYPE = { RGB: "rgb", HEX: "hex", COLOR: "color" }; } } Sorter.setup(); ColorContrastCalc.Sorter = Sorter; })(); ColorContrastCalc.setup(require("./color-keywords.json")); module.exports.ColorUtils = ColorUtils; module.exports.ColorContrastCalc = ColorContrastCalc;
lib/color-contrast-calc.js
"use strict"; const ColorUtils = require("./color-utils").ColorUtils; const Utils = ColorUtils; /** * Provides methods to calculate RGB colors. * An instance represents a RGB color. */ class ColorContrastCalc { /** * @param {string|Array<number, number, number>} rgb - RGB value represented as a string (hex code) or an array of numbers * @param {string} [name=null] - the value of this.name: if null, the value of this.hexCode is set to this.name instead */ constructor(rgb, name = null) { const ownClass = this.constructor; /** @property {Array<number, number, number>} rgb - RGB value repsented as an array of decimal numbers */ this.rgb = Utils.isString(rgb) ? Utils.hexCodeToDecimal(rgb) : rgb; /** @property {number} relativeLuminance - The relative luminance of the color */ this.relativeLuminance = ownClass.relativeLuminance(this.rgb); /** @property {string} name - If no name is explicitely given, the property is set to the value of this.hexCode */ this.name = name === null ? Utils.decimalToHexCode(this.rgb) : name; /** @property {string} hexCode - The RGB value in hex code notation */ this.hexCode = Utils.decimalToHexCode(this.rgb); this.freezeProperties(); } /** * @private */ static tristimulusValue(primaryColor, base = 255) { const s = primaryColor / base; if (s <= 0.03928) { return s / 12.92; } else { return Math.pow((s + 0.055) / 1.055, 2.4); } } /** * Calculate the relative luminance of a RGB color given as a string or an array of numbers * @param {string|Array<number, number, number>} rgb - RGB value represented as a string (hex code) or an array of numbers * @returns {number} Relative luminance */ static relativeLuminance(rgb = [255, 255, 255]) { if (Utils.isString(rgb)) { rgb = Utils.hexCodeToDecimal(rgb); } const [r, g, b] = rgb.map(c => this.tristimulusValue(c)); return r * 0.2126 + g * 0.7152 + b * 0.0722; } /** * Calculate the contrast ratio of given colors * @param {string|Array<number, number, number>} foreground - RGB value represented as a string (hex code) or an array of numbers * @param {string|Array<number, number, number>} background - RGB value represented as a string (hex code) or an array of numbers * @returns {number} Contrast ratio */ static contrastRatio(foreground, background) { const [l1, l2] = [foreground, background] .map(c => this.relativeLuminance(c)) .sort((f, b) => b - f); return (l1 + 0.05) / (l2 + 0.05); } /** * Returns an instance of ColorContrastCalc for a predefined color name. * @param {string} name - names are defined at https://www.w3.org/TR/SVG/types.html#ColorKeywords * @returns {ColorContrastCalc} */ static getByName(name) { return this.NAME_TO_COLOR.get(name); } /** * Returns an instance of ColorContrastCalc for a hex code * @param {string} code - RGB value in hex code * @returns {ColorContrastCalc} */ static getByHexCode(code) { const hexCode = Utils.normalizeHexCode(code); const registeredCode = this.HEX_TO_COLOR.get(hexCode); return registeredCode ? registeredCode : new ColorContrastCalc(hexCode); } /** * Returns a function to be used as a parameter of Array.prototype.sort() * @param {string} [colorOrder="rgb"] - A left side primary color has a higher sorting precedence * @param {string} [keyType="color"] - Type of keys used for sorting: "color", "hex" or "rgb" * @param {function} [keyMapper=null] - A function used to retrive key values from elements to be sorted * @returns {function} Function that compares given two colors */ static compareFunction(colorOrder = "rgb", keyType = "color", keyMapper = null) { return this.Sorter.compareFunction(colorOrder, keyType, keyMapper); } /** * Sorts colors in an array and returns the result as a new array * @param {ColorContrastCalc[]|String[]} colors - List of colors * @param {string} [colorOrder="rgb"] - A left side primary color has a higher sorting precedence * @param {function} [keyMapper=null] - A function used to retrive key values from elements to be sorted * @param {string} [mode="auto"] - If set to "hex", key values are handled as hex code strings * @returns {ColorContrastCalc[]} An array of sorted colors */ static sort(colors, colorOrder = "rgb", keyMapper = null, mode = "auto") { return this.Sorter.sort(colors, colorOrder, keyMapper, mode); } /** * Creates an instance of ColorContractCalc from an HSL value * @param {Array<number,number, number>} hsl - an array of numbers that represents an HSL value * @returns {ColorContrastCalc} An instance of ColorContrastCalc */ static newHslColor(hsl) { return this.getByHexCode(Utils.hslToHexCode(hsl)); } /** * @private */ static setup(colorKeywordsJSON) { this.loadColorKeywords(colorKeywordsJSON); this.assignColorConstants(); this.generateWebSafeColors(); } /** * @private */ static loadColorKeywords(colorKeywordsJSON) { /** * Array of named colors defined at https://www.w3.org/TR/SVG/types.html#ColorKeywords * @property {ColorContrastCalc[]} NAMED_COLORS */ this.NAMED_COLORS = []; /** @private */ this.NAME_TO_COLOR = new Map(); /** @private */ this.HEX_TO_COLOR = new Map(); colorKeywordsJSON.forEach(color => { const [name, hex] = color; const calc = new ColorContrastCalc(hex, name); this.NAMED_COLORS.push(calc); this.NAME_TO_COLOR.set(name, calc); this.HEX_TO_COLOR.set(hex, calc); }); Object.freeze(this.NAMED_COLORS); } /** * @private */ static assignColorConstants() { /** @property {ColorContrastCalc} BLACK - an instance that represents #000000 */ this.BLACK = this.HEX_TO_COLOR.get("#000000"); /** @property {ColorContrastCalc} WHITE - an instance that represents #ffffff */ this.WHITE = this.HEX_TO_COLOR.get("#ffffff"); /** @property {ColorContrastCalc} GRAY - an instance that represents #808080 */ this.GRAY = this.NAME_TO_COLOR.get("gray"); this.prototype.BLACK = this.BLACK; this.prototype.WHITE = this.WHITE; this.prototype.GRAY = this.GRAY; Object.freeze(this.BLACK); Object.freeze(this.WHITE); Object.freeze(this.GRAY); Object.freeze(this.prototype.BLACK); Object.freeze(this.prototype.WHITE); Object.freeze(this.prototype.GRAY); } /** * @private */ static generateWebSafeColors() { /** * Array of web safe colors * @property {ColorContrastCalc[]} WEB_SAFE_COLORS */ this.WEB_SAFE_COLORS = []; for (let r = 0; r < 16; r += 3) { for (let g = 0; g < 16; g += 3) { for (let b = 0; b < 16; b += 3) { let hexCode = Utils.decimalToHexCode([r, g, b].map(c => c * 17)); let predefined = this.HEX_TO_COLOR.get(hexCode); let color = predefined ? predefined : new ColorContrastCalc(hexCode); this.WEB_SAFE_COLORS.push(color); } } } } /** * Calculate the contrast ratio against another color * @param {ColorContrastCalc|string|Array<number, number, number>} color - another instance of ColorContrastCalc or a RGB value * @returns {number} */ contrastRatioAgainst(color) { if (!(color instanceof ColorContrastCalc)) { return this.constructor.contrastRatio(this.rgb, color); } const [l1, l2] = [this.relativeLuminance, color.relativeLuminance] .sort((s, o) => o - s); return (l1 + 0.05) / (l2 + 0.05); } /** * Returns an array of named colors that satisfy a given level of contrast ratio * @param {string} [level="AA"] - A, AA or AAA * @returns {ColorContrastCalc[]} */ colorsWithSufficientContrast(level = "AA") { const ratio = this.levelToContrastRatio(level); return this.constructor.NAMED_COLORS.filter(combinedColor => { return this.contrastRatioAgainst(combinedColor) >= ratio; }); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newContrastColor(ratio, name = null) { return this.generateNewColor(Utils.ContrastCalc, ratio, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newBrightnessColor(ratio, name = null) { return this.generateNewColor(Utils.BrightnessCalc, ratio, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newInvertColor(ratio, name = null) { return this.generateNewColor(Utils.InvertCalc, ratio, name); } /** * @param {number} degree - Value in degree * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newHueRotateColor(degree, name = null) { return this.generateNewColor(Utils.HueRotateCalc, degree, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newSaturateColor(ratio, name = null) { return this.generateNewColor(Utils.SaturateCalc, ratio, name); } /** * @param {number} ratio - Value in percent * @param {string} [name=null] - Name of color * @returns {ColorContrastCalc} */ newGrayscaleColor(ratio, name = null) { return this.generateNewColor(Utils.GrayscaleCalc, ratio, name); } /** * Tries to find a color whose contrast against the base color is close to a given level. * * The returned color is gained by modifying the brightness of otherColor. * Even when a color that satisfies the level is not found, it returns a new color anyway. * @param {ColorContrastCalc} otherColor - The color before the modification of brightness * @param {string} [level="AA"] - A, AA or AAA * @returns {ColorContrastCalc} A color whose contrast against the base color is close to a specified level */ findBrightnessThreshold(otherColor, level = "AA") { const targetRatio = this.levelToContrastRatio(level); const criteria = this.brightnessThresholdCriteria(targetRatio, otherColor); const w = otherColor.calcUpperRatioLimit() / 2; const upperColor = otherColor.newBrightnessColor(w * 2); if (otherColor.isBrighterThan(this) && ! upperColor.hasSufficientContrast(this, level)) { return upperColor; } const [r, lastSufficentRatio] = this.calcBrightnessRatio(otherColor, targetRatio, criteria, w); const nearestColor = otherColor.newBrightnessColor(criteria.round(r)); if (lastSufficentRatio && nearestColor.contrastRatioAgainst(this) < targetRatio) { return otherColor.newBrightnessColor(criteria.round(lastSufficentRatio)); } return nearestColor; } /** * Tries to find a color whose contrast against the base color is close to a given level. * * The returned color is gained by modifying the lightness of otherColor. * Even when a color that satisfies the level is not found, it returns a new color anyway. * @param {ColorContrastCalc} otherColor - The color before the modification of lightness * @param {string} [level="AA"] - A, AA or AAA * @returns {ColorContrastCalc} A color whose contrast against the base color is close to a specified level */ findLightnessThreshold(otherColor, level = "AA") { const targetRatio = this.levelToContrastRatio(level); const criteria = this.brightnessThresholdCriteria(targetRatio, otherColor); const [h, s, initL] = Utils.rgbToHsl(otherColor.rgb); const [max, min] = this.shouldScanDarkerSide(otherColor) ? [initL, 0] : [100, initL]; const boundaryColor = this.lightnessBoundaryColor(max, min, level); if (boundaryColor) { return boundaryColor; } let l = (max + min) / 2; let lastSufficientLightness = null; for (let d of ColorContrastCalc.binarySearchWidth(max - min, 0.01)) { let newColor = Utils.hslToRgb([h, s, l]); let contrastRatio = this.contrastRatioAgainst(newColor); if (contrastRatio >= targetRatio) { lastSufficientLightness = l; } if (contrastRatio === targetRatio) { break; } l += criteria.incrementCondition(contrastRatio) ? d : -d; } const nearlestColor = ColorContrastCalc.newHslColor([h, s, l]); if (lastSufficientLightness && nearlestColor.contrastRatioAgainst(this) < targetRatio) { return ColorContrastCalc.newHslColor([h, s, lastSufficientLightness]); } return nearlestColor; } /** * @private */ shouldScanDarkerSide(otherColor) { if (this.isBrighterThan(otherColor) || this.isSameColor(otherColor) && this.isLightColor()) { return true; } return false; } /** * @private */ lightnessBoundaryColor(max, min, level) { if (min === 0 && ! this.hasSufficientContrast(this.BLACK, level)) { return this.BLACK; } if (max === 100 && ! this.hasSufficientContrast(this.WHITE, level)) { return this.WHITE; } return null; } /** * @param {ColorContrastCalc} otherColor * @returns {string} A, AA or AAA if the contrast ratio meets the criteria of WCAG 2.0, otherwise "-" */ contrastLevel(otherColor) { const ratio = this.contrastRatioAgainst(otherColor); if (ratio >= 7) { return "AAA"; } else if (ratio >= 4.5) { return "AA"; } else if (ratio >= 3) { return "A"; } return "-"; } /** * Checks if the contrast ratio between the base color and otherColor meets the requirement of WCAG 2.0 * @param {ColorContrastCalc} otherColor * @param {string} [level="AA"] - A, AA or AAA * @returns {boolean} */ hasSufficientContrast(otherColor, level = "AA") { const ratio = this.levelToContrastRatio(level); return this.contrastRatioAgainst(otherColor) >= ratio; } /** * Checks if the base color and otherColor have the same RGB value * @param {ColorContrastCalc} otherColor * @returns {boolean} */ isSameColor(otherColor) { return this.hexCode === otherColor.hexCode; } /** * @returns {boolean} true if each primary color of the base color is 0 or 255 */ isMaxContrast() { const limits = [0, 255]; return this.rgb.every(primaryColor => limits.includes(primaryColor)); } /** * @returns {boolean} true if the hex code of the color is #808080 */ isMinContrast() { return this.rgb.every((primaryColor, i) => { return this.GRAY.rgb[i] === primaryColor; }); } /** * Returns a string representation of the color. * When 16 is passed, it return the hex code, and when 10 is passed, it returns the value in RGB notation * Otherwise, it returns the color name or the hex code * @param {number|null} [base=16] - 16, 10 or null * @returns {string} */ toString(base = 16) { switch (base) { case 16: return this.hexCode; case 10: return `rgb(${this.rgb.join(",")})`; default: return this.name || this.hexCode; } } /** * @private */ levelToContrastRatio(level) { if (level === "A" || level === 1) { return 3.0; } else if (level === "AA" || level === 2) { return 4.5; } else if (level === "AAA" || level === 3) { return 7.0; } } /** * @private */ calcBrightnessRatio(otherColor, targetRatio, criteria, w) { let r = w; let lastSufficentRatio = null; for (let d of ColorContrastCalc.binarySearchWidth(w, 0.01)) { let newColor = otherColor.newBrightnessColor(r); let contrastRatio = newColor.contrastRatioAgainst(this); if (contrastRatio >= targetRatio) { lastSufficentRatio = r; } if (contrastRatio === targetRatio) { break; } r += criteria.incrementCondition(contrastRatio) ? d : -d; } return [r, lastSufficentRatio]; } /** * @private */ calcUpperRatioLimit() { if (this.isSameColor(this.BLACK)) { return 100; } const darkest = this.rgb .filter(c => c !== 0) .reduce((a, b) => Math.min(a, b)); return Math.ceil((255 / darkest) * 100); } /** * @private */ brightnessThresholdCriteria(targetRatio, otherColor) { const criteria = {}; if (this.isBrighterThan(otherColor) || this.hasSameLuminance(otherColor) && this.isLightColor()) { criteria.round = (r) => Math.floor(r * 10 ) / 10; criteria.incrementCondition = (contrastRatio) => contrastRatio > targetRatio; } else { criteria.round = (r) => Math.ceil(r * 10) / 10; criteria.incrementCondition = (contrastRatio) => targetRatio > contrastRatio; } return criteria; } /** * @param {ColorContrastCalc} otherColor * @returns {boolean} true if the relative luminance of the base color is greater than that of otherColor */ isBrighterThan(otherColor) { return this.relativeLuminance > otherColor.relativeLuminance; } /** * @param {ColorContrastCalc} otherColor * @returns {boolean} true if the relative luminance of the base color is equal to that of otherColor */ hasSameLuminance(otherColor) { return this.relativeLuminance === otherColor.relativeLuminance; } /** * @returns {boolean} true if the contrast ratio against white is qual to/ less than the ratio against black */ isLightColor() { return this.WHITE.contrastRatioAgainst(this) <= this.BLACK.contrastRatioAgainst(this); } /** * @private */ freezeProperties() { Object.freeze(this.rgb); Object.freeze(this.relativeLuminance); Object.freeze(this.name); Object.freeze(this.hexCode); } /** * @private */ generateNewColor(calc, ratio, name = null) { const newRgb = calc.calcRgb(this.rgb, ratio); return new ColorContrastCalc(newRgb, name); } } ColorContrastCalc.binarySearchWidth = function*(initWidth, min) { let i = 1; let d = initWidth / Math.pow(2, i); while (d > min) { yield d; i++; d = initWidth / Math.pow(2, i); } }; (function() { class Sorter { static sort(colors, colorOrder = "rgb", keyMapper = null, mode = "auto") { const keyType = this.guessKeyType(mode, colors[0], keyMapper); const compare = this.compareFunction(colorOrder, keyType, keyMapper); return colors.slice().sort(compare); } static compareFunction(colorOrder = "rgb", keyType = this.KEY_TYPE.COLOR, keyMapper = null) { let compare = null; if (keyType === this.KEY_TYPE.HEX) { compare = this.compareHexFunction(colorOrder); } else if (keyType === this.KEY_TYPE.RGB) { compare = this.compareRgbFunction(colorOrder); } else { compare = this.compareColorFunction(colorOrder); } return this.composeFunction(compare, keyMapper); } static composeFunction(compareFunc, keyMapper = null) { if (! keyMapper) { return compareFunc; } return function(color1, color2) { return compareFunc(keyMapper(color1), keyMapper(color2)); }; } static guessKeyType(mode, color, keyMapper) { if (mode === this.KEY_TYPE.HEX || mode === "auto" && this.isStringKey(color, keyMapper)) { return this.KEY_TYPE.HEX; } else if (mode === this.KEY_TYPE.RGB) { return this.KEY_TYPE.RGB; } else { return this.KEY_TYPE.COLOR; } } static isStringKey(color, keyMapper) { const keyType = keyMapper ? keyMapper(color) : color; return Utils.isString(keyType); } static compareColorFunction(colorOrder = "rgb") { const rgbPos = this.primaryColorPos(colorOrder); const compFuncs = this.chooseCompFunc(colorOrder); return function(color1, color2) { return Sorter.compareRgbVal(color1.rgb, color2.rgb, rgbPos, compFuncs); }; } static compareRgbFunction(colorOrder = "rgb") { const rgbPos = this.primaryColorPos(colorOrder); const compFuncs = this.chooseCompFunc(colorOrder); return function(rgb1, rgb2) { return Sorter.compareRgbVal(rgb1, rgb2, rgbPos, compFuncs); }; } static compareHexFunction(colorOrder = "rgb") { const rgbPos = this.primaryColorPos(colorOrder); const compFuncs = this.chooseCompFunc(colorOrder); const rgbCache = new Map(); return function(hex1, hex2) { return Sorter.compareHexVal(hex1, hex2, rgbPos, compFuncs, rgbCache); }; } static compareRgbVal(rgb1, rgb2, rgbPos = [0, 1, 2], compFuncs = this.defaultCompFuncs) { for (let i of rgbPos) { const result = compFuncs[i](rgb1[i], rgb2[i]); if (result !== 0) { return result; } } return 0; } static compareHexVal(hex1, hex2, rgbPos, compFuncs, rgbCache) { const rgb1 = rgbCache.get(hex1) || Utils.hexCodeToDecimal(hex1); const rgb2 = rgbCache.get(hex2) || Utils.hexCodeToDecimal(hex2); return this.compareRgbVal(rgb1, rgb2, rgbPos, compFuncs); } static primaryColorPos(colorOrder) { return colorOrder.toLowerCase().split("").map((primary) => { return this.RGB_IDENTIFIERS.indexOf(primary); }); } static ascendComp(primaryColor1, primaryColor2) { return primaryColor1 - primaryColor2; } static descendComp(primaryColor1, primaryColor2) { return primaryColor2 - primaryColor1; } static chooseCompFunc(colorOrder) { const primaryColors = colorOrder.split("") .sort(this.caseInsensitiveComp).reverse(); return primaryColors.map(primary => { if (Utils.isUpperCase(primary)) { return this.descendComp; } return this.ascendComp; }); } static caseInsensitiveComp(str1, str2) { const lStr1 = str1.toLowerCase(); const lStr2 = str2.toLowerCase(); if (lStr1 < lStr2) { return -1; } if (lStr1 > lStr2) { return 1; } return 0; } static setup() { this.RGB_IDENTIFIERS = ["r", "g", "b"]; this.defaultCompFuncs = [ Sorter.ascendComp, Sorter.ascendComp, Sorter.ascendComp ]; this.KEY_TYPE = { RGB: "rgb", HEX: "hex", COLOR: "color" }; } } Sorter.setup(); ColorContrastCalc.Sorter = Sorter; })(); ColorContrastCalc.setup(require("./color-keywords.json")); module.exports.ColorUtils = ColorUtils; module.exports.ColorContrastCalc = ColorContrastCalc;
freeze ColorContrastCalc
lib/color-contrast-calc.js
freeze ColorContrastCalc
<ide><path>ib/color-contrast-calc.js <ide> this.loadColorKeywords(colorKeywordsJSON); <ide> this.assignColorConstants(); <ide> this.generateWebSafeColors(); <add> Object.freeze(this); <ide> } <ide> <ide> /** <ide> this.prototype.BLACK = this.BLACK; <ide> this.prototype.WHITE = this.WHITE; <ide> this.prototype.GRAY = this.GRAY; <del> Object.freeze(this.BLACK); <del> Object.freeze(this.WHITE); <del> Object.freeze(this.GRAY); <del> Object.freeze(this.prototype.BLACK); <del> Object.freeze(this.prototype.WHITE); <del> Object.freeze(this.prototype.GRAY); <ide> } <ide> <ide> /**
Java
apache-2.0
b7018f6bf3761cdf6966c9faef52c4dfae913be8
0
mikeb01/Aeron,mikeb01/Aeron,mikeb01/Aeron,mikeb01/Aeron
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.samples; import io.aeron.Aeron; import org.agrona.concurrent.status.CountersReader; import java.io.PrintStream; import java.util.*; import static io.aeron.driver.status.PublisherLimit.PUBLISHER_LIMIT_TYPE_ID; import static io.aeron.driver.status.PublisherPos.PUBLISHER_POS_TYPE_ID; import static io.aeron.driver.status.ReceiverPos.RECEIVER_POS_TYPE_ID; import static io.aeron.driver.status.SenderLimit.SENDER_LIMIT_TYPE_ID; import static io.aeron.driver.status.StreamCounter.*; /** * Tool for taking a snapshot of Aeron streams and relevant position counters. * <p> * Each stream managed by the {@link io.aeron.driver.MediaDriver} will be sampled and a line of text * output per stream with each of the position counters for that stream. * <p> * Each counter has the format: * {@code <label-name>:<registration-id>:<position value>} */ public final class StreamStat { private static final Comparator<StreamCompositeKey> LINES_COMPARATOR = Comparator.comparingLong(StreamCompositeKey::sessionId) .thenComparingInt(StreamCompositeKey::streamId) .thenComparing(StreamCompositeKey::channel); private final CountersReader counters; /** * Main method for launching the process. * * @param args passed to the process. */ public static void main(final String[] args) { final CountersReader counters = SamplesUtil.mapCounters(); final StreamStat streamStat = new StreamStat(counters); streamStat.print(System.out); } /** * Construct by using a {@link CountersReader} which can be obtained from {@link Aeron#countersReader()}. * * @param counters to read for tracking positions. */ public StreamStat(final CountersReader counters) { this.counters = counters; } /** * Take a snapshot of all the counters and group them by streams. * * @return a snapshot of all the counters and group them by streams. */ public Map<StreamCompositeKey, List<StreamPosition>> snapshot() { final Map<StreamCompositeKey, List<StreamPosition>> streams = new TreeMap<>(LINES_COMPARATOR); counters.forEach( (counterId, typeId, keyBuffer, label) -> { if ((typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID) || typeId == SENDER_LIMIT_TYPE_ID || typeId == PUBLISHER_POS_TYPE_ID) { final StreamCompositeKey key = new StreamCompositeKey( keyBuffer.getInt(SESSION_ID_OFFSET), keyBuffer.getInt(STREAM_ID_OFFSET), keyBuffer.getStringAscii(CHANNEL_OFFSET)); final StreamPosition position = new StreamPosition( keyBuffer.getLong(REGISTRATION_ID_OFFSET), counters.getCounterValue(counterId), typeId); streams.computeIfAbsent(key, (ignore) -> new ArrayList<>()).add(position); } }); return streams; } /** * Print a snapshot of the stream positions to a {@link PrintStream}. * <p> * Each stream will be printed on its own line. * * @param out to which the stream snapshot will be written. * @return the number of streams printed. */ public int print(final PrintStream out) { final Map<StreamCompositeKey, List<StreamPosition>> streams = snapshot(); final StringBuilder builder = new StringBuilder(); for (final Map.Entry<StreamCompositeKey, List<StreamPosition>> entry : streams.entrySet()) { builder.setLength(0); final StreamCompositeKey key = entry.getKey(); builder .append("sessionId=").append(key.sessionId()) .append(" streamId=").append(key.streamId()) .append(" channel=").append(key.channel()) .append(" :"); for (final StreamPosition streamPosition : entry.getValue()) { builder .append(' ') .append(labelName(streamPosition.typeId())) .append(':').append(streamPosition.id()) .append(':').append(streamPosition.value()); } out.println(builder); } return streams.size(); } /** * Composite key which identifies an Aeron stream of messages. */ public static final class StreamCompositeKey { private final int sessionId; private final int streamId; private final String channel; /** * Construct a new key representing a unique stream. * * @param sessionId to identify the stream. * @param streamId within a channel. * @param channel as a URI. */ public StreamCompositeKey(final int sessionId, final int streamId, final String channel) { Objects.requireNonNull(channel, "Channel cannot be null"); this.sessionId = sessionId; this.streamId = streamId; this.channel = channel; } /** * The session id of the stream. * * @return session id of the stream. */ public int sessionId() { return sessionId; } /** * The stream id within a channel. * * @return stream id within a channel. */ public int streamId() { return streamId; } /** * The channel as a URI. * * @return channel as a URI. */ public String channel() { return channel; } /** * {@inheritDoc} */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof StreamCompositeKey)) { return false; } final StreamCompositeKey that = (StreamCompositeKey)o; return this.sessionId == that.sessionId && this.streamId == that.streamId && this.channel.equals(that.channel); } /** * {@inheritDoc} */ public int hashCode() { int result = sessionId; result = 31 * result + streamId; result = 31 * result + channel.hashCode(); return result; } /** * {@inheritDoc} */ public String toString() { return "StreamCompositeKey{" + "sessionId=" + sessionId + ", streamId=" + streamId + ", channel='" + channel + '\'' + '}'; } } /** * Represents a position within a particular stream of messages. */ public static final class StreamPosition { private final long id; private final long value; private final int typeId; /** * Stream position representation. * * @param id of the registered entity. * @param value of the position. * @param typeId of the counter. */ public StreamPosition(final long id, final long value, final int typeId) { this.id = id; this.value = value; this.typeId = typeId; } /** * The identifier for the registered entity, such as publication or subscription, to which the counter relates. * * @return the identifier for the registered entity to which the counter relates. */ public long id() { return id; } /** * The value of the counter. * * @return the value of the counter. */ public long value() { return value; } /** * The type category of the counter for the stream position. * * @return the type category of the counter for the stream position. */ public int typeId() { return typeId; } /** * {@inheritDoc} */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof StreamPosition)) { return false; } final StreamPosition that = (StreamPosition)o; return this.id == that.id && this.value == that.value && this.typeId == that.typeId; } /** * {@inheritDoc} */ public int hashCode() { int result = (int)(id ^ (id >>> 32)); result = 31 * result + (int)(value ^ (value >>> 32)); result = 31 * result + typeId; return result; } /** * {@inheritDoc} */ public String toString() { return "StreamPosition{" + "id=" + id + ", value=" + value + ", typeId=" + typeId + '}'; } } }
aeron-samples/src/main/java/io/aeron/samples/StreamStat.java
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.samples; import io.aeron.Aeron; import org.agrona.concurrent.status.CountersReader; import java.io.PrintStream; import java.util.*; import static io.aeron.driver.status.PublisherLimit.PUBLISHER_LIMIT_TYPE_ID; import static io.aeron.driver.status.PublisherPos.PUBLISHER_POS_TYPE_ID; import static io.aeron.driver.status.ReceiverPos.RECEIVER_POS_TYPE_ID; import static io.aeron.driver.status.SenderLimit.SENDER_LIMIT_TYPE_ID; import static io.aeron.driver.status.StreamCounter.*; /** * Tool for taking a snapshot of Aeron streams and relevant position counters. * <p> * Each stream managed by the {@link io.aeron.driver.MediaDriver} will be sampled and a line of text * output per stream with each of the position counters for that stream. * <p> * Each counter has the format: * {@code <label-name>:<registration-id>:<position value>} */ public final class StreamStat { private final CountersReader counters; /** * Main method for launching the process. * * @param args passed to the process. */ public static void main(final String[] args) { final CountersReader counters = SamplesUtil.mapCounters(); final StreamStat streamStat = new StreamStat(counters); streamStat.print(System.out); } /** * Construct by using a {@link CountersReader} which can be obtained from {@link Aeron#countersReader()}. * * @param counters to read for tracking positions. */ public StreamStat(final CountersReader counters) { this.counters = counters; } /** * Take a snapshot of all the counters and group them by streams. * * @return a snapshot of all the counters and group them by streams. */ public Map<StreamCompositeKey, List<StreamPosition>> snapshot() { final Map<StreamCompositeKey, List<StreamPosition>> streams = new HashMap<>(); counters.forEach( (counterId, typeId, keyBuffer, label) -> { if ((typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID) || typeId == SENDER_LIMIT_TYPE_ID || typeId == PUBLISHER_POS_TYPE_ID) { final StreamCompositeKey key = new StreamCompositeKey( keyBuffer.getInt(SESSION_ID_OFFSET), keyBuffer.getInt(STREAM_ID_OFFSET), keyBuffer.getStringAscii(CHANNEL_OFFSET)); final StreamPosition position = new StreamPosition( keyBuffer.getLong(REGISTRATION_ID_OFFSET), counters.getCounterValue(counterId), typeId); streams.computeIfAbsent(key, (ignore) -> new ArrayList<>()).add(position); } }); return streams; } /** * Print a snapshot of the stream positions to a {@link PrintStream}. * <p> * Each stream will be printed on its own line. * * @param out to which the stream snapshot will be written. * @return the number of streams printed. */ public int print(final PrintStream out) { final Map<StreamCompositeKey, List<StreamPosition>> streams = snapshot(); final StringBuilder builder = new StringBuilder(); for (final Map.Entry<StreamCompositeKey, List<StreamPosition>> entry : streams.entrySet()) { builder.setLength(0); final StreamCompositeKey key = entry.getKey(); builder .append("sessionId=").append(key.sessionId()) .append(" streamId=").append(key.streamId()) .append(" channel=").append(key.channel()) .append(" :"); for (final StreamPosition streamPosition : entry.getValue()) { builder .append(' ') .append(labelName(streamPosition.typeId())) .append(':').append(streamPosition.id()) .append(':').append(streamPosition.value()); } out.println(builder); } return streams.size(); } /** * Composite key which identifies an Aeron stream of messages. */ public static final class StreamCompositeKey { private final int sessionId; private final int streamId; private final String channel; /** * Construct a new key representing a unique stream. * * @param sessionId to identify the stream. * @param streamId within a channel. * @param channel as a URI. */ public StreamCompositeKey(final int sessionId, final int streamId, final String channel) { Objects.requireNonNull(channel, "Channel cannot be null"); this.sessionId = sessionId; this.streamId = streamId; this.channel = channel; } /** * The session id of the stream. * * @return session id of the stream. */ public int sessionId() { return sessionId; } /** * The stream id within a channel. * * @return stream id within a channel. */ public int streamId() { return streamId; } /** * The channel as a URI. * * @return channel as a URI. */ public String channel() { return channel; } /** * {@inheritDoc} */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof StreamCompositeKey)) { return false; } final StreamCompositeKey that = (StreamCompositeKey)o; return this.sessionId == that.sessionId && this.streamId == that.streamId && this.channel.equals(that.channel); } /** * {@inheritDoc} */ public int hashCode() { int result = sessionId; result = 31 * result + streamId; result = 31 * result + channel.hashCode(); return result; } /** * {@inheritDoc} */ public String toString() { return "StreamCompositeKey{" + "sessionId=" + sessionId + ", streamId=" + streamId + ", channel='" + channel + '\'' + '}'; } } /** * Represents a position within a particular stream of messages. */ public static final class StreamPosition { private final long id; private final long value; private final int typeId; /** * Stream position representation. * * @param id of the registered entity. * @param value of the position. * @param typeId of the counter. */ public StreamPosition(final long id, final long value, final int typeId) { this.id = id; this.value = value; this.typeId = typeId; } /** * The identifier for the registered entity, such as publication or subscription, to which the counter relates. * * @return the identifier for the registered entity to which the counter relates. */ public long id() { return id; } /** * The value of the counter. * * @return the value of the counter. */ public long value() { return value; } /** * The type category of the counter for the stream position. * * @return the type category of the counter for the stream position. */ public int typeId() { return typeId; } /** * {@inheritDoc} */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof StreamPosition)) { return false; } final StreamPosition that = (StreamPosition)o; return this.id == that.id && this.value == that.value && this.typeId == that.typeId; } /** * {@inheritDoc} */ public int hashCode() { int result = (int)(id ^ (id >>> 32)); result = 31 * result + (int)(value ^ (value >>> 32)); result = 31 * result + typeId; return result; } /** * {@inheritDoc} */ public String toString() { return "StreamPosition{" + "id=" + id + ", value=" + value + ", typeId=" + typeId + '}'; } } }
[Java] Sort output of the StreamStat by sessionId/streamId/channel so that related items appear together.
aeron-samples/src/main/java/io/aeron/samples/StreamStat.java
[Java] Sort output of the StreamStat by sessionId/streamId/channel so that related items appear together.
<ide><path>eron-samples/src/main/java/io/aeron/samples/StreamStat.java <ide> */ <ide> public final class StreamStat <ide> { <add> private static final Comparator<StreamCompositeKey> LINES_COMPARATOR = <add> Comparator.comparingLong(StreamCompositeKey::sessionId) <add> .thenComparingInt(StreamCompositeKey::streamId) <add> .thenComparing(StreamCompositeKey::channel); <add> <ide> private final CountersReader counters; <ide> <ide> /** <ide> */ <ide> public Map<StreamCompositeKey, List<StreamPosition>> snapshot() <ide> { <del> final Map<StreamCompositeKey, List<StreamPosition>> streams = new HashMap<>(); <add> final Map<StreamCompositeKey, List<StreamPosition>> streams = new TreeMap<>(LINES_COMPARATOR); <ide> <ide> counters.forEach( <ide> (counterId, typeId, keyBuffer, label) ->
Java
agpl-3.0
e62e514249c42792ae6517ea30d765faf8a9727f
0
Peergos/Peergos,ianopolous/Peergos,Peergos/Peergos,Peergos/Peergos,ianopolous/Peergos,ianopolous/Peergos
package peergos.server; import peergos.server.cli.CLI; import peergos.server.space.*; import peergos.server.sql.*; import peergos.server.storage.admin.*; import peergos.shared.*; import peergos.server.corenode.*; import peergos.server.fuse.*; import peergos.server.mutable.*; import peergos.server.storage.*; import peergos.server.util.*; import peergos.shared.cbor.*; import peergos.shared.corenode.*; import peergos.shared.crypto.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.asymmetric.curve25519.*; import peergos.shared.crypto.hash.*; import peergos.shared.crypto.password.*; import peergos.shared.io.ipfs.multiaddr.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.io.ipfs.multihash.*; import peergos.shared.mutable.*; import peergos.shared.social.*; import peergos.shared.storage.*; import peergos.shared.user.*; import peergos.shared.user.fs.*; import java.io.*; import java.net.*; import java.nio.file.*; import java.sql.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static final String PEERGOS_PATH = "PEERGOS_PATH"; public static final Path DEFAULT_PEERGOS_DIR_PATH = Paths.get(System.getProperty("user.home"), ".peergos"); static { PublicSigningKey.addProvider(PublicSigningKey.Type.Ed25519, new Ed25519.Java()); } public static Command<Boolean> ENSURE_IPFS_INSTALLED = new Command<>("install-ipfs", "Download/update IPFS binary. Does nothing if current IPFS binary is up-to-date.", args -> { Path ipfsExePath = IpfsWrapper.getIpfsExePath(args); File dir = ipfsExePath.getParent().toFile(); if (! dir.isDirectory() && ! dir.mkdirs()) throw new IllegalStateException("Specified install directory "+ dir +" doesn't exist and can't be created"); IpfsInstaller.ensureInstalled(ipfsExePath); List<IpfsInstaller.Plugin> plugins = IpfsInstaller.Plugin.parseAll(args); Path ipfsDir = IpfsWrapper.getIpfsDir(args); if (! plugins.isEmpty()) if (! ipfsDir.toFile().exists() && ! ipfsDir.toFile().mkdirs()) throw new IllegalStateException("Couldn't create ipfs dir: " + ipfsDir); for (IpfsInstaller.Plugin plugin : plugins) { plugin.ensureInstalled(ipfsDir); } return true; }, Arrays.asList( new Command.Arg("ipfs-exe-path", "Desired path to IPFS executable. Defaults to $PEERGOS_PATH/ipfs", false), new Command.Arg("ipfs-plugins", "comma separated list of ipfs plugins to install, currently only go-ds-s3 is supported", false), new Command.Arg("s3.path", "Path of data store in S3", false, "blocks"), new Command.Arg("s3.bucket", "S3 bucket name", false), new Command.Arg("s3.region", "S3 region", false, "us-east-1"), new Command.Arg("s3.accessKey", "S3 access key", false, ""), new Command.Arg("s3.secretKey", "S3 secret key", false, ""), new Command.Arg("s3.region.endpoint", "Base url for S3 service", false) ) ); public static Command<IpfsWrapper> IPFS = new Command<>("ipfs", "Start IPFS daemon and ensure configuration, optionally manage runtime.", Main::startIpfs, Arrays.asList( new Command.Arg("IPFS_PATH", "Path to IPFS directory. Defaults to $PEERGOS_PATH/.ipfs, or ~/.peergos/.ipfs", false), new Command.Arg("ipfs-exe-path", "Path to IPFS executable. Defaults to $PEERGOS_PATH/ipfs", false), new Command.Arg("ipfs-config-api-port", "IPFS API port", false, "5001"), new Command.Arg("ipfs-config-gateway-port", "IPFS Gateway port", false, "8080"), new Command.Arg("ipfs-config-swarm-port", "IPFS Swarm port", false, "4001"), new Command.Arg("ipfs-config-bootstrap-node-list", "Comma separated list of IPFS bootstrap nodes. Uses existing bootstrap nodes by default.", false), new Command.Arg("ipfs-manage-runtime", "Will manage the IPFS daemon runtime when set (restart on exit)", false, "true") ) ); public static final Command<UserService> PEERGOS = new Command<>("daemon", "The user facing Peergos server", Main::startPeergos, Stream.of( new Command.Arg("port", "service port", false, "8000"), new Command.Arg("peergos.identity.hash", "The hash of peergos user's public key, this is used to bootstrap the pki", true, "z59vuwzfFDp3ZA8ZpnnmHEuMtyA1q34m3Th49DYXQVJntWpxdGrRqXi"), new Command.Arg("pki-node-id", "Ipfs node id of the pki node", true, "QmVdFZgHnEgcedCS2G2ZNiEN59LuVrnRm7z3yXtEBv2XiF"), new Command.Arg("pki.node.ipaddress", "IP address of the pki node", true, "172.104.157.121"), new Command.Arg("pki.node.swarm.port", "Swarm port of the pki node", true, "5001"), new Command.Arg("domain", "Domain name to bind to,", false, "localhost"), new Command.Arg("max-users", "The maximum number of local users", false, "1"), new Command.Arg("useIPFS", "Use IPFS for storage or a local disk store", false, "true"), new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers datastore", true, "mutable.sql"), new Command.Arg("social-sql-file", "The filename for the follow requests datastore", true, "social.sql"), new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), new Command.Arg("transactions-sql-file", "The filename for the transactions datastore", false, "transactions.sql"), new Command.Arg("webroot", "the path to the directory to serve as the web root", false), new Command.Arg("default-quota", "default maximum storage per user", false, Long.toString(1024L * 1024 * 1024)), new Command.Arg("mirror.node.id", "Mirror a server's data locally", false), new Command.Arg("mirror.username", "Mirror a user's data locally", false), new Command.Arg("collect-metrics", "Export aggregated metrics", false, "false"), new Command.Arg("metrics.address", "Listen address for serving aggregated metrics", false, "localhost"), new Command.Arg("metrics.port", "Port for serving aggregated metrics", false, "8001") ).collect(Collectors.toList()) ); private static final void bootstrap(Args args) { try { // This means creating a pki keypair and publishing the public key Crypto crypto = Crypto.initJava(); // setup peergos user and pki keys String peergosPassword = args.getArg("peergos.password"); String pkiUsername = "peergos"; UserWithRoot peergos = UserUtil.generateUser(pkiUsername, peergosPassword, crypto.hasher, crypto.symmetricProvider, crypto.random, crypto.signer, crypto.boxer, SecretGenerationAlgorithm.getDefaultWithoutExtraSalt()).get(); boolean useIPFS = args.getBoolean("useIPFS"); String ipfsApiAddress = args.getArg("ipfs-api-address", "/ip4/127.0.0.1/tcp/5001"); ContentAddressedStorage dht = useIPFS ? new IpfsDHT(new MultiAddress(ipfsApiAddress)) : new FileContentAddressedStorage(blockstorePath(args), JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands())); SigningKeyPair peergosIdentityKeys = peergos.getUser(); PublicKeyHash peergosPublicHash = ContentAddressedStorage.hashKey(peergosIdentityKeys.publicSigningKey); String pkiPassword = args.getArg("pki.keygen.password"); if (peergosPassword.equals(pkiPassword)) throw new IllegalStateException("Pki password and peergos password must be different!!"); SigningKeyPair pkiKeys = UserUtil.generateUser(pkiUsername, pkiPassword, crypto.hasher, crypto.symmetricProvider, crypto.random, crypto.signer, crypto.boxer, SecretGenerationAlgorithm.getDefaultWithoutExtraSalt()).get().getUser(); IpfsTransaction.call(peergosPublicHash, tid -> dht.putSigningKey(peergosIdentityKeys.secretSigningKey.signatureOnly( pkiKeys.publicSigningKey.serialize()), peergosPublicHash, pkiKeys.publicSigningKey, tid), dht).get(); String pkiKeyfilePassword = args.getArg("pki.keyfile.password"); Cborable cipherTextCbor = PasswordProtected.encryptWithPassword(pkiKeys.secretSigningKey.toCbor().toByteArray(), pkiKeyfilePassword, crypto.hasher, crypto.symmetricProvider, crypto.random); Files.write(args.fromPeergosDir("pki.secret.key.path"), cipherTextCbor.serialize()); Files.write(args.fromPeergosDir("pki.public.key.path"), pkiKeys.publicSigningKey.toCbor().toByteArray()); args.setIfAbsent("peergos.identity.hash", peergosPublicHash.toString()); System.out.println("Peergos user identity hash: " + peergosPublicHash); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static final void poststrap(Args args) { try { // The final step of bootstrapping a new peergos network, which must be run once after network bootstrap // This means signing up the peergos user, and adding the pki public key to the peergos user Crypto crypto = Crypto.initJava(); // recreate peergos user and pki keys String password = args.getArg("peergos.password"); String pkiUsername = "peergos"; UserWithRoot peergos = UserUtil.generateUser(pkiUsername, password, crypto.hasher, crypto.symmetricProvider, crypto.random, crypto.signer, crypto.boxer, SecretGenerationAlgorithm.getDefaultWithoutExtraSalt()).get(); SigningKeyPair peergosIdentityKeys = peergos.getUser(); PublicKeyHash peergosPublicHash = ContentAddressedStorage.hashKey(peergosIdentityKeys.publicSigningKey); PublicSigningKey pkiPublic = PublicSigningKey.fromByteArray( Files.readAllBytes(args.fromPeergosDir("pki.public.key.path"))); PublicKeyHash pkiPublicHash = ContentAddressedStorage.hashKey(pkiPublic); int webPort = args.getInt("port"); NetworkAccess network = NetworkAccess.buildJava(new URL("http://localhost:" + webPort)).get(); String pkiFilePassword = args.getArg("pki.keyfile.password"); SecretSigningKey pkiSecret = SecretSigningKey.fromCbor(CborObject.fromByteArray(PasswordProtected.decryptWithPassword( CborObject.fromByteArray(Files.readAllBytes(args.fromPeergosDir("pki.secret.key.path"))), pkiFilePassword, crypto.hasher, crypto.symmetricProvider, crypto.random))); // sign up peergos user SecretGenerationAlgorithm algorithm = SecretGenerationAlgorithm.getDefaultWithoutExtraSalt(); UserContext context = UserContext.signUpGeneral(pkiUsername, password, network, crypto, algorithm, x -> {}).get(); Optional<PublicKeyHash> existingPkiKey = context.getNamedKey("pki").get(); if (!existingPkiKey.isPresent() || existingPkiKey.get().equals(pkiPublicHash)) { SigningPrivateKeyAndPublicHash pkiKeyPair = new SigningPrivateKeyAndPublicHash(pkiPublicHash, pkiSecret); // write pki public key to ipfs IpfsTransaction.call(peergosPublicHash, tid -> network.dhtClient.putSigningKey(peergosIdentityKeys.secretSigningKey .signatureOnly(pkiPublic.serialize()), peergosPublicHash, pkiPublic, tid), network.dhtClient).get(); context.addNamedOwnedKeyAndCommit("pki", pkiKeyPair).join(); } // Create /peergos/releases and make it public Optional<FileWrapper> releaseDir = context.getByPath(Paths.get(pkiUsername, "releases")).join(); if (! releaseDir.isPresent()) { context.getUserRoot().join().mkdir("releases", network, false, crypto).join(); FileWrapper releases = context.getByPath(Paths.get(pkiUsername, "releases")).join().get(); context.makePublic(releases).join(); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static final Command<UserService> PKI_INIT = new Command<>("pki-init", "Bootstrap and start the Peergos PKI Server", args -> { try { int peergosPort = args.getInt("port"); int ipfsApiPort = args.getInt("ipfs-config-api-port"); args.setIfAbsent("proxy-target", getLocalMultiAddress(peergosPort).toString()); IpfsWrapper ipfs = null; boolean useIPFS = args.getBoolean("useIPFS"); if (useIPFS) { ENSURE_IPFS_INSTALLED.main(args); ipfs = startIpfs(args); } args.setArg("ipfs-api-address", getLocalMultiAddress(ipfsApiPort).toString()); bootstrap(args); Multihash pkiIpfsNodeId = useIPFS ? new IpfsDHT(getLocalMultiAddress(ipfsApiPort)).id().get() : new FileContentAddressedStorage(blockstorePath(args), JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands())).id().get(); if (ipfs != null) ipfs.stop(); args.setIfAbsent("pki-node-id", pkiIpfsNodeId.toBase58()); UserService daemon = PEERGOS.main(args); poststrap(args); return daemon; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }, Arrays.asList( new Command.Arg("domain", "The hostname to listen on", true, "localhost"), new Command.Arg("port", "The port for the local non tls server to listen on", true, "8000"), new Command.Arg("useIPFS", "Whether to use IPFS or a local datastore", true, "false"), new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers (or :memory: or ram based)", true, ":memory:"), new Command.Arg("social-sql-file", "The filename for the follow requests (or :memory: or ram based)", true, ":memory:"), new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), new Command.Arg("ipfs-config-api-port", "ipfs api port", true, "5001"), new Command.Arg("ipfs-config-gateway-port", "ipfs gateway port", true, "8080"), new Command.Arg("pki.secret.key.path", "The path to the pki secret key file", true, "test.pki.secret.key"), new Command.Arg("pki.public.key.path", "The path to the pki public key file", true, "test.pki.public.key"), // Secret parameters new Command.Arg("peergos.password", "The password for the 'peergos' user", true), new Command.Arg("pki.keygen.password", "The password to generate the pki key from", true), new Command.Arg("pki.keyfile.password", "The password protecting the pki keyfile", true) ) ); public static final Command<UserService> PKI = new Command<>("pki", "Start the Peergos PKI Server that has already been bootstrapped", args -> { try { int peergosPort = args.getInt("port"); int ipfsApiPort = args.getInt("ipfs-config-api-port"); args.setIfAbsent("proxy-target", getLocalMultiAddress(peergosPort).toString()); IpfsWrapper ipfs = null; boolean useIPFS = args.getBoolean("useIPFS"); if (useIPFS) { ENSURE_IPFS_INSTALLED.main(args); ipfs = startIpfs(args); } args.setArg("ipfs-api-address", getLocalMultiAddress(ipfsApiPort).toString()); Multihash pkiIpfsNodeId = useIPFS ? new IpfsDHT(getLocalMultiAddress(ipfsApiPort)).id().get() : new FileContentAddressedStorage(blockstorePath(args), JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands())).id().get(); if (ipfs != null) ipfs.stop(); args.setIfAbsent("pki-node-id", pkiIpfsNodeId.toBase58()); return PEERGOS.main(args); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }, Arrays.asList( new Command.Arg("peergos.identity.hash", "The hostname to listen on", true), new Command.Arg("domain", "The hostname to listen on", true, "localhost"), new Command.Arg("port", "The port for the local non tls server to listen on", true, "8000"), new Command.Arg("useIPFS", "Whether to use IPFS or a local datastore", true, "false"), new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers (or :memory: or ram based)", true, ":memory:"), new Command.Arg("social-sql-file", "The filename for the follow requests (or :memory: or ram based)", true, ":memory:"), new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), new Command.Arg("ipfs-config-api-port", "ipfs api port", true, "5001"), new Command.Arg("ipfs-config-gateway-port", "ipfs gateway port", true, "8080"), new Command.Arg("pki.secret.key.path", "The path to the pki secret key file", true, "test.pki.secret.key"), new Command.Arg("pki.public.key.path", "The path to the pki public key file", true, "test.pki.public.key"), // Secret parameters new Command.Arg("pki.keyfile.password", "The password protecting the pki keyfile", true) ) ); public static final Command<FuseProcess> FUSE = new Command<>("fuse", "Mount a Peergos user's filesystem natively", Main::startFuse, Stream.of( new Command.Arg("username", "Peergos username", true), new Command.Arg("password", "Peergos password", true), new Command.Arg("webport", "Peergos service address port", false, "8000"), new Command.Arg("mountPoint", "The directory to mount the Peergos filesystem in", true, "peergos") ).collect(Collectors.toList()) ); public static final Command<Boolean> SHELL = new Command<>("shell", "An interactive command-line-interface to a Peergos server.", Main::startShell, Collections.emptyList() ); public static UserService startPeergos(Args a) { try { Crypto crypto = Crypto.initJava(); int webPort = a.getInt("port"); MultiAddress localPeergosApi = getLocalMultiAddress(webPort); a.setIfAbsent("proxy-target", localPeergosApi.toString()); boolean useIPFS = a.getBoolean("useIPFS"); IpfsWrapper ipfsWrapper = null; if (useIPFS) { ENSURE_IPFS_INSTALLED.main(a); ipfsWrapper = IPFS.main(a); } boolean doExportAggregatedMetrics = a.getBoolean("collect-metrics"); if (doExportAggregatedMetrics) { int exporterPort = a.getInt("metrics.port"); String exporterAddress = a.getArg("metrics.address"); AggregatedMetrics.startExporter(exporterAddress, exporterPort); } Multihash pkiServerNodeId = Cid.decode(a.getArg("pki-node-id")); URL ipfsApiAddress = AddressUtil.getLocalAddress(a.getInt("ipfs-config-api-port")); URL ipfsGatewayAddress = AddressUtil.getLocalAddress(a.getInt("ipfs-config-gateway-port")); String domain = a.getArg("domain"); InetSocketAddress userAPIAddress = new InetSocketAddress(domain, webPort); int dhtCacheEntries = 1000; int maxValueSizeToCache = 50 * 1024; JavaPoster ipfsApi = new JavaPoster(ipfsApiAddress); JavaPoster ipfsGateway = new JavaPoster(ipfsGatewayAddress); boolean usePostgres = a.getBoolean("use-postgres", false); SqlSupplier sqlCommands = usePostgres ? new PostgresCommands() : new SqliteCommands(); Connection database; if (usePostgres) { String postgresHost = a.getArg("postgres.host"); int postgresPort = a.getInt("postgres.port", 5432); String databaseName = a.getArg("postgres.database", "peergos"); String postgresUsername = a.getArg("postgres.username"); String postgresPassword = a.getArg("postgres.password"); database = Postgres.build(postgresHost, postgresPort, databaseName, postgresUsername, postgresPassword); } else { database = Sqlite.build(Sqlite.getDbPath(a, "mutable-pointers-file")); } ContentAddressedStorage localDht; if (useIPFS) { boolean enableGC = a.getBoolean("enable-gc", true); ContentAddressedStorage.HTTP ipfs = new ContentAddressedStorage.HTTP(ipfsApi, false); if (enableGC) { GarbageCollector gced = new GarbageCollector(ipfs, a.getInt("gc.period.millis", 60 * 60 * 1000)); gced.start(); localDht = new CachingStorage(gced, dhtCacheEntries, maxValueSizeToCache); } else localDht = new CachingStorage(ipfs, dhtCacheEntries, maxValueSizeToCache); } else { boolean enableGC = a.getBoolean("enable-gc", false); if (enableGC) throw new IllegalStateException("GC has not been implemented when not using IPFS!"); Connection transactionsDb = usePostgres ? database : Sqlite.build(Sqlite.getDbPath(a, "transactions-sql-file")); SqlSupplier commands = new SqliteCommands(); TransactionStore transactions = JdbcTransactionStore.build(transactionsDb, commands); // In S3 mode of operation we require the ipfs id to be supplied as we don't have a local ipfs running if (S3Config.useS3(a)) localDht = new S3BlockStorage(S3Config.build(a), Cid.decode(a.getArg("ipfs.id")), transactions); else localDht = new FileContentAddressedStorage(blockstorePath(a), transactions); } String hostname = a.getArg("domain"); Multihash nodeId = localDht.id().get(); JdbcIpnsAndSocial rawPointers = new JdbcIpnsAndSocial(database, sqlCommands); MutablePointers localPointers = UserRepository.build(localDht, rawPointers); MutablePointersProxy proxingMutable = new HttpMutablePointers(ipfsGateway, pkiServerNodeId); PublicKeyHash peergosId = PublicKeyHash.fromString(a.getArg("peergos.identity.hash")); // build a mirroring proxying corenode, unless we are the pki node boolean isPkiNode = nodeId.equals(pkiServerNodeId); CoreNode core = isPkiNode ? buildPkiCorenode(new PinningMutablePointers(localPointers, localDht), localDht, a) : new MirrorCoreNode(new HTTPCoreNode(ipfsGateway, pkiServerNodeId), proxingMutable, localDht, peergosId, a.fromPeergosDir("pki-mirror-state-path","pki-state.cbor")); long defaultQuota = a.getLong("default-quota"); long maxUsers = a.getLong("max-users"); Logging.LOG().info("Using default user space quota of " + defaultQuota); Path quotaFilePath = a.fromPeergosDir("quotas_file","quotas.txt"); Path statePath = a.fromPeergosDir("state_path","usage-state.cbor"); Connection spaceDb = usePostgres ? database : Sqlite.build(Sqlite.getDbPath(a, "space-requests-sql-file")); JdbcSpaceRequests spaceRequests = JdbcSpaceRequests.build(spaceDb, sqlCommands); UserQuotas userQuotas = new UserQuotas(quotaFilePath, defaultQuota, maxUsers); CoreNode signupFilter = new SignUpFilter(core, userQuotas, nodeId); SpaceCheckingKeyFilter spaceChecker = new SpaceCheckingKeyFilter(core, localPointers, localDht, userQuotas, spaceRequests, statePath); CorenodeEventPropagator corePropagator = new CorenodeEventPropagator(signupFilter); corePropagator.addListener(spaceChecker::accept); MutableEventPropagator localMutable = new MutableEventPropagator(localPointers); localMutable.addListener(spaceChecker::accept); ContentAddressedStorage filteringDht = new WriteFilter(localDht, spaceChecker::allowWrite); ContentAddressedStorageProxy proxingDht = new ContentAddressedStorageProxy.HTTP(ipfsGateway); ContentAddressedStorage p2pDht = new ContentAddressedStorage.Proxying(filteringDht, proxingDht, nodeId, core); Path blacklistPath = a.fromPeergosDir("blacklist_file", "blacklist.txt"); PublicKeyBlackList blacklist = new UserBasedBlacklist(blacklistPath, core, localMutable, p2pDht); MutablePointers blockingMutablePointers = new BlockingMutablePointers(new PinningMutablePointers(localMutable, p2pDht), blacklist); MutablePointers p2mMutable = new ProxyingMutablePointers(nodeId, core, blockingMutablePointers, proxingMutable); SocialNetworkProxy httpSocial = new HttpSocialNetwork(ipfsGateway, ipfsGateway); Connection socialDatabase = usePostgres ? database : Sqlite.build(Sqlite.getDbPath(a, "social-sql-file")); JdbcIpnsAndSocial rawSocial = new JdbcIpnsAndSocial(socialDatabase, sqlCommands); SocialNetwork local = UserRepository.build(p2pDht, rawSocial); SocialNetwork p2pSocial = new ProxyingSocialNetwork(nodeId, core, local, httpSocial); Path userPath = a.fromPeergosDir("whitelist_file", "user_whitelist.txt"); int delayMs = a.getInt("whitelist_sleep_period", 1000 * 60 * 10); new UserFilePinner(userPath, core, p2mMutable, p2pDht, delayMs).start(); Set<String> adminUsernames = Arrays.asList(a.getArg("admin-usernames").split(",")) .stream() .collect(Collectors.toSet()); Admin storageAdmin = new Admin(adminUsernames, spaceRequests, userQuotas, core, localDht); HttpSpaceUsage httpSpaceUsage = new HttpSpaceUsage(ipfsGateway, ipfsGateway); ProxyingSpaceUsage p2pSpaceUsage = new ProxyingSpaceUsage(nodeId, corePropagator, spaceChecker, httpSpaceUsage); UserService peergos = new UserService(p2pDht, crypto, corePropagator, p2pSocial, p2mMutable, storageAdmin, p2pSpaceUsage); InetSocketAddress localAddress = new InetSocketAddress("localhost", userAPIAddress.getPort()); Optional<Path> webroot = a.hasArg("webroot") ? Optional.of(Paths.get(a.getArg("webroot"))) : Optional.empty(); boolean useWebAssetCache = a.getBoolean("webcache", true); Optional<String> tlsHostname = hostname.equals("localhost") ? Optional.empty() : Optional.of(hostname); Optional<UserService.TlsProperties> tlsProps = tlsHostname.map(host -> new UserService.TlsProperties(host, a.getArg("tls.keyfile.password"))); peergos.initAndStart(localAddress, tlsProps, webroot, useWebAssetCache); if (! isPkiNode) { int pkiNodeSwarmPort = a.getInt("pki.node.swarm.port"); InetAddress pkiNodeIpAddress = InetAddress.getByName(a.getArg("pki.node.ipaddress")); ipfsWrapper.connectToNode(new InetSocketAddress(pkiNodeIpAddress, pkiNodeSwarmPort), pkiServerNodeId); ((MirrorCoreNode) core).start(); } spaceChecker.calculateUsage(); if (a.hasArg("mirror.node.id")) { Multihash nodeToMirrorId = Cid.decode(a.getArg("mirror.node.id")); NetworkAccess localApi = NetworkAccess.buildJava(webPort).join(); new Thread(() -> { while (true) { try { Mirror.mirrorNode(nodeToMirrorId, localApi, rawPointers, localDht); try { Thread.sleep(60_000); } catch (InterruptedException f) {} } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(5_000); } catch (InterruptedException f) {} } } }).start(); } if (a.hasArg("mirror.username")) { NetworkAccess localApi = NetworkAccess.buildJava(webPort).join(); new Thread(() -> { while (true) { try { Mirror.mirrorUser(a.getArg("mirror.username"), localApi, rawPointers, localDht); try { Thread.sleep(60_000); } catch (InterruptedException f) {} } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(5_000); } catch (InterruptedException f) {} } } }).start(); } return peergos; } catch (Exception e) { throw new RuntimeException(e); } } public static FuseProcess startFuse(Args a) { String username = a.getArg("username"); String password = a.getArg("password"); int webPort = a.getInt("webport"); try { Files.createTempDirectory("peergos").toString(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } String mountPath = a.getArg("mountPoint"); Path path = Paths.get(mountPath); path.toFile().mkdirs(); System.out.println("\n\nPeergos mounted at " + path + "\n\n"); try { NetworkAccess network = NetworkAccess.buildJava(webPort).get(); Crypto crypto = Crypto.initJava(); UserContext userContext = PeergosNetworkUtils.ensureSignedUp(username, password, network, crypto); PeergosFS peergosFS = new PeergosFS(userContext); FuseProcess fuseProcess = new FuseProcess(peergosFS, path); Runtime.getRuntime().addShutdownHook(new Thread(() -> fuseProcess.close(), "Fuse shutdown")); fuseProcess.start(); return fuseProcess; } catch (Exception ex) { throw new IllegalStateException(ex); } } public static IpfsWrapper startIpfs(Args a) { // test if ipfs is already running int ipfsApiPort = IpfsWrapper.getApiPort(a); if (IpfsWrapper.isHttpApiListening(ipfsApiPort)) { throw new IllegalStateException("IPFS is already running on api port " + ipfsApiPort); } IpfsWrapper ipfs = IpfsWrapper.build(a); if (a.getBoolean("ipfs-manage-runtime", true)) IpfsWrapper.launchAndManage(ipfs); else { IpfsWrapper.launchOnce(ipfs); } // wait for daemon to finish starting ipfs.waitForDaemon(10); return ipfs; } public static Boolean startShell(Args args) { CLI.main(new String[]{}); return true; } private static CoreNode buildPkiCorenode(MutablePointers mutable, ContentAddressedStorage dht, Args a) { try { Crypto crypto = Crypto.initJava(); PublicKeyHash peergosIdentity = PublicKeyHash.fromString(a.getArg("peergos.identity.hash")); String pkiSecretKeyfilePassword = a.getArg("pki.keyfile.password"); PublicSigningKey pkiPublic = PublicSigningKey.fromByteArray( Files.readAllBytes(a.fromPeergosDir("pki.public.key.path"))); SecretSigningKey pkiSecretKey = SecretSigningKey.fromCbor(CborObject.fromByteArray( PasswordProtected.decryptWithPassword( CborObject.fromByteArray(Files.readAllBytes(a.fromPeergosDir("pki.secret.key.path"))), pkiSecretKeyfilePassword, crypto.hasher, crypto.symmetricProvider, crypto.random ))); SigningKeyPair pkiKeys = new SigningKeyPair(pkiPublic, pkiSecretKey); PublicKeyHash pkiPublicHash = ContentAddressedStorage.hashKey(pkiKeys.publicSigningKey); MaybeMultihash currentPkiRoot = mutable.getPointerTarget(peergosIdentity, pkiPublicHash, dht).get(); SigningPrivateKeyAndPublicHash pkiSigner = new SigningPrivateKeyAndPublicHash(pkiPublicHash, pkiSecretKey); if (! currentPkiRoot.isPresent()) currentPkiRoot = IpfsTransaction.call(peergosIdentity, tid -> WriterData.createEmpty(peergosIdentity, pkiSigner, dht, tid).join() .commit(peergosIdentity, pkiSigner, MaybeMultihash.empty(), mutable, dht, tid) .thenApply(version -> version.get(pkiSigner).hash), dht).join(); return new IpfsCoreNode(pkiSigner, currentPkiRoot, dht, mutable, peergosIdentity); } catch (Exception e) { throw new RuntimeException(e); } } public static final Command<Void> MAIN = new Command<>("Main", "Run a Peergos command", args -> { System.out.println("Run with -help to show options"); return null; }, Collections.emptyList(), Arrays.asList( PEERGOS, SHELL, FUSE, PKI_INIT, PKI ) ); /** * Create path to local blockstore directory from Args. * * @param args * @return */ private static Path blockstorePath(Args args) { return args.fromPeergosDir("blockstore_dir", "blockstore"); } public static MultiAddress getLocalMultiAddress(int port) { return new MultiAddress("/ip4/127.0.0.1/tcp/" + port); } public static MultiAddress getLocalBootstrapAddress(int port, Multihash nodeId) { return new MultiAddress("/ip4/127.0.0.1/tcp/" + port + "/ipfs/"+ nodeId); } public static void main(String[] args) { MAIN.main(Args.parse(args)); } }
src/peergos/server/Main.java
package peergos.server; import peergos.server.cli.CLI; import peergos.server.space.*; import peergos.server.sql.*; import peergos.server.storage.admin.*; import peergos.shared.*; import peergos.server.corenode.*; import peergos.server.fuse.*; import peergos.server.mutable.*; import peergos.server.storage.*; import peergos.server.util.*; import peergos.shared.cbor.*; import peergos.shared.corenode.*; import peergos.shared.crypto.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.asymmetric.curve25519.*; import peergos.shared.crypto.hash.*; import peergos.shared.crypto.password.*; import peergos.shared.io.ipfs.multiaddr.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.io.ipfs.multihash.*; import peergos.shared.mutable.*; import peergos.shared.social.*; import peergos.shared.storage.*; import peergos.shared.user.*; import peergos.shared.user.fs.*; import java.io.*; import java.net.*; import java.nio.file.*; import java.sql.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static final String PEERGOS_PATH = "PEERGOS_PATH"; public static final Path DEFAULT_PEERGOS_DIR_PATH = Paths.get(System.getProperty("user.home"), ".peergos"); static { PublicSigningKey.addProvider(PublicSigningKey.Type.Ed25519, new Ed25519.Java()); } public static Command<Boolean> ENSURE_IPFS_INSTALLED = new Command<>("install-ipfs", "Download/update IPFS binary. Does nothing if current IPFS binary is up-to-date.", args -> { Path ipfsExePath = IpfsWrapper.getIpfsExePath(args); File dir = ipfsExePath.getParent().toFile(); if (! dir.isDirectory() && ! dir.mkdirs()) throw new IllegalStateException("Specified install directory "+ dir +" doesn't exist and can't be created"); IpfsInstaller.ensureInstalled(ipfsExePath); List<IpfsInstaller.Plugin> plugins = IpfsInstaller.Plugin.parseAll(args); Path ipfsDir = IpfsWrapper.getIpfsDir(args); if (! plugins.isEmpty()) if (! ipfsDir.toFile().exists() && ! ipfsDir.toFile().mkdirs()) throw new IllegalStateException("Couldn't create ipfs dir: " + ipfsDir); for (IpfsInstaller.Plugin plugin : plugins) { plugin.ensureInstalled(ipfsDir); } return true; }, Arrays.asList( new Command.Arg("ipfs-exe-path", "Desired path to IPFS executable. Defaults to $PEERGOS_PATH/ipfs", false), new Command.Arg("ipfs-plugins", "comma separated list of ipfs plugins to install, currently only go-ds-s3 is supported", false), new Command.Arg("s3.path", "Path of data store in S3", false, "blocks"), new Command.Arg("s3.bucket", "S3 bucket name", false), new Command.Arg("s3.region", "S3 region", false, "us-east-1"), new Command.Arg("s3.accessKey", "S3 access key", false, ""), new Command.Arg("s3.secretKey", "S3 secret key", false, ""), new Command.Arg("s3.region.endpoint", "Base url for S3 service", false) ) ); public static Command<IpfsWrapper> IPFS = new Command<>("ipfs", "Start IPFS daemon and ensure configuration, optionally manage runtime.", Main::startIpfs, Arrays.asList( new Command.Arg("IPFS_PATH", "Path to IPFS directory. Defaults to $PEERGOS_PATH/.ipfs, or ~/.peergos/.ipfs", false), new Command.Arg("ipfs-exe-path", "Path to IPFS executable. Defaults to $PEERGOS_PATH/ipfs", false), new Command.Arg("ipfs-config-api-port", "IPFS API port", false, "5001"), new Command.Arg("ipfs-config-gateway-port", "IPFS Gateway port", false, "8080"), new Command.Arg("ipfs-config-swarm-port", "IPFS Swarm port", false, "4001"), new Command.Arg("ipfs-config-bootstrap-node-list", "Comma separated list of IPFS bootstrap nodes. Uses existing bootstrap nodes by default.", false), new Command.Arg("ipfs-manage-runtime", "Will manage the IPFS daemon runtime when set (restart on exit)", false, "true") ) ); public static final Command<UserService> PEERGOS = new Command<>("daemon", "The user facing Peergos server", Main::startPeergos, Stream.of( new Command.Arg("port", "service port", false, "8000"), new Command.Arg("peergos.identity.hash", "The hash of peergos user's public key, this is used to bootstrap the pki", true, "z59vuwzfFDp3ZA8ZpnnmHEuMtyA1q34m3Th49DYXQVJntWpxdGrRqXi"), new Command.Arg("pki-node-id", "Ipfs node id of the pki node", true, "QmVdFZgHnEgcedCS2G2ZNiEN59LuVrnRm7z3yXtEBv2XiF"), new Command.Arg("pki.node.ipaddress", "IP address of the pki node", true, "172.104.157.121"), new Command.Arg("pki.node.swarm.port", "Swarm port of the pki node", true, "5001"), new Command.Arg("domain", "Domain name to bind to,", false, "localhost"), new Command.Arg("max-users", "The maximum number of local users", false, "1"), new Command.Arg("useIPFS", "Use IPFS for storage or a local disk store", false, "true"), new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers datastore", true, "mutable.sql"), new Command.Arg("social-sql-file", "The filename for the follow requests datastore", true, "social.sql"), new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), new Command.Arg("webroot", "the path to the directory to serve as the web root", false), new Command.Arg("default-quota", "default maximum storage per user", false, Long.toString(1024L * 1024 * 1024)), new Command.Arg("mirror.node.id", "Mirror a server's data locally", false), new Command.Arg("mirror.username", "Mirror a user's data locally", false), new Command.Arg("collect-metrics", "Export aggregated metrics", false, "false"), new Command.Arg("metrics.address", "Listen address for serving aggregated metrics", false, "localhost"), new Command.Arg("metrics.port", "Port for serving aggregated metrics", false, "8001") ).collect(Collectors.toList()) ); private static final void bootstrap(Args args) { try { // This means creating a pki keypair and publishing the public key Crypto crypto = Crypto.initJava(); // setup peergos user and pki keys String peergosPassword = args.getArg("peergos.password"); String pkiUsername = "peergos"; UserWithRoot peergos = UserUtil.generateUser(pkiUsername, peergosPassword, crypto.hasher, crypto.symmetricProvider, crypto.random, crypto.signer, crypto.boxer, SecretGenerationAlgorithm.getDefaultWithoutExtraSalt()).get(); boolean useIPFS = args.getBoolean("useIPFS"); String ipfsApiAddress = args.getArg("ipfs-api-address", "/ip4/127.0.0.1/tcp/5001"); ContentAddressedStorage dht = useIPFS ? new IpfsDHT(new MultiAddress(ipfsApiAddress)) : new FileContentAddressedStorage(blockstorePath(args), JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands())); SigningKeyPair peergosIdentityKeys = peergos.getUser(); PublicKeyHash peergosPublicHash = ContentAddressedStorage.hashKey(peergosIdentityKeys.publicSigningKey); String pkiPassword = args.getArg("pki.keygen.password"); if (peergosPassword.equals(pkiPassword)) throw new IllegalStateException("Pki password and peergos password must be different!!"); SigningKeyPair pkiKeys = UserUtil.generateUser(pkiUsername, pkiPassword, crypto.hasher, crypto.symmetricProvider, crypto.random, crypto.signer, crypto.boxer, SecretGenerationAlgorithm.getDefaultWithoutExtraSalt()).get().getUser(); IpfsTransaction.call(peergosPublicHash, tid -> dht.putSigningKey(peergosIdentityKeys.secretSigningKey.signatureOnly( pkiKeys.publicSigningKey.serialize()), peergosPublicHash, pkiKeys.publicSigningKey, tid), dht).get(); String pkiKeyfilePassword = args.getArg("pki.keyfile.password"); Cborable cipherTextCbor = PasswordProtected.encryptWithPassword(pkiKeys.secretSigningKey.toCbor().toByteArray(), pkiKeyfilePassword, crypto.hasher, crypto.symmetricProvider, crypto.random); Files.write(args.fromPeergosDir("pki.secret.key.path"), cipherTextCbor.serialize()); Files.write(args.fromPeergosDir("pki.public.key.path"), pkiKeys.publicSigningKey.toCbor().toByteArray()); args.setIfAbsent("peergos.identity.hash", peergosPublicHash.toString()); System.out.println("Peergos user identity hash: " + peergosPublicHash); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static final void poststrap(Args args) { try { // The final step of bootstrapping a new peergos network, which must be run once after network bootstrap // This means signing up the peergos user, and adding the pki public key to the peergos user Crypto crypto = Crypto.initJava(); // recreate peergos user and pki keys String password = args.getArg("peergos.password"); String pkiUsername = "peergos"; UserWithRoot peergos = UserUtil.generateUser(pkiUsername, password, crypto.hasher, crypto.symmetricProvider, crypto.random, crypto.signer, crypto.boxer, SecretGenerationAlgorithm.getDefaultWithoutExtraSalt()).get(); SigningKeyPair peergosIdentityKeys = peergos.getUser(); PublicKeyHash peergosPublicHash = ContentAddressedStorage.hashKey(peergosIdentityKeys.publicSigningKey); PublicSigningKey pkiPublic = PublicSigningKey.fromByteArray( Files.readAllBytes(args.fromPeergosDir("pki.public.key.path"))); PublicKeyHash pkiPublicHash = ContentAddressedStorage.hashKey(pkiPublic); int webPort = args.getInt("port"); NetworkAccess network = NetworkAccess.buildJava(new URL("http://localhost:" + webPort)).get(); String pkiFilePassword = args.getArg("pki.keyfile.password"); SecretSigningKey pkiSecret = SecretSigningKey.fromCbor(CborObject.fromByteArray(PasswordProtected.decryptWithPassword( CborObject.fromByteArray(Files.readAllBytes(args.fromPeergosDir("pki.secret.key.path"))), pkiFilePassword, crypto.hasher, crypto.symmetricProvider, crypto.random))); // sign up peergos user SecretGenerationAlgorithm algorithm = SecretGenerationAlgorithm.getDefaultWithoutExtraSalt(); UserContext context = UserContext.signUpGeneral(pkiUsername, password, network, crypto, algorithm, x -> {}).get(); Optional<PublicKeyHash> existingPkiKey = context.getNamedKey("pki").get(); if (!existingPkiKey.isPresent() || existingPkiKey.get().equals(pkiPublicHash)) { SigningPrivateKeyAndPublicHash pkiKeyPair = new SigningPrivateKeyAndPublicHash(pkiPublicHash, pkiSecret); // write pki public key to ipfs IpfsTransaction.call(peergosPublicHash, tid -> network.dhtClient.putSigningKey(peergosIdentityKeys.secretSigningKey .signatureOnly(pkiPublic.serialize()), peergosPublicHash, pkiPublic, tid), network.dhtClient).get(); context.addNamedOwnedKeyAndCommit("pki", pkiKeyPair).join(); } // Create /peergos/releases and make it public Optional<FileWrapper> releaseDir = context.getByPath(Paths.get(pkiUsername, "releases")).join(); if (! releaseDir.isPresent()) { context.getUserRoot().join().mkdir("releases", network, false, crypto).join(); FileWrapper releases = context.getByPath(Paths.get(pkiUsername, "releases")).join().get(); context.makePublic(releases).join(); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static final Command<UserService> PKI_INIT = new Command<>("pki-init", "Bootstrap and start the Peergos PKI Server", args -> { try { int peergosPort = args.getInt("port"); int ipfsApiPort = args.getInt("ipfs-config-api-port"); args.setIfAbsent("proxy-target", getLocalMultiAddress(peergosPort).toString()); IpfsWrapper ipfs = null; boolean useIPFS = args.getBoolean("useIPFS"); if (useIPFS) { ENSURE_IPFS_INSTALLED.main(args); ipfs = startIpfs(args); } args.setArg("ipfs-api-address", getLocalMultiAddress(ipfsApiPort).toString()); bootstrap(args); Multihash pkiIpfsNodeId = useIPFS ? new IpfsDHT(getLocalMultiAddress(ipfsApiPort)).id().get() : new FileContentAddressedStorage(blockstorePath(args), JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands())).id().get(); if (ipfs != null) ipfs.stop(); args.setIfAbsent("pki-node-id", pkiIpfsNodeId.toBase58()); UserService daemon = PEERGOS.main(args); poststrap(args); return daemon; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }, Arrays.asList( new Command.Arg("domain", "The hostname to listen on", true, "localhost"), new Command.Arg("port", "The port for the local non tls server to listen on", true, "8000"), new Command.Arg("useIPFS", "Whether to use IPFS or a local datastore", true, "false"), new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers (or :memory: or ram based)", true, ":memory:"), new Command.Arg("social-sql-file", "The filename for the follow requests (or :memory: or ram based)", true, ":memory:"), new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), new Command.Arg("ipfs-config-api-port", "ipfs api port", true, "5001"), new Command.Arg("ipfs-config-gateway-port", "ipfs gateway port", true, "8080"), new Command.Arg("pki.secret.key.path", "The path to the pki secret key file", true, "test.pki.secret.key"), new Command.Arg("pki.public.key.path", "The path to the pki public key file", true, "test.pki.public.key"), // Secret parameters new Command.Arg("peergos.password", "The password for the 'peergos' user", true), new Command.Arg("pki.keygen.password", "The password to generate the pki key from", true), new Command.Arg("pki.keyfile.password", "The password protecting the pki keyfile", true) ) ); public static final Command<UserService> PKI = new Command<>("pki", "Start the Peergos PKI Server that has already been bootstrapped", args -> { try { int peergosPort = args.getInt("port"); int ipfsApiPort = args.getInt("ipfs-config-api-port"); args.setIfAbsent("proxy-target", getLocalMultiAddress(peergosPort).toString()); IpfsWrapper ipfs = null; boolean useIPFS = args.getBoolean("useIPFS"); if (useIPFS) { ENSURE_IPFS_INSTALLED.main(args); ipfs = startIpfs(args); } args.setArg("ipfs-api-address", getLocalMultiAddress(ipfsApiPort).toString()); Multihash pkiIpfsNodeId = useIPFS ? new IpfsDHT(getLocalMultiAddress(ipfsApiPort)).id().get() : new FileContentAddressedStorage(blockstorePath(args), JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands())).id().get(); if (ipfs != null) ipfs.stop(); args.setIfAbsent("pki-node-id", pkiIpfsNodeId.toBase58()); return PEERGOS.main(args); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }, Arrays.asList( new Command.Arg("peergos.identity.hash", "The hostname to listen on", true), new Command.Arg("domain", "The hostname to listen on", true, "localhost"), new Command.Arg("port", "The port for the local non tls server to listen on", true, "8000"), new Command.Arg("useIPFS", "Whether to use IPFS or a local datastore", true, "false"), new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers (or :memory: or ram based)", true, ":memory:"), new Command.Arg("social-sql-file", "The filename for the follow requests (or :memory: or ram based)", true, ":memory:"), new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), new Command.Arg("ipfs-config-api-port", "ipfs api port", true, "5001"), new Command.Arg("ipfs-config-gateway-port", "ipfs gateway port", true, "8080"), new Command.Arg("pki.secret.key.path", "The path to the pki secret key file", true, "test.pki.secret.key"), new Command.Arg("pki.public.key.path", "The path to the pki public key file", true, "test.pki.public.key"), // Secret parameters new Command.Arg("pki.keyfile.password", "The password protecting the pki keyfile", true) ) ); public static final Command<FuseProcess> FUSE = new Command<>("fuse", "Mount a Peergos user's filesystem natively", Main::startFuse, Stream.of( new Command.Arg("username", "Peergos username", true), new Command.Arg("password", "Peergos password", true), new Command.Arg("webport", "Peergos service address port", false, "8000"), new Command.Arg("mountPoint", "The directory to mount the Peergos filesystem in", true, "peergos") ).collect(Collectors.toList()) ); public static final Command<Boolean> SHELL = new Command<>("shell", "An interactive command-line-interface to a Peergos server.", Main::startShell, Collections.emptyList() ); public static UserService startPeergos(Args a) { try { Crypto crypto = Crypto.initJava(); int webPort = a.getInt("port"); MultiAddress localPeergosApi = getLocalMultiAddress(webPort); a.setIfAbsent("proxy-target", localPeergosApi.toString()); boolean useIPFS = a.getBoolean("useIPFS"); IpfsWrapper ipfsWrapper = null; if (useIPFS) { ENSURE_IPFS_INSTALLED.main(a); ipfsWrapper = IPFS.main(a); } boolean doExportAggregatedMetrics = a.getBoolean("collect-metrics"); if (doExportAggregatedMetrics) { int exporterPort = a.getInt("metrics.port"); String exporterAddress = a.getArg("metrics.address"); AggregatedMetrics.startExporter(exporterAddress, exporterPort); } Multihash pkiServerNodeId = Cid.decode(a.getArg("pki-node-id")); URL ipfsApiAddress = AddressUtil.getLocalAddress(a.getInt("ipfs-config-api-port")); URL ipfsGatewayAddress = AddressUtil.getLocalAddress(a.getInt("ipfs-config-gateway-port")); String domain = a.getArg("domain"); InetSocketAddress userAPIAddress = new InetSocketAddress(domain, webPort); int dhtCacheEntries = 1000; int maxValueSizeToCache = 50 * 1024; JavaPoster ipfsApi = new JavaPoster(ipfsApiAddress); JavaPoster ipfsGateway = new JavaPoster(ipfsGatewayAddress); boolean usePostgres = a.getBoolean("use-postgres", false); SqlSupplier sqlCommands = usePostgres ? new PostgresCommands() : new SqliteCommands(); Connection database; if (usePostgres) { String postgresHost = a.getArg("postgres.host"); int postgresPort = a.getInt("postgres.port", 5432); String databaseName = a.getArg("postgres.database", "peergos"); String postgresUsername = a.getArg("postgres.username"); String postgresPassword = a.getArg("postgres.password"); database = Postgres.build(postgresHost, postgresPort, databaseName, postgresUsername, postgresPassword); } else { database = Sqlite.build(Sqlite.getDbPath(a, "mutable-pointers-file")); } ContentAddressedStorage localDht; if (useIPFS) { boolean enableGC = a.getBoolean("enable-gc", true); ContentAddressedStorage.HTTP ipfs = new ContentAddressedStorage.HTTP(ipfsApi, false); if (enableGC) { GarbageCollector gced = new GarbageCollector(ipfs, a.getInt("gc.period.millis", 60 * 60 * 1000)); gced.start(); localDht = new CachingStorage(gced, dhtCacheEntries, maxValueSizeToCache); } else localDht = new CachingStorage(ipfs, dhtCacheEntries, maxValueSizeToCache); } else { boolean enableGC = a.getBoolean("enable-gc", false); if (enableGC) throw new IllegalStateException("GC has not been implemented when not using IPFS!"); Connection transactionsDb = usePostgres ? database : Sqlite.build(Sqlite.getDbPath(a, "transactions-sql-file")); SqlSupplier commands = new SqliteCommands(); TransactionStore transactions = JdbcTransactionStore.build(transactionsDb, commands); // In S3 mode of operation we require the ipfs id to be supplied as we don't have a local ipfs running if (S3Config.useS3(a)) localDht = new S3BlockStorage(S3Config.build(a), Cid.decode(a.getArg("ipfs.id")), transactions); else localDht = new FileContentAddressedStorage(blockstorePath(a), transactions); } String hostname = a.getArg("domain"); Multihash nodeId = localDht.id().get(); JdbcIpnsAndSocial rawPointers = new JdbcIpnsAndSocial(database, sqlCommands); MutablePointers localPointers = UserRepository.build(localDht, rawPointers); MutablePointersProxy proxingMutable = new HttpMutablePointers(ipfsGateway, pkiServerNodeId); PublicKeyHash peergosId = PublicKeyHash.fromString(a.getArg("peergos.identity.hash")); // build a mirroring proxying corenode, unless we are the pki node boolean isPkiNode = nodeId.equals(pkiServerNodeId); CoreNode core = isPkiNode ? buildPkiCorenode(new PinningMutablePointers(localPointers, localDht), localDht, a) : new MirrorCoreNode(new HTTPCoreNode(ipfsGateway, pkiServerNodeId), proxingMutable, localDht, peergosId, a.fromPeergosDir("pki-mirror-state-path","pki-state.cbor")); long defaultQuota = a.getLong("default-quota"); long maxUsers = a.getLong("max-users"); Logging.LOG().info("Using default user space quota of " + defaultQuota); Path quotaFilePath = a.fromPeergosDir("quotas_file","quotas.txt"); Path statePath = a.fromPeergosDir("state_path","usage-state.cbor"); Connection spaceDb = usePostgres ? database : Sqlite.build(Sqlite.getDbPath(a, "space-requests-sql-file")); JdbcSpaceRequests spaceRequests = JdbcSpaceRequests.build(spaceDb, sqlCommands); UserQuotas userQuotas = new UserQuotas(quotaFilePath, defaultQuota, maxUsers); CoreNode signupFilter = new SignUpFilter(core, userQuotas, nodeId); SpaceCheckingKeyFilter spaceChecker = new SpaceCheckingKeyFilter(core, localPointers, localDht, userQuotas, spaceRequests, statePath); CorenodeEventPropagator corePropagator = new CorenodeEventPropagator(signupFilter); corePropagator.addListener(spaceChecker::accept); MutableEventPropagator localMutable = new MutableEventPropagator(localPointers); localMutable.addListener(spaceChecker::accept); ContentAddressedStorage filteringDht = new WriteFilter(localDht, spaceChecker::allowWrite); ContentAddressedStorageProxy proxingDht = new ContentAddressedStorageProxy.HTTP(ipfsGateway); ContentAddressedStorage p2pDht = new ContentAddressedStorage.Proxying(filteringDht, proxingDht, nodeId, core); Path blacklistPath = a.fromPeergosDir("blacklist_file", "blacklist.txt"); PublicKeyBlackList blacklist = new UserBasedBlacklist(blacklistPath, core, localMutable, p2pDht); MutablePointers blockingMutablePointers = new BlockingMutablePointers(new PinningMutablePointers(localMutable, p2pDht), blacklist); MutablePointers p2mMutable = new ProxyingMutablePointers(nodeId, core, blockingMutablePointers, proxingMutable); SocialNetworkProxy httpSocial = new HttpSocialNetwork(ipfsGateway, ipfsGateway); Connection socialDatabase = usePostgres ? database : Sqlite.build(Sqlite.getDbPath(a, "social-sql-file")); JdbcIpnsAndSocial rawSocial = new JdbcIpnsAndSocial(socialDatabase, sqlCommands); SocialNetwork local = UserRepository.build(p2pDht, rawSocial); SocialNetwork p2pSocial = new ProxyingSocialNetwork(nodeId, core, local, httpSocial); Path userPath = a.fromPeergosDir("whitelist_file", "user_whitelist.txt"); int delayMs = a.getInt("whitelist_sleep_period", 1000 * 60 * 10); new UserFilePinner(userPath, core, p2mMutable, p2pDht, delayMs).start(); Set<String> adminUsernames = Arrays.asList(a.getArg("admin-usernames").split(",")) .stream() .collect(Collectors.toSet()); Admin storageAdmin = new Admin(adminUsernames, spaceRequests, userQuotas, core, localDht); HttpSpaceUsage httpSpaceUsage = new HttpSpaceUsage(ipfsGateway, ipfsGateway); ProxyingSpaceUsage p2pSpaceUsage = new ProxyingSpaceUsage(nodeId, corePropagator, spaceChecker, httpSpaceUsage); UserService peergos = new UserService(p2pDht, crypto, corePropagator, p2pSocial, p2mMutable, storageAdmin, p2pSpaceUsage); InetSocketAddress localAddress = new InetSocketAddress("localhost", userAPIAddress.getPort()); Optional<Path> webroot = a.hasArg("webroot") ? Optional.of(Paths.get(a.getArg("webroot"))) : Optional.empty(); boolean useWebAssetCache = a.getBoolean("webcache", true); Optional<String> tlsHostname = hostname.equals("localhost") ? Optional.empty() : Optional.of(hostname); Optional<UserService.TlsProperties> tlsProps = tlsHostname.map(host -> new UserService.TlsProperties(host, a.getArg("tls.keyfile.password"))); peergos.initAndStart(localAddress, tlsProps, webroot, useWebAssetCache); if (! isPkiNode) { int pkiNodeSwarmPort = a.getInt("pki.node.swarm.port"); InetAddress pkiNodeIpAddress = InetAddress.getByName(a.getArg("pki.node.ipaddress")); ipfsWrapper.connectToNode(new InetSocketAddress(pkiNodeIpAddress, pkiNodeSwarmPort), pkiServerNodeId); ((MirrorCoreNode) core).start(); } spaceChecker.calculateUsage(); if (a.hasArg("mirror.node.id")) { Multihash nodeToMirrorId = Cid.decode(a.getArg("mirror.node.id")); NetworkAccess localApi = NetworkAccess.buildJava(webPort).join(); new Thread(() -> { while (true) { try { Mirror.mirrorNode(nodeToMirrorId, localApi, rawPointers, localDht); try { Thread.sleep(60_000); } catch (InterruptedException f) {} } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(5_000); } catch (InterruptedException f) {} } } }).start(); } if (a.hasArg("mirror.username")) { NetworkAccess localApi = NetworkAccess.buildJava(webPort).join(); new Thread(() -> { while (true) { try { Mirror.mirrorUser(a.getArg("mirror.username"), localApi, rawPointers, localDht); try { Thread.sleep(60_000); } catch (InterruptedException f) {} } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(5_000); } catch (InterruptedException f) {} } } }).start(); } return peergos; } catch (Exception e) { throw new RuntimeException(e); } } public static FuseProcess startFuse(Args a) { String username = a.getArg("username"); String password = a.getArg("password"); int webPort = a.getInt("webport"); try { Files.createTempDirectory("peergos").toString(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } String mountPath = a.getArg("mountPoint"); Path path = Paths.get(mountPath); path.toFile().mkdirs(); System.out.println("\n\nPeergos mounted at " + path + "\n\n"); try { NetworkAccess network = NetworkAccess.buildJava(webPort).get(); Crypto crypto = Crypto.initJava(); UserContext userContext = PeergosNetworkUtils.ensureSignedUp(username, password, network, crypto); PeergosFS peergosFS = new PeergosFS(userContext); FuseProcess fuseProcess = new FuseProcess(peergosFS, path); Runtime.getRuntime().addShutdownHook(new Thread(() -> fuseProcess.close(), "Fuse shutdown")); fuseProcess.start(); return fuseProcess; } catch (Exception ex) { throw new IllegalStateException(ex); } } public static IpfsWrapper startIpfs(Args a) { // test if ipfs is already running int ipfsApiPort = IpfsWrapper.getApiPort(a); if (IpfsWrapper.isHttpApiListening(ipfsApiPort)) { throw new IllegalStateException("IPFS is already running on api port " + ipfsApiPort); } IpfsWrapper ipfs = IpfsWrapper.build(a); if (a.getBoolean("ipfs-manage-runtime", true)) IpfsWrapper.launchAndManage(ipfs); else { IpfsWrapper.launchOnce(ipfs); } // wait for daemon to finish starting ipfs.waitForDaemon(10); return ipfs; } public static Boolean startShell(Args args) { CLI.main(new String[]{}); return true; } private static CoreNode buildPkiCorenode(MutablePointers mutable, ContentAddressedStorage dht, Args a) { try { Crypto crypto = Crypto.initJava(); PublicKeyHash peergosIdentity = PublicKeyHash.fromString(a.getArg("peergos.identity.hash")); String pkiSecretKeyfilePassword = a.getArg("pki.keyfile.password"); PublicSigningKey pkiPublic = PublicSigningKey.fromByteArray( Files.readAllBytes(a.fromPeergosDir("pki.public.key.path"))); SecretSigningKey pkiSecretKey = SecretSigningKey.fromCbor(CborObject.fromByteArray( PasswordProtected.decryptWithPassword( CborObject.fromByteArray(Files.readAllBytes(a.fromPeergosDir("pki.secret.key.path"))), pkiSecretKeyfilePassword, crypto.hasher, crypto.symmetricProvider, crypto.random ))); SigningKeyPair pkiKeys = new SigningKeyPair(pkiPublic, pkiSecretKey); PublicKeyHash pkiPublicHash = ContentAddressedStorage.hashKey(pkiKeys.publicSigningKey); MaybeMultihash currentPkiRoot = mutable.getPointerTarget(peergosIdentity, pkiPublicHash, dht).get(); SigningPrivateKeyAndPublicHash pkiSigner = new SigningPrivateKeyAndPublicHash(pkiPublicHash, pkiSecretKey); if (! currentPkiRoot.isPresent()) currentPkiRoot = IpfsTransaction.call(peergosIdentity, tid -> WriterData.createEmpty(peergosIdentity, pkiSigner, dht, tid).join() .commit(peergosIdentity, pkiSigner, MaybeMultihash.empty(), mutable, dht, tid) .thenApply(version -> version.get(pkiSigner).hash), dht).join(); return new IpfsCoreNode(pkiSigner, currentPkiRoot, dht, mutable, peergosIdentity); } catch (Exception e) { throw new RuntimeException(e); } } public static final Command<Void> MAIN = new Command<>("Main", "Run a Peergos command", args -> { System.out.println("Run with -help to show options"); return null; }, Collections.emptyList(), Arrays.asList( PEERGOS, SHELL, FUSE, PKI_INIT, PKI ) ); /** * Create path to local blockstore directory from Args. * * @param args * @return */ private static Path blockstorePath(Args args) { return args.fromPeergosDir("blockstore_dir", "blockstore"); } public static MultiAddress getLocalMultiAddress(int port) { return new MultiAddress("/ip4/127.0.0.1/tcp/" + port); } public static MultiAddress getLocalBootstrapAddress(int port, Multihash nodeId) { return new MultiAddress("/ip4/127.0.0.1/tcp/" + port + "/ipfs/"+ nodeId); } public static void main(String[] args) { MAIN.main(Args.parse(args)); } }
Fix tests with default parameter value
src/peergos/server/Main.java
Fix tests with default parameter value
<ide><path>rc/peergos/server/Main.java <ide> new Command.Arg("mutable-pointers-file", "The filename for the mutable pointers datastore", true, "mutable.sql"), <ide> new Command.Arg("social-sql-file", "The filename for the follow requests datastore", true, "social.sql"), <ide> new Command.Arg("space-requests-sql-file", "The filename for the space requests datastore", true, "space-requests.sql"), <add> new Command.Arg("transactions-sql-file", "The filename for the transactions datastore", false, "transactions.sql"), <ide> new Command.Arg("webroot", "the path to the directory to serve as the web root", false), <ide> new Command.Arg("default-quota", "default maximum storage per user", false, Long.toString(1024L * 1024 * 1024)), <ide> new Command.Arg("mirror.node.id", "Mirror a server's data locally", false),
Java
mit
fcedf52b0fec4291f6d72e5fbd09eb074d0d6486
0
Suseika/inflectible,Suseika/liblexeme
/** * The MIT License (MIT) * * Copyright (c) 2015 Georgy Vlasov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.tendiwa.inflectible.antlr.parsed; import com.google.common.base.Joiner; import java.io.IOException; import java.io.InputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.apache.commons.io.IOUtils; import org.tendiwa.inflectible.antlr.TemplateBundleLexer; import org.tendiwa.inflectible.antlr.TemplateBundleParser; /** * A convenience descendant of {@link TemplateBundleParser} created from an * {@link InputStream} without explicitly specifying any additional plumbing. * @author Georgy Vlasov ([email protected]) * @version $Id$ * @since 0.1.0 */ public final class BasicTemplateBundleParser extends TemplateBundleParser { /** * Ctor. * @param mode Identifier of a lexer mode to start at. Identifiers are * static fields of the generated class {@link TemplateBundleLexer}. * @param input Input stream with templates' markup * @throws IOException If can't read the input stream */ public BasicTemplateBundleParser( final int mode, final InputStream input ) throws IOException { super( new CommonTokenStream( new BasicTemplateBundleLexer(mode, input) ) ); } /** * Ctor. * @param input Input Input stream with templates' markup * @throws IOException If can't read the input stream */ public BasicTemplateBundleParser( final InputStream input ) throws IOException { this(TemplateBundleLexer.DEFAULT_MODE, input); } /** * Ctor. * @param mode Starting lexer mode * @param markup Templates' markup * @throws IOException If can't read the input stream */ public BasicTemplateBundleParser( final int mode, final String... markup ) throws IOException { this( mode, IOUtils.toInputStream( Joiner.on('\n').join(markup) ) ); } }
src/main/java/org/tendiwa/inflectible/antlr/parsed/BasicTemplateBundleParser.java
/** * The MIT License (MIT) * * Copyright (c) 2015 Georgy Vlasov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.tendiwa.inflectible.antlr.parsed; import com.google.common.base.Joiner; import java.io.IOException; import java.io.InputStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.apache.commons.io.IOUtils; import org.tendiwa.inflectible.antlr.TemplateBundleLexer; import org.tendiwa.inflectible.antlr.TemplateBundleParser; /** * A convenience descendant of {@link TemplateBundleParser} created from an * {@link InputStream} without explicitly specifying any additional plumbing. * @author Georgy Vlasov ([email protected]) * @version $Id$ * @since 0.1.0 */ public final class BasicTemplateBundleParser extends TemplateBundleParser { /** * Ctor. * @param input Input stream with templates' markup. * @throws IOException If can't read the input stream */ public BasicTemplateBundleParser( final InputStream input ) throws IOException { super( new CommonTokenStream( new TemplateBundleLexer( new ANTLRInputStream(input) ) ) ); } /** * Ctor. * @param markup Templates' markup * @throws IOException If can't read the input stream */ public BasicTemplateBundleParser( final String... markup ) throws IOException { this( IOUtils.toInputStream( Joiner.on('\n').join(markup) ) ); } }
#150 Add more constructors to BasicTemplateBundleParser
src/main/java/org/tendiwa/inflectible/antlr/parsed/BasicTemplateBundleParser.java
#150 Add more constructors to BasicTemplateBundleParser
<ide><path>rc/main/java/org/tendiwa/inflectible/antlr/parsed/BasicTemplateBundleParser.java <ide> import com.google.common.base.Joiner; <ide> import java.io.IOException; <ide> import java.io.InputStream; <del>import org.antlr.v4.runtime.ANTLRInputStream; <ide> import org.antlr.v4.runtime.CommonTokenStream; <ide> import org.apache.commons.io.IOUtils; <ide> import org.tendiwa.inflectible.antlr.TemplateBundleLexer; <ide> public final class BasicTemplateBundleParser extends TemplateBundleParser { <ide> /** <ide> * Ctor. <del> * @param input Input stream with templates' markup. <add> * @param mode Identifier of a lexer mode to start at. Identifiers are <add> * static fields of the generated class {@link TemplateBundleLexer}. <add> * @param input Input stream with templates' markup <ide> * @throws IOException If can't read the input stream <ide> */ <ide> public BasicTemplateBundleParser( <add> final int mode, <ide> final InputStream input <ide> ) throws IOException { <ide> super( <ide> new CommonTokenStream( <del> new TemplateBundleLexer( <del> new ANTLRInputStream(input) <del> ) <add> new BasicTemplateBundleLexer(mode, input) <ide> ) <ide> ); <ide> } <ide> <ide> /** <ide> * Ctor. <add> * @param input Input Input stream with templates' markup <add> * @throws IOException If can't read the input stream <add> */ <add> public BasicTemplateBundleParser( <add> final InputStream input <add> ) throws IOException { <add> this(TemplateBundleLexer.DEFAULT_MODE, input); <add> } <add> <add> /** <add> * Ctor. <add> * @param mode Starting lexer mode <ide> * @param markup Templates' markup <ide> * @throws IOException If can't read the input stream <ide> */ <ide> public BasicTemplateBundleParser( <add> final int mode, <ide> final String... markup <ide> ) throws IOException { <ide> this( <add> mode, <ide> IOUtils.toInputStream( <ide> Joiner.on('\n').join(markup) <ide> )
JavaScript
apache-2.0
9397ac1e043434f03916150563deb3ff46eb354d
0
modulexcite/experience-sampling,googlearchive/experience-sampling,modulexcite/experience-sampling,adrifelt/experience-sampling,googlearchive/experience-sampling,modulexcite/experience-sampling,adrifelt/experience-sampling,adrifelt/experience-sampling,googlearchive/experience-sampling
/** * Experience Sampling event page. * * This background page handles the various events for registering participants * and showing new surveys in response to API events. * * Participants must fill out both a consent form and a startup survey (with * demographics) before they can begin to answer real survey questions. */ /** * cesp namespace. */ var cesp = cesp || {}; cesp.openTabId = -1; // Settings. cesp.NOTIFICATION_TITLE = 'Take a Chrome user experience survey!'; cesp.NOTIFICATION_BODY = 'Your feedback makes Chrome better.'; cesp.NOTIFICATION_BUTTON = 'Take survey!'; cesp.NOTIFICATION_CONSENT_LINK = 'What is this?'; cesp.MAX_SURVEYS_PER_DAY = 2; cesp.MAX_SURVEYS_PER_WEEK = 4; cesp.ICON_FILE = 'icons/cues_85.png'; cesp.NOTIFICATION_DEFAULT_TIMEOUT = 10; // minutes cesp.NOTIFICATION_TAG = 'chromeSurvey'; cesp.SURVEY_THROTTLE_DAILY_RESET_ALARM = 'dailySurveyCountReset'; cesp.SURVEY_THROTTLE_WEEKLY_RESET_ALARM = 'weeklySurveyCountReset'; cesp.NOTIFICATION_ALARM_NAME = 'notificationTimeout'; cesp.UNINSTALL_ALARM_NAME = 'uninstallAlarm'; cesp.READY_FOR_SURVEYS = 'readyForSurveys'; cesp.PARTICIPANT_ID_LOOKUP = 'participantId'; cesp.LAST_NOTIFICATION_TIME = 'lastNotificationTime'; cesp.MINIMUM_SURVEY_DELAY = 300000; // 5 minutes in ms. cesp.FIRST_SURVEY_READY = 'firstSurveyReady'; cesp.FIRST_SURVEY_DELAY_LENGTH = 40; // minutes // SETUP /** * A helper method for updating the value in local storage. * @param {bool} newState The desired new state for the ready for surveys flag. */ function setReadyForSurveysStorageValue(newState) { var items = {}; items[cesp.READY_FOR_SURVEYS] = newState; chrome.storage.sync.set(items); } /** * A helper method for updating the value in local storage. * @param {int} newCount The desired new survey count value. */ function setSurveysShownDaily(newCount) { var items = {}; items[cesp.SURVEYS_SHOWN_TODAY] = newCount; chrome.storage.sync.set(items); } /** * A helper method for updating the value in local storage. * @param {bool} newState The desired new state for the first survey readiness. */ function setFirstSurveyReady(newState) { var items = {}; items[cesp.FIRST_SURVEY_READY] = newState; chrome.storage.sync.set(items); } /** * A helper method for updating the value in local storage. * @param {int} newCount The desired new survey count value. */ function setSurveysShownWeekly(newCount) { var items = {}; items[cesp.SURVEYS_SHOWN_THIS_WEEK] = newCount; chrome.storage.sync.set(items); } /** * Resets the last notification time value in local storage to the current time. */ function resetLastNotificationTimeStorageValue() { var items = {}; items[cesp.LAST_NOTIFICATION_TIME] = Date.now(); chrome.storage.sync.set(items); } /** * Sets up basic state for the extension. Called when extension is installed. * @param {object} details The details of the chrome.runtime.onInstalled event. */ function setupState(details) { // We check the event reason because onInstalled can trigger for other // reasons (extension or browser update). if (details.reason !== 'install') return; setReadyForSurveysStorageValue(false); // Automatically uninstall the extension after 120 days. chrome.alarms.create(cesp.UNINSTALL_ALARM_NAME, {delayInMinutes: 172800}); // Set the count of surveys shown to 0. Reset it each day/week at midnight. setSurveysShownDaily(0); setSurveysShownWeekly(0); setFirstSurveyReady(false); var midnight = new Date(); midnight.setHours(0, 0, 0, 0); chrome.alarms.create(cesp.SURVEY_THROTTLE_DAILY_RESET_ALARM, {when: midnight.getTime(), periodInMinutes: 1440}); chrome.alarms.create(cesp.SURVEY_THROTTLE_WEEKLY_RESET_ALARM, {when: midnight.getTime(), periodInMinutes: 10080}); // Process the pending survey submission queue every 20 minutes. chrome.alarms.create(SurveySubmission.QUEUE_ALARM_NAME, {delayInMinutes: 1, periodInMinutes: 20}); } /** * Handles the uninstall alarm. * @param {Alarm} alarm The alarm object from the onAlarm event. */ function handleUninstallAlarm(alarm) { if (alarm.name === cesp.UNINSTALL_ALARM_NAME) chrome.management.uninstallSelf(); } chrome.alarms.onAlarm.addListener(handleUninstallAlarm); /** * Resets the count of surveys shown today to 0. * @param {Alarm} alarm The alarm object from the onAlarm event. */ function resetSurveyDailyCount(alarm) { if (alarm.name === cesp.SURVEY_THROTTLE_DAILY_RESET_ALARM) setSurveysShownDaily(0); } chrome.alarms.onAlarm.addListener(resetSurveyDailyCount); /** * Resets the count of surveys shown this week to 0. * @param {Alarm} alarm The alarm object from the onAlarm event. */ function resetSurveyWeeklyCount(alarm) { if (alarm.name === cesp.SURVEY_THROTTLE_WEEKLY_RESET_ALARM) setSurveysShownWeekly(0); } chrome.alarms.onAlarm.addListener(resetSurveyWeeklyCount); /** * Checks whether participant has granted consent and/or completed the * demographic survey. If not, get the participant started. */ function maybeShowConsentOrSetupSurvey() { var setupCallback = function(lookup) { if (!lookup || !lookup[constants.SETUP_KEY] || lookup[constants.SETUP_KEY] === constants.SETUP_PENDING) { getOperatingSystem().then(function(os) { chrome.tabs.create( {'url': chrome.extension.getURL('surveys/setup.html?os=' + os)}); }); } else if (lookup[constants.SETUP_KEY] === constants.SETUP_COMPLETED) { setReadyForSurveysStorageValue(true); } }; var consentCallback = function(lookup) { if (!lookup || !lookup[constants.CONSENT_KEY] || lookup[constants.CONSENT_KEY] === constants.CONSENT_PENDING) { getOperatingSystem().then(function(os) { chrome.tabs.create( {'url': chrome.extension.getURL('consent.html?os=' + os)}); }); } else if (lookup[constants.CONSENT_KEY] === constants.CONSENT_REJECTED) { chrome.management.uninstallSelf(); } else if (lookup[constants.CONSENT_KEY] === constants.CONSENT_GRANTED) { // Someone might have filled out the consent form previously but not // filled out the setup survey. Check to see if that's the case. chrome.storage.sync.get(constants.SETUP_KEY, setupCallback); } }; chrome.storage.sync.get(constants.CONSENT_KEY, consentCallback); } /** * Listens for the setup survey submission. When that happens, signals that * the experience sampling is now ready to begin. * @param {object} changes The changed portions of the database. * @param {string} areaName The name of the storage area. */ function storageUpdated(changes, areaName) { if (!changes) return; if (changes[constants.CONSENT_KEY] && changes[constants.CONSENT_KEY].newValue === constants.CONSENT_GRANTED) { chrome.runtime.sendMessage({ 'message_type': constants.MSG_CONSENT }); } if (changes[constants.SETUP_KEY] && changes[constants.SETUP_KEY].newValue === constants.SETUP_COMPLETED) { setReadyForSurveysStorageValue(true); chrome.runtime.sendMessage({ 'message_type': constants.MSG_SETUP }); chrome.alarms.create(cesp.FIRST_SURVEY_READY, {delayInMinutes: cesp.FIRST_SURVEY_DELAY_LENGTH}); } } chrome.storage.onChanged.addListener(storageUpdated); // Performs consent and registration checks on startup and install. chrome.runtime.onInstalled.addListener(maybeShowConsentOrSetupSurvey); chrome.runtime.onStartup.addListener(maybeShowConsentOrSetupSurvey); chrome.runtime.onInstalled.addListener(setupState); // GETTERS /** * A helper method for getting (or, if necessary, setting) the participant ID. * @returns {Promise} A promise that resolves with the participant ID. */ function getParticipantId() { return new Promise(function(resolve, reject) { chrome.storage.sync.get(cesp.PARTICIPANT_ID_LOOKUP, function(lookup) { if (lookup && lookup[cesp.PARTICIPANT_ID_LOOKUP]) { resolve(lookup[cesp.PARTICIPANT_ID_LOOKUP]); return; } var charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var participantId = ''; for (var i = 0; i < 100; i++) { var rand = Math.floor(Math.random() * charset.length); participantId += charset.charAt(rand); } var items = {}; items[cesp.PARTICIPANT_ID_LOOKUP] = participantId; chrome.storage.sync.set(items); resolve(participantId); }); }); } /** * A helper method for getting the operating system. * @returns {Promise} A promise that resolves with the operating system. */ function getOperatingSystem() { return new Promise(function(resolve, reject) { chrome.runtime.getPlatformInfo(function(platformInfo) { resolve(platformInfo.os); }); }); } // TRIGGERING THE FIRST SURVEY (HTTP OR HTTPS) /** * Ensures the first (HTTP vs HTTPS) survey is completely ended. It should stop * being available once the user takes it, or once the user takes any other * survey. */ function endFirstSurvey() { setFirstSurveyReady(false); chrome.tabs.onUpdated.removeListener(handleTabUpdated); chrome.alarms.onAlarm.removeListener(lookForFirstSurveyEvent); chrome.alarms.clear(cesp.FIRST_SURVEY_READY); }; /** * After the initial wait time has completed, begin watching for potential * events. * @param {Alarm} alarm An alarm that may or may not be from the right timer. */ function lookForFirstSurveyEvent(alarm) { if (alarm.name !== cesp.FIRST_SURVEY_READY) return; setFirstSurveyReady(true); }; chrome.alarms.onAlarm.addListener(lookForFirstSurveyEvent); /** * Look to see if a tab updated event would be appropriate for a survey. If so, * fire a notification with an element and decision. * @param {int} tabId The ID of the tab that was updated. * @param {Object} changeInfo Information about the update event. * @param {Tab} tab The tab that was updated. */ function handleTabUpdated(tabId, changeInfo, tab) { chrome.storage.sync.get(cesp.FIRST_SURVEY_READY, function(items) { if (!items || !items[cesp.FIRST_SURVEY_READY]) return; // Only survey about HTTP and HTTPS navigations. if (!tab.url) return; var scheme = tab.url.split(':')[0]; if (scheme !== 'https' && scheme !== 'http') return; if (scheme === 'https' && !urlHandler.IsGreenLockSite(tab.url)) return; var timeFired = Date.now(); var element = { destination: tab.url, name: scheme, referrer: '', time: timeFired }; var decision = { details: false, learn_more: false, name: 'N/A', time: timeFired }; endFirstSurvey(); showSurveyNotification(element, decision); }); }; chrome.tabs.onUpdated.addListener(handleTabUpdated); // SURVEY HANDLING /** * Clears our existing notification(s). * @param {Alarm} alarm The alarm object from the onAlarm event (optional). */ function clearNotifications(alarm) { if (alarm && alarm.name !== cesp.NOTIFICATION_ALARM_NAME) return; chrome.notifications.clear(cesp.NOTIFICATION_TAG, function(unused) {}); chrome.alarms.clear(cesp.NOTIFICATION_ALARM_NAME); } // Clear the notification state when the survey times out. chrome.alarms.onAlarm.addListener(clearNotifications); /** * Creates a new notification to prompt the participant to take an experience * sampling survey. * @param {object} element The browser element of interest. * @param {object} decision The decision the participant made. */ function showSurveyNotification(element, decision) { var eventType = constants.FindEventType(element['name']); switch (eventType) { case constants.EventType.SSL_OVERRIDABLE: case constants.EventType.SSL_NONOVERRIDABLE: case constants.EventType.MALWARE: case constants.EventType.PHISHING: case constants.EventType.EXTENSION_INSTALL: case constants.EventType.EXTENSION_BUNDLE: case constants.EventType.VISITED_HTTPS: case constants.EventType.VISITED_HTTP: // Supported events. break; case constants.EventType.EXTENSION_INLINE_INSTALL: // Don't survey for an inline install if the user cancels. // See https://github.com/GoogleChrome/experience-sampling/issues/74. if (decision['name'] === constants.DecisionType.DENY) return; break; case constants.EventType.HARMFUL: case constants.EventType.SB_OTHER: case constants.EventType.DOWNLOAD_MALICIOUS: case constants.EventType.DOWNLOAD_DANGEROUS: case constants.EventType.DOWNLOAD_DANGER_PROMPT: case constants.EventType.EXTENSION_OTHER: case constants.EventType.UNKNOWN: default: // Unsupported events. return; } chrome.storage.sync.get([cesp.READY_FOR_SURVEYS, cesp.LAST_NOTIFICATION_TIME], function(items) { if (!items[cesp.READY_FOR_SURVEYS]) return; // If we've shown a notification less than MINIMUM_SURVEY_DELAY ago, stop. if (items[cesp.LAST_NOTIFICATION_TIME] && Date.now() - items[cesp.LAST_NOTIFICATION_TIME] < cesp.MINIMUM_SURVEY_DELAY) return; chrome.storage.sync.get(cesp.SURVEYS_SHOWN_TODAY, function(today) { if (today[cesp.SURVEYS_SHOWN_TODAY] >= cesp.MAX_SURVEYS_PER_DAY) return; chrome.storage.sync.get(cesp.SURVEYS_SHOWN_THIS_WEEK, function(week) { if (week[cesp.SURVEYS_SHOWN_THIS_WEEK] >= cesp.MAX_SURVEYS_PER_WEEK) return; clearNotifications(); recordShowedNotification(eventType); endFirstSurvey(); var timePromptShown = new Date(); var clickHandler = function(notificationId, buttonIndex) { var timePromptClicked = new Date(); var maybeOpenConsentForm = function() { if (buttonIndex != 1) return; chrome.tabs.create({ 'url': chrome.extension.getURL('consent.html') }); }; loadSurvey(element, decision, timePromptShown, timePromptClicked) .then(maybeOpenConsentForm, maybeOpenConsentForm); clearNotifications(); }; var options = { type: 'basic', iconUrl: cesp.ICON_FILE, title: cesp.NOTIFICATION_TITLE, message: cesp.NOTIFICATION_BODY, eventTime: Date.now(), buttons: [ {title: cesp.NOTIFICATION_BUTTON}, {title: cesp.NOTIFICATION_CONSENT_LINK} ], isClickable: true }; chrome.notifications.create( cesp.NOTIFICATION_TAG, options, function(id) { chrome.alarms.create( cesp.NOTIFICATION_ALARM_NAME, {delayInMinutes: cesp.NOTIFICATION_DEFAULT_TIMEOUT}); }); chrome.notifications.onClicked.addListener(clickHandler); chrome.notifications.onButtonClicked.addListener(clickHandler); setSurveysShownDaily(items[cesp.SURVEYS_SHOWN_TODAY] + 1); setSurveysShownWeekly(items[cesp.SURVEYS_SHOWN_THIS_WEEK] + 1); resetLastNotificationTimeStorageValue(); }); }); }); } /** * Creates a new tab with the experience sampling survey page. * @param {object} element The browser element of interest. * @param {object} decision The decision the participant made. * @param {object} timePromptShown Date object of when the survey prompt * notification was shown to the participant. * @param {object} timePromptClicked Date object of when the participant * clicked the survey prompt notification. * @returns {Promise} A promise that resolves when the survey is done opening. */ function loadSurvey(element, decision, timePromptShown, timePromptClicked) { return new Promise(function(resolve, reject) { chrome.storage.sync.get(cesp.READY_FOR_SURVEYS, function(items) { if (!items[cesp.READY_FOR_SURVEYS]) { reject(); return; } var userDecision = decision['name']; if (userDecision !== constants.DecisionType.PROCEED && userDecision !== constants.DecisionType.DENY && userDecision !== constants.DecisionType.NA) { reject(); return; } var surveyUrl, visitUrl; var eventType = constants.FindEventType(element['name']); switch (eventType) { case constants.EventType.SSL_OVERRIDABLE: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.SSL_OVERRIDABLE_PROCEED : constants.SurveyLocation.SSL_OVERRIDABLE_NOPROCEED; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.SSL_NONOVERRIDABLE: surveyUrl = constants.SurveyLocation.SSL_NONOVERRIDABLE; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.MALWARE: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.MALWARE_PROCEED : constants.SurveyLocation.MALWARE_NOPROCEED; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.PHISHING: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.PHISHING_PROCEED : constants.SurveyLocation.PHISHING_NOPROCEED; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.EXTENSION_INSTALL: case constants.EventType.EXTENSION_INLINE_INSTALL: case constants.EventType.EXTENSION_BUNDLE: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.EXTENSION_PROCEED : constants.SurveyLocation.EXTENSION_NOPROCEED; break; case constants.EventType.VISITED_HTTPS: surveyUrl = constants.SurveyLocation.VISITED_HTTPS; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.VISITED_HTTP: surveyUrl = constants.SurveyLocation.VISITED_HTTP; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.HARMFUL: case constants.EventType.SB_OTHER: case constants.EventType.DOWNLOAD_MALICIOUS: case constants.EventType.DOWNLOAD_DANGEROUS: case constants.EventType.DOWNLOAD_DANGER_PROMPT: case constants.EventType.EXTENSION_OTHER: // Don't survey about these. reject(); return; case constants.EventType.UNKNOWN: throw new Error('Unknown event type: ' + element['name']); reject(); return; } getOperatingSystem().then(function(os) { visitUrl = encodeURIComponent(visitUrl); var openUrl = 'surveys/survey.html?js=' + surveyUrl + '&url=' + visitUrl + '&os=' + os; chrome.tabs.create( {'url': chrome.extension.getURL(openUrl)}, function(tab) { try { chrome.tabs.remove(cesp.openTabId); } catch (err) { } cesp.openTabId = tab.id; resolve(); }); }); }); }); } /** * Record basic information about the event. * @param {object} element The browser element of interest. * @param {object} decision The decision the participant made. */ function recordEvent(element, decision) { var responses = []; responses.push(new SurveySubmission.Response( 'MANUFACTURED', 'Recording event')); responses.push(new SurveySubmission.Response( 'Full event type', element['name'])); responses.push(new SurveySubmission.Response( 'Response', decision['name'])); responses.push(new SurveySubmission.Response( 'Details', decision['details'].toString())); responses.push(new SurveySubmission.Response( 'Learn more', decision['learn_more'].toString())); getParticipantId().then(function(participantId) { var record = new SurveySubmission.SurveyRecord( constants.FindEventType(element['name']), participantId, (new Date), responses); SurveySubmission.saveSurveyRecord(record); }); } /** * Record that a notification was displayed. * @param {string} eventType The event type (one of constants.EventType) */ function recordShowedNotification(eventType) { var responses = []; responses.push(new SurveySubmission.Response( 'MANUFACTURED', 'Showed notification')); getParticipantId().then(function(participantId) { var record = new SurveySubmission.SurveyRecord( eventType, participantId, (new Date), responses); SurveySubmission.saveSurveyRecord(record); }); } // Trigger the new survey prompt and record the event when the participant // makes a decision about an experience sampling element. chrome.experienceSamplingPrivate.onDecision.addListener(showSurveyNotification); chrome.experienceSamplingPrivate.onDecision.addListener(recordEvent); /** * Handle the submission of a completed survey. */ function handleCompletedSurvey(message) { if (message[constants.MSG_TYPE] !== constants.MSG_SURVEY) return; getParticipantId().then(function(participantId) { var record = new SurveySubmission.SurveyRecord( message['survey_type'], participantId, (new Date), message['responses']); SurveySubmission.saveSurveyRecord(record); }); } chrome.runtime.onMessage.addListener(handleCompletedSurvey);
extension/background.js
/** * Experience Sampling event page. * * This background page handles the various events for registering participants * and showing new surveys in response to API events. * * Participants must fill out both a consent form and a startup survey (with * demographics) before they can begin to answer real survey questions. */ /** * cesp namespace. */ var cesp = cesp || {}; cesp.openTabId = -1; // Settings. cesp.NOTIFICATION_TITLE = 'Take a Chrome user experience survey!'; cesp.NOTIFICATION_BODY = 'Your feedback makes Chrome better.'; cesp.NOTIFICATION_BUTTON = 'Take survey!'; cesp.NOTIFICATION_CONSENT_LINK = 'What is this?'; cesp.MAX_SURVEYS_PER_DAY = 2; cesp.MAX_SURVEYS_PER_WEEK = 4; cesp.ICON_FILE = 'icons/cues_85.png'; cesp.NOTIFICATION_DEFAULT_TIMEOUT = 10; // minutes cesp.NOTIFICATION_TAG = 'chromeSurvey'; cesp.SURVEY_THROTTLE_DAILY_RESET_ALARM = 'dailySurveyCountReset'; cesp.SURVEY_THROTTLE_WEEKLY_RESET_ALARM = 'weeklySurveyCountReset'; cesp.NOTIFICATION_ALARM_NAME = 'notificationTimeout'; cesp.UNINSTALL_ALARM_NAME = 'uninstallAlarm'; cesp.READY_FOR_SURVEYS = 'readyForSurveys'; cesp.PARTICIPANT_ID_LOOKUP = 'participantId'; cesp.LAST_NOTIFICATION_TIME = 'lastNotificationTime'; cesp.MINIMUM_SURVEY_DELAY = 300000; // 5 minutes in ms. cesp.FIRST_SURVEY_READY = 'firstSurveyReady'; cesp.FIRST_SURVEY_DELAY_LENGTH = 1;//40; // minutes // SETUP /** * A helper method for updating the value in local storage. * @param {bool} newState The desired new state for the ready for surveys flag. */ function setReadyForSurveysStorageValue(newState) { var items = {}; items[cesp.READY_FOR_SURVEYS] = newState; chrome.storage.sync.set(items); } /** * A helper method for updating the value in local storage. * @param {int} newCount The desired new survey count value. */ function setSurveysShownDaily(newCount) { var items = {}; items[cesp.SURVEYS_SHOWN_TODAY] = newCount; chrome.storage.sync.set(items); } /** * A helper method for updating the value in local storage. * @param {bool} newState The desired new state for the first survey readiness. */ function setFirstSurveyReady(newState) { var items = {}; items[cesp.FIRST_SURVEY_READY] = newState; chrome.storage.sync.set(items); } /** * A helper method for updating the value in local storage. * @param {int} newCount The desired new survey count value. */ function setSurveysShownWeekly(newCount) { var items = {}; items[cesp.SURVEYS_SHOWN_THIS_WEEK] = newCount; chrome.storage.sync.set(items); } /** * Resets the last notification time value in local storage to the current time. */ function resetLastNotificationTimeStorageValue() { var items = {}; items[cesp.LAST_NOTIFICATION_TIME] = Date.now(); chrome.storage.sync.set(items); } /** * Sets up basic state for the extension. Called when extension is installed. * @param {object} details The details of the chrome.runtime.onInstalled event. */ function setupState(details) { // We check the event reason because onInstalled can trigger for other // reasons (extension or browser update). if (details.reason !== 'install') return; setReadyForSurveysStorageValue(false); // Automatically uninstall the extension after 120 days. chrome.alarms.create(cesp.UNINSTALL_ALARM_NAME, {delayInMinutes: 172800}); // Set the count of surveys shown to 0. Reset it each day/week at midnight. setSurveysShownDaily(0); setSurveysShownWeekly(0); setFirstSurveyReady(false); var midnight = new Date(); midnight.setHours(0, 0, 0, 0); chrome.alarms.create(cesp.SURVEY_THROTTLE_DAILY_RESET_ALARM, {when: midnight.getTime(), periodInMinutes: 1440}); chrome.alarms.create(cesp.SURVEY_THROTTLE_WEEKLY_RESET_ALARM, {when: midnight.getTime(), periodInMinutes: 10080}); // Process the pending survey submission queue every 20 minutes. chrome.alarms.create(SurveySubmission.QUEUE_ALARM_NAME, {delayInMinutes: 1, periodInMinutes: 20}); } /** * Handles the uninstall alarm. * @param {Alarm} alarm The alarm object from the onAlarm event. */ function handleUninstallAlarm(alarm) { if (alarm.name === cesp.UNINSTALL_ALARM_NAME) chrome.management.uninstallSelf(); } chrome.alarms.onAlarm.addListener(handleUninstallAlarm); /** * Resets the count of surveys shown today to 0. * @param {Alarm} alarm The alarm object from the onAlarm event. */ function resetSurveyDailyCount(alarm) { if (alarm.name === cesp.SURVEY_THROTTLE_DAILY_RESET_ALARM) setSurveysShownDaily(0); } chrome.alarms.onAlarm.addListener(resetSurveyDailyCount); /** * Resets the count of surveys shown this week to 0. * @param {Alarm} alarm The alarm object from the onAlarm event. */ function resetSurveyWeeklyCount(alarm) { if (alarm.name === cesp.SURVEY_THROTTLE_WEEKLY_RESET_ALARM) setSurveysShownWeekly(0); } chrome.alarms.onAlarm.addListener(resetSurveyWeeklyCount); /** * Checks whether participant has granted consent and/or completed the * demographic survey. If not, get the participant started. */ function maybeShowConsentOrSetupSurvey() { var setupCallback = function(lookup) { if (!lookup || !lookup[constants.SETUP_KEY] || lookup[constants.SETUP_KEY] === constants.SETUP_PENDING) { getOperatingSystem().then(function(os) { chrome.tabs.create( {'url': chrome.extension.getURL('surveys/setup.html?os=' + os)}); }); } else if (lookup[constants.SETUP_KEY] === constants.SETUP_COMPLETED) { setReadyForSurveysStorageValue(true); } }; var consentCallback = function(lookup) { if (!lookup || !lookup[constants.CONSENT_KEY] || lookup[constants.CONSENT_KEY] === constants.CONSENT_PENDING) { getOperatingSystem().then(function(os) { chrome.tabs.create( {'url': chrome.extension.getURL('consent.html?os=' + os)}); }); } else if (lookup[constants.CONSENT_KEY] === constants.CONSENT_REJECTED) { chrome.management.uninstallSelf(); } else if (lookup[constants.CONSENT_KEY] === constants.CONSENT_GRANTED) { // Someone might have filled out the consent form previously but not // filled out the setup survey. Check to see if that's the case. chrome.storage.sync.get(constants.SETUP_KEY, setupCallback); } }; chrome.storage.sync.get(constants.CONSENT_KEY, consentCallback); } /** * Listens for the setup survey submission. When that happens, signals that * the experience sampling is now ready to begin. * @param {object} changes The changed portions of the database. * @param {string} areaName The name of the storage area. */ function storageUpdated(changes, areaName) { if (!changes) return; if (changes[constants.CONSENT_KEY] && changes[constants.CONSENT_KEY].newValue === constants.CONSENT_GRANTED) { chrome.runtime.sendMessage({ 'message_type': constants.MSG_CONSENT }); } if (changes[constants.SETUP_KEY] && changes[constants.SETUP_KEY].newValue === constants.SETUP_COMPLETED) { setReadyForSurveysStorageValue(true); chrome.runtime.sendMessage({ 'message_type': constants.MSG_SETUP }); chrome.alarms.create(cesp.FIRST_SURVEY_READY, {delayInMinutes: cesp.FIRST_SURVEY_DELAY_LENGTH}); } } chrome.storage.onChanged.addListener(storageUpdated); // Performs consent and registration checks on startup and install. chrome.runtime.onInstalled.addListener(maybeShowConsentOrSetupSurvey); chrome.runtime.onStartup.addListener(maybeShowConsentOrSetupSurvey); chrome.runtime.onInstalled.addListener(setupState); // GETTERS /** * A helper method for getting (or, if necessary, setting) the participant ID. * @returns {Promise} A promise that resolves with the participant ID. */ function getParticipantId() { return new Promise(function(resolve, reject) { chrome.storage.sync.get(cesp.PARTICIPANT_ID_LOOKUP, function(lookup) { if (lookup && lookup[cesp.PARTICIPANT_ID_LOOKUP]) { resolve(lookup[cesp.PARTICIPANT_ID_LOOKUP]); return; } var charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var participantId = ''; for (var i = 0; i < 100; i++) { var rand = Math.floor(Math.random() * charset.length); participantId += charset.charAt(rand); } var items = {}; items[cesp.PARTICIPANT_ID_LOOKUP] = participantId; chrome.storage.sync.set(items); resolve(participantId); }); }); } /** * A helper method for getting the operating system. * @returns {Promise} A promise that resolves with the operating system. */ function getOperatingSystem() { return new Promise(function(resolve, reject) { chrome.runtime.getPlatformInfo(function(platformInfo) { resolve(platformInfo.os); }); }); } // TRIGGERING THE FIRST SURVEY (HTTP OR HTTPS) /** * Ensures the first (HTTP vs HTTPS) survey is completely ended. It should stop * being available once the user takes it, or once the user takes any other * survey. */ function endFirstSurvey() { setFirstSurveyReady(false); chrome.tabs.onUpdated.removeListener(handleTabUpdated); chrome.alarms.onAlarm.removeListener(lookForFirstSurveyEvent); chrome.alarms.clear(cesp.FIRST_SURVEY_READY); }; /** * After the initial wait time has completed, begin watching for potential * events. * @param {Alarm} alarm An alarm that may or may not be from the right timer. */ function lookForFirstSurveyEvent(alarm) { if (alarm.name !== cesp.FIRST_SURVEY_READY) return; setFirstSurveyReady(true); }; chrome.alarms.onAlarm.addListener(lookForFirstSurveyEvent); /** * Look to see if a tab updated event would be appropriate for a survey. If so, * fire a notification with an element and decision. * @param {int} tabId The ID of the tab that was updated. * @param {Object} changeInfo Information about the update event. * @param {Tab} tab The tab that was updated. */ function handleTabUpdated(tabId, changeInfo, tab) { chrome.storage.sync.get(cesp.FIRST_SURVEY_READY, function(items) { if (!items || !items[cesp.FIRST_SURVEY_READY]) return; // Only survey about HTTP and HTTPS navigations. if (!tab.url) return; var scheme = tab.url.split(':')[0]; if (scheme !== 'https' && scheme !== 'http') return; if (scheme === 'https' && !urlHandler.IsGreenLockSite(tab.url)) return; var timeFired = Date.now(); var element = { destination: tab.url, name: scheme, referrer: '', time: timeFired }; var decision = { details: false, learn_more: false, name: 'N/A', time: timeFired }; endFirstSurvey(); showSurveyNotification(element, decision); }); }; chrome.tabs.onUpdated.addListener(handleTabUpdated); // SURVEY HANDLING /** * Clears our existing notification(s). * @param {Alarm} alarm The alarm object from the onAlarm event (optional). */ function clearNotifications(alarm) { if (alarm && alarm.name !== cesp.NOTIFICATION_ALARM_NAME) return; chrome.notifications.clear(cesp.NOTIFICATION_TAG, function(unused) {}); chrome.alarms.clear(cesp.NOTIFICATION_ALARM_NAME); } // Clear the notification state when the survey times out. chrome.alarms.onAlarm.addListener(clearNotifications); /** * Creates a new notification to prompt the participant to take an experience * sampling survey. * @param {object} element The browser element of interest. * @param {object} decision The decision the participant made. */ function showSurveyNotification(element, decision) { var eventType = constants.FindEventType(element['name']); switch (eventType) { case constants.EventType.SSL_OVERRIDABLE: case constants.EventType.SSL_NONOVERRIDABLE: case constants.EventType.MALWARE: case constants.EventType.PHISHING: case constants.EventType.EXTENSION_INSTALL: case constants.EventType.EXTENSION_BUNDLE: case constants.EventType.VISITED_HTTPS: case constants.EventType.VISITED_HTTP: // Supported events. break; case constants.EventType.EXTENSION_INLINE_INSTALL: // Don't survey for an inline install if the user cancels. // See https://github.com/GoogleChrome/experience-sampling/issues/74. if (decision['name'] === constants.DecisionType.DENY) return; break; case constants.EventType.HARMFUL: case constants.EventType.SB_OTHER: case constants.EventType.DOWNLOAD_MALICIOUS: case constants.EventType.DOWNLOAD_DANGEROUS: case constants.EventType.DOWNLOAD_DANGER_PROMPT: case constants.EventType.EXTENSION_OTHER: case constants.EventType.UNKNOWN: default: // Unsupported events. return; } chrome.storage.sync.get([cesp.READY_FOR_SURVEYS, cesp.LAST_NOTIFICATION_TIME], function(items) { if (!items[cesp.READY_FOR_SURVEYS]) return; // If we've shown a notification less than MINIMUM_SURVEY_DELAY ago, stop. if (items[cesp.LAST_NOTIFICATION_TIME] && Date.now() - items[cesp.LAST_NOTIFICATION_TIME] < cesp.MINIMUM_SURVEY_DELAY) return; chrome.storage.sync.get(cesp.SURVEYS_SHOWN_TODAY, function(today) { if (today[cesp.SURVEYS_SHOWN_TODAY] >= cesp.MAX_SURVEYS_PER_DAY) return; chrome.storage.sync.get(cesp.SURVEYS_SHOWN_THIS_WEEK, function(week) { if (week[cesp.SURVEYS_SHOWN_THIS_WEEK] >= cesp.MAX_SURVEYS_PER_WEEK) return; clearNotifications(); recordShowedNotification(eventType); endFirstSurvey(); var timePromptShown = new Date(); var clickHandler = function(notificationId, buttonIndex) { var timePromptClicked = new Date(); var maybeOpenConsentForm = function() { if (buttonIndex != 1) return; chrome.tabs.create({ 'url': chrome.extension.getURL('consent.html') }); }; loadSurvey(element, decision, timePromptShown, timePromptClicked) .then(maybeOpenConsentForm, maybeOpenConsentForm); clearNotifications(); }; var options = { type: 'basic', iconUrl: cesp.ICON_FILE, title: cesp.NOTIFICATION_TITLE, message: cesp.NOTIFICATION_BODY, eventTime: Date.now(), buttons: [ {title: cesp.NOTIFICATION_BUTTON}, {title: cesp.NOTIFICATION_CONSENT_LINK} ], isClickable: true }; chrome.notifications.create( cesp.NOTIFICATION_TAG, options, function(id) { chrome.alarms.create( cesp.NOTIFICATION_ALARM_NAME, {delayInMinutes: cesp.NOTIFICATION_DEFAULT_TIMEOUT}); }); chrome.notifications.onClicked.addListener(clickHandler); chrome.notifications.onButtonClicked.addListener(clickHandler); setSurveysShownDaily(items[cesp.SURVEYS_SHOWN_TODAY] + 1); setSurveysShownWeekly(items[cesp.SURVEYS_SHOWN_THIS_WEEK] + 1); resetLastNotificationTimeStorageValue(); }); }); }); } /** * Creates a new tab with the experience sampling survey page. * @param {object} element The browser element of interest. * @param {object} decision The decision the participant made. * @param {object} timePromptShown Date object of when the survey prompt * notification was shown to the participant. * @param {object} timePromptClicked Date object of when the participant * clicked the survey prompt notification. * @returns {Promise} A promise that resolves when the survey is done opening. */ function loadSurvey(element, decision, timePromptShown, timePromptClicked) { return new Promise(function(resolve, reject) { chrome.storage.sync.get(cesp.READY_FOR_SURVEYS, function(items) { if (!items[cesp.READY_FOR_SURVEYS]) { reject(); return; } var userDecision = decision['name']; if (userDecision !== constants.DecisionType.PROCEED && userDecision !== constants.DecisionType.DENY && userDecision !== constants.DecisionType.NA) { reject(); return; } var surveyUrl, visitUrl; var eventType = constants.FindEventType(element['name']); switch (eventType) { case constants.EventType.SSL_OVERRIDABLE: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.SSL_OVERRIDABLE_PROCEED : constants.SurveyLocation.SSL_OVERRIDABLE_NOPROCEED; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.SSL_NONOVERRIDABLE: surveyUrl = constants.SurveyLocation.SSL_NONOVERRIDABLE; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.MALWARE: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.MALWARE_PROCEED : constants.SurveyLocation.MALWARE_NOPROCEED; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.PHISHING: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.PHISHING_PROCEED : constants.SurveyLocation.PHISHING_NOPROCEED; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.EXTENSION_INSTALL: case constants.EventType.EXTENSION_INLINE_INSTALL: case constants.EventType.EXTENSION_BUNDLE: surveyUrl = userDecision === constants.DecisionType.PROCEED ? constants.SurveyLocation.EXTENSION_PROCEED : constants.SurveyLocation.EXTENSION_NOPROCEED; break; case constants.EventType.VISITED_HTTPS: surveyUrl = constants.SurveyLocation.VISITED_HTTPS; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.VISITED_HTTP: surveyUrl = constants.SurveyLocation.VISITED_HTTP; visitUrl = urlHandler.GetMinimalUrl(element['destination']); break; case constants.EventType.HARMFUL: case constants.EventType.SB_OTHER: case constants.EventType.DOWNLOAD_MALICIOUS: case constants.EventType.DOWNLOAD_DANGEROUS: case constants.EventType.DOWNLOAD_DANGER_PROMPT: case constants.EventType.EXTENSION_OTHER: // Don't survey about these. reject(); return; case constants.EventType.UNKNOWN: throw new Error('Unknown event type: ' + element['name']); reject(); return; } getOperatingSystem().then(function(os) { visitUrl = encodeURIComponent(visitUrl); var openUrl = 'surveys/survey.html?js=' + surveyUrl + '&url=' + visitUrl + '&os=' + os; chrome.tabs.create( {'url': chrome.extension.getURL(openUrl)}, function(tab) { try { chrome.tabs.remove(cesp.openTabId); } catch (err) { } cesp.openTabId = tab.id; resolve(); }); }); }); }); } /** * Record basic information about the event. * @param {object} element The browser element of interest. * @param {object} decision The decision the participant made. */ function recordEvent(element, decision) { var responses = []; responses.push(new SurveySubmission.Response( 'MANUFACTURED', 'Recording event')); responses.push(new SurveySubmission.Response( 'Full event type', element['name'])); responses.push(new SurveySubmission.Response( 'Response', decision['name'])); responses.push(new SurveySubmission.Response( 'Details', decision['details'].toString())); responses.push(new SurveySubmission.Response( 'Learn more', decision['learn_more'].toString())); getParticipantId().then(function(participantId) { var record = new SurveySubmission.SurveyRecord( constants.FindEventType(element['name']), participantId, (new Date), responses); SurveySubmission.saveSurveyRecord(record); }); } /** * Record that a notification was displayed. * @param {string} eventType The event type (one of constants.EventType) */ function recordShowedNotification(eventType) { var responses = []; responses.push(new SurveySubmission.Response( 'MANUFACTURED', 'Showed notification')); getParticipantId().then(function(participantId) { var record = new SurveySubmission.SurveyRecord( eventType, participantId, (new Date), responses); SurveySubmission.saveSurveyRecord(record); }); } // Trigger the new survey prompt and record the event when the participant // makes a decision about an experience sampling element. chrome.experienceSamplingPrivate.onDecision.addListener(showSurveyNotification); chrome.experienceSamplingPrivate.onDecision.addListener(recordEvent); /** * Handle the submission of a completed survey. */ function handleCompletedSurvey(message) { if (message[constants.MSG_TYPE] !== constants.MSG_SURVEY) return; getParticipantId().then(function(participantId) { var record = new SurveySubmission.SurveyRecord( message['survey_type'], participantId, (new Date), message['responses']); SurveySubmission.saveSurveyRecord(record); }); } chrome.runtime.onMessage.addListener(handleCompletedSurvey);
remove debug code
extension/background.js
remove debug code
<ide><path>xtension/background.js <ide> cesp.LAST_NOTIFICATION_TIME = 'lastNotificationTime'; <ide> cesp.MINIMUM_SURVEY_DELAY = 300000; // 5 minutes in ms. <ide> cesp.FIRST_SURVEY_READY = 'firstSurveyReady'; <del>cesp.FIRST_SURVEY_DELAY_LENGTH = 1;//40; // minutes <add>cesp.FIRST_SURVEY_DELAY_LENGTH = 40; // minutes <ide> <ide> // SETUP <ide>
Java
agpl-3.0
09305e6626016eb7871341ebb771345306515669
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
ae2ad882-2e61-11e5-9284-b827eb9e62be
hello.java
ae253b34-2e61-11e5-9284-b827eb9e62be
ae2ad882-2e61-11e5-9284-b827eb9e62be
hello.java
ae2ad882-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>ae253b34-2e61-11e5-9284-b827eb9e62be <add>ae2ad882-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
3cf300f1ca4252489d201cacb9e8ea5303601c70
0
quantiply-fork/c5-replicator,cloud-software-foundation/c5-replicator,cloud-software-foundation/c5-replicator,quantiply-fork/c5-replicator
/* * Copyright (C) 2014 Ohm Data * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package c5db.tablet; import c5db.interfaces.ReplicationModule; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.SettableFuture; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.regionserver.wal.HLog; import org.jetlang.fibers.Fiber; import org.jetlang.fibers.ThreadFiber; import org.jmock.Expectations; import org.jmock.integration.junit4.JUnitRuleMockery; import org.jmock.lib.concurrent.Synchroniser; import org.junit.Rule; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import static org.junit.Assert.assertTrue; /** * */ public class TabletTest { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery() {{ setThreadingPolicy(new Synchroniser()); }}; ReplicationModule replicationModule = context.mock(ReplicationModule.class); //HRegion region = context.mock(HRegion.class); ReplicationModule.Replicator replicator = context.mock(ReplicationModule.Replicator.class); IRegion.Creator regionCreator = context.mock(IRegion.Creator.class); IRegion region = context.mock(IRegion.class); HLog log = context.mock(HLog.class); final List<Long> peerList = ImmutableList.of(1L, 2L, 3L); final HRegionInfo regionInfo = new HRegionInfo(TableName.valueOf("tablename")); final String regionName = regionInfo.getRegionNameAsString(); final HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("tablename")); // TODO real path. final Path path = Paths.get("/"); final Configuration conf = new Configuration(); @Test public void basicTest() throws Exception { SettableFuture<ReplicationModule.Replicator> future = SettableFuture.create(); future.set(replicator); context.checking(new Expectations() {{ oneOf(replicationModule).createReplicator(regionName, peerList); will(returnValue(future)); oneOf(replicator).start(); oneOf(regionCreator).getHRegion(path, regionInfo, tableDescriptor, log, conf); will(returnValue(region)); }}); Fiber f = new ThreadFiber(); Tablet tablet = new Tablet( regionInfo, tableDescriptor, peerList, f, replicationModule, regionCreator); // TODO never ever call sleep Thread.sleep(1000); assertTrue(tablet.isOpen()); } }
c5db/src/test/java/c5db/tablet/TabletTest.java
/* * Copyright (C) 2014 Ohm Data * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package c5db.tablet; import c5db.interfaces.ReplicationModule; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.SettableFuture; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.regionserver.wal.HLog; import org.jetlang.fibers.Fiber; import org.jetlang.fibers.ThreadFiber; import org.jmock.Expectations; import org.jmock.integration.junit4.JUnitRuleMockery; import org.jmock.lib.concurrent.Synchroniser; import org.junit.Rule; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import static org.junit.Assert.assertTrue; /** * */ public class TabletTest { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery() {{ setThreadingPolicy(new Synchroniser()); }}; ReplicationModule replicationModule = context.mock(ReplicationModule.class); //HRegion region = context.mock(HRegion.class); ReplicationModule.Replicator replicator = context.mock(ReplicationModule.Replicator.class); IRegion.Creator regionCreator = context.mock(IRegion.Creator.class); IRegion region = context.mock(IRegion.class); HLog log = context.mock(HLog.class); final String regionName = "foobar1234"; final List<Long> peerList = ImmutableList.of(1L, 2L, 3L); final HRegionInfo regionInfo = new HRegionInfo(TableName.valueOf("tablename")); final HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("tablename")); // TODO real path. final Path path = Paths.get("/"); final Configuration conf = new Configuration(); @Test public void basicTest() throws Exception { SettableFuture<ReplicationModule.Replicator> future = SettableFuture.create(); future.set(replicator); context.checking(new Expectations() {{ oneOf(replicationModule).createReplicator(regionName, peerList); will(returnValue(future)); oneOf(replicator).start(); oneOf(regionCreator).getHRegion(path, regionInfo, tableDescriptor, log, conf); will(returnValue(region)); }}); Fiber f = new ThreadFiber(); Tablet tablet = new Tablet(f, replicationModule, regionCreator); // TODO never ever call sleep Thread.sleep(1000); assertTrue(tablet.isOpen()); } }
Make one more expectation pass
c5db/src/test/java/c5db/tablet/TabletTest.java
Make one more expectation pass
<ide><path>5db/src/test/java/c5db/tablet/TabletTest.java <ide> IRegion region = context.mock(IRegion.class); <ide> HLog log = context.mock(HLog.class); <ide> <del> final String regionName = "foobar1234"; <ide> final List<Long> peerList = ImmutableList.of(1L, 2L, 3L); <ide> final HRegionInfo regionInfo = new HRegionInfo(TableName.valueOf("tablename")); <add> final String regionName = regionInfo.getRegionNameAsString(); <ide> final HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("tablename")); <ide> // TODO real path. <ide> final Path path = Paths.get("/"); <ide> }}); <ide> <ide> Fiber f = new ThreadFiber(); <del> Tablet tablet = new Tablet(f, replicationModule, regionCreator); <add> Tablet tablet = new Tablet( <add> regionInfo, <add> tableDescriptor, <add> peerList, <add> f, replicationModule, regionCreator); <ide> <ide> // TODO never ever call sleep <ide> Thread.sleep(1000);
Java
apache-2.0
6451b5f655ce586e98f49784a1b2a1cf0a8dbd9b
0
fbaligand/lognavigator,fbaligand/lognavigator
package org.lognavigator.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import net.schmizz.sshj.common.IOUtils; import org.lognavigator.bean.FileInfo; import org.lognavigator.bean.LogAccessConfig; import org.lognavigator.bean.LogAccessConfig.LogAccessType; import org.lognavigator.exception.LogAccessException; import org.lognavigator.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.util.FileCopyUtils; /** * Service which manages HTTP connections and commands to remote hosts * where logs are exposed by an Apache Httpd server, using DirectoryIndex directive */ @Service @Qualifier("httpd") public class HttpdLogAccessService implements LogAccessService { private static final String TABLE_START = "<pre>"; private static final String TABLE_END = "</pre>"; private static final String LINK_HREF_END = "\""; private static final String LINK_HREF_START = "<a href=\""; private static final String DATE_FORMAT_NUMERIC = "yyyy-MM-dd HH:mm"; private static final String DATE_FORMAT_LITTERAL = "dd-MMM-yyyy HH:mm"; private static final String LINK_END_TAG = "</a>"; private static final String DIRECTORY_SEPARATOR = "/"; private static final String LAST_MODIFIED_SORT = "?C=M;O=D"; private static final long ONE_KB = 1024L; @Autowired ConfigService configService; @Autowired @Qualifier("local") LogAccessService localLogAccessService; @Override public InputStream executeCommand(String logAccessConfigId, String shellCommand) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Generate authentication option (if requested in configuration) String authenticationOption = ""; if (logAccessConfig.getUser() != null && logAccessConfig.getPassword() != null) { authenticationOption = "-u \"" + logAccessConfig.getUser() + ":" + logAccessConfig.getPassword() + "\" "; } // Generate proxy option (if requested in configuration) String proxyOption = ""; if (logAccessConfig.getProxy() != null) { proxyOption = "-x " + logAccessConfig.getProxy() + " "; } // Generate curl command with full url String urlPrefix = logAccessConfig.getUrl(); String fullUrlShellCommand = shellCommand.replaceFirst(Constants.HTTPD_FILE_VIEW_COMMAND_START, Constants.HTTPD_FILE_VIEW_COMMAND_START + authenticationOption + proxyOption + urlPrefix); // Execute curl command return localLogAccessService.executeCommand(logAccessConfigId, fullUrlShellCommand); } @Override public void downloadFile(String logAccessConfigId, String fileName, OutputStream downloadOutputStream) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Define curl shell command String shellCommand = Constants.HTTPD_FILE_VIEW_COMMAND_START + fileName; // Execute the download try { InputStream remoteInputStream = executeCommand(logAccessConfigId, shellCommand); FileCopyUtils.copy(remoteInputStream, downloadOutputStream); } catch (IOException e) { throw new LogAccessException("Error when executing downloading " + fileName + " on " + logAccessConfig, e); } } @Override public Set<FileInfo> listFiles(String logAccessConfigId, String subPath) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Define curl shell command String shellCommand = Constants.HTTPD_FILE_VIEW_COMMAND_START; if (subPath != null) { shellCommand += subPath + DIRECTORY_SEPARATOR; } shellCommand += LAST_MODIFIED_SORT; // Execute command to get file list BufferedReader remoteReader; try { InputStream remoteInputStream = executeCommand(logAccessConfigId, shellCommand); remoteReader = new BufferedReader(new InputStreamReader(remoteInputStream, Constants.ISO_ENCODING)); } catch (IOException e) { throw new LogAccessException("Error when connecting to " + logAccessConfig, e); } try { // Read until table head String currentLine; boolean isTableStartReached = false; while ( (currentLine = remoteReader.readLine()) != null) { if (currentLine.contains(TABLE_START)) { isTableStartReached = true; break; } } if (!isTableStartReached) { throw new LogAccessException("Impossible to get log files list on " + logAccessConfig); } // Result meta-informations Set<FileInfo> fileInfos = new TreeSet<FileInfo>(); int maxFileCount = configService.getFileListMaxCount(); int fileCount = 0; // Extract files and directories : each line is a file/directory while ( (currentLine = remoteReader.readLine()) != null) { // Last Line if (currentLine.contains(TABLE_END)) { break; } // Check file count ++fileCount; if (fileCount > maxFileCount) { break; } // Parse file name int linkHrefStart = currentLine.indexOf(LINK_HREF_START) + LINK_HREF_START.length(); int linkHrefEnd = currentLine.indexOf(LINK_HREF_END, linkHrefStart); String fileName = currentLine.substring(linkHrefStart, linkHrefEnd); boolean isDirectory = fileName.endsWith(DIRECTORY_SEPARATOR); if (isDirectory) { fileName = fileName.substring(0, fileName.length() - 1); } // Parse date int linkTagEnd = currentLine.indexOf(LINK_END_TAG) + LINK_END_TAG.length(); String[] dateAndSize = currentLine.substring(linkTagEnd).trim().replaceAll("\\s+", " ").split(" "); String dateAsString = dateAndSize[0] + " " + dateAndSize[1]; Date date; if (dateAsString.length() == DATE_FORMAT_NUMERIC.length()) { date = new SimpleDateFormat(DATE_FORMAT_NUMERIC).parse(dateAsString); } else { date = new SimpleDateFormat(DATE_FORMAT_LITTERAL, Locale.US).parse(dateAsString); } // Parse size long size = 0; if (!isDirectory) { String sizeAsString = dateAndSize[2]; if (sizeAsString.matches("[0-9.]+[KMG]")) { BigDecimal sizeAsBigDecimal = new BigDecimal(sizeAsString.substring(0, sizeAsString.length()-1)); char sizeLastChar = sizeAsString.charAt(sizeAsString.length()-1); switch (sizeLastChar) { case 'K': sizeAsBigDecimal = sizeAsBigDecimal.multiply(BigDecimal.valueOf(ONE_KB)); break; case 'M': sizeAsBigDecimal = sizeAsBigDecimal.multiply(BigDecimal.valueOf(ONE_KB * ONE_KB)); break; case 'G': sizeAsBigDecimal = sizeAsBigDecimal.multiply(BigDecimal.valueOf(ONE_KB * ONE_KB * ONE_KB)); break; } size = sizeAsBigDecimal.longValue(); } else { size = Long.parseLong(sizeAsString); } } // Extract meta-informations FileInfo fileInfo = new FileInfo(); fileInfo.setFileName(fileName); fileInfo.setRelativePath((subPath != null ? subPath + DIRECTORY_SEPARATOR : "") + fileName); fileInfo.setDirectory(isDirectory); fileInfo.setLastModified(date); fileInfo.setFileSize(size); fileInfo.setLogAccessType(LogAccessType.HTTPD); fileInfos.add(fileInfo); } // Return meta-informations about files and directories return fileInfos; } catch (IOException e) { throw new LogAccessException("Error when parsing log files list on " + logAccessConfig, e); } catch (NumberFormatException e) { throw new LogAccessException("Error when parsing log files list on " + logAccessConfig, e); } catch (ParseException e) { throw new LogAccessException("Error when parsing log files list on " + logAccessConfig, e); } finally { IOUtils.closeQuietly(remoteReader); } } }
src/main/java/org/lognavigator/service/HttpdLogAccessService.java
package org.lognavigator.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.math.BigDecimal; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import net.schmizz.sshj.common.IOUtils; import org.lognavigator.bean.FileInfo; import org.lognavigator.bean.LogAccessConfig; import org.lognavigator.bean.LogAccessConfig.LogAccessType; import org.lognavigator.exception.LogAccessException; import org.lognavigator.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.util.FileCopyUtils; /** * Service which manages HTTP connections and commands to remote hosts * where logs are exposed by an Apache Httpd server, using DirectoryIndex directive */ @Service @Qualifier("httpd") public class HttpdLogAccessService implements LogAccessService { private static final String CHARSET_PARAM = "charset="; private static final String TABLE_START = "<pre>"; private static final String TABLE_END = "</pre>"; private static final String LINK_HREF_END = "\""; private static final String LINK_HREF_START = "<a href=\""; private static final String DATE_FORMAT_NUMERIC = "yyyy-MM-dd HH:mm"; private static final String DATE_FORMAT_LITTERAL = "dd-MMM-yyyy HH:mm"; private static final String LINK_END_TAG = "</a>"; private static final String DIRECTORY_SEPARATOR = "/"; private static final String LAST_MODIFIED_SORT = "?C=M;O=D"; private static final long ONE_KB = 1024L; @Autowired ConfigService configService; @Autowired @Qualifier("local") LogAccessService localLogAccessService; @Override public InputStream executeCommand(String logAccessConfigId, String shellCommand) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Replace "curl -s <file>" occurences by "curl -s <full url>" String urlPrefix = logAccessConfig.getUrl(); String fullUrlShellCommand = shellCommand.replaceFirst(Constants.HTTPD_FILE_VIEW_COMMAND_START, Constants.HTTPD_FILE_VIEW_COMMAND_START + urlPrefix); // Execute curl command return localLogAccessService.executeCommand(logAccessConfigId, fullUrlShellCommand); } @Override public void downloadFile(String logAccessConfigId, String fileName, OutputStream downloadOutputStream) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Define target url String targetUrl = logAccessConfig.getUrl() + DIRECTORY_SEPARATOR + fileName; // Execute the download try { URL url = new URL(targetUrl); InputStream remoteInputStream = url.openStream(); FileCopyUtils.copy(remoteInputStream, downloadOutputStream); } catch (IOException e) { throw new LogAccessException("Error when executing downloading " + fileName + " on " + logAccessConfig, e); } } @Override public Set<FileInfo> listFiles(String logAccessConfigId, String subPath) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Define target url String targetUrl = logAccessConfig.getUrl(); if (subPath != null) { targetUrl += DIRECTORY_SEPARATOR + subPath; } if (!targetUrl.endsWith(DIRECTORY_SEPARATOR)) { targetUrl += DIRECTORY_SEPARATOR; } targetUrl += LAST_MODIFIED_SORT; // Connect to URL (provided by Apache Http Server) BufferedReader remoteReader; try { URL url = new URL(targetUrl); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); String contentType = urlConnection.getContentType(); String encoding = Constants.ISO_ENCODING; if (contentType != null && contentType.contains(CHARSET_PARAM)) { int encodingStartIndex = contentType.indexOf(CHARSET_PARAM) + CHARSET_PARAM.length(); encoding = contentType.substring(encodingStartIndex); } InputStream remoteInputStream = urlConnection.getInputStream(); remoteReader = new BufferedReader(new InputStreamReader(remoteInputStream, encoding)); } catch (IOException e) { throw new LogAccessException("Error when connecting to " + logAccessConfig, e); } try { // Read until table head String currentLine; boolean isTableStartReached = false; while ( (currentLine = remoteReader.readLine()) != null) { if (currentLine.contains(TABLE_START)) { isTableStartReached = true; break; } } if (!isTableStartReached) { throw new LogAccessException("No valid content for log files list on " + logAccessConfig); } // Result meta-informations Set<FileInfo> fileInfos = new TreeSet<FileInfo>(); int maxFileCount = configService.getFileListMaxCount(); int fileCount = 0; // Extract files and directories : each line is a file/directory while ( (currentLine = remoteReader.readLine()) != null) { // Last Line if (currentLine.contains(TABLE_END)) { break; } // Check file count ++fileCount; if (fileCount > maxFileCount) { break; } // Parse file name int linkHrefStart = currentLine.indexOf(LINK_HREF_START) + LINK_HREF_START.length(); int linkHrefEnd = currentLine.indexOf(LINK_HREF_END, linkHrefStart); String fileName = currentLine.substring(linkHrefStart, linkHrefEnd); boolean isDirectory = fileName.endsWith(DIRECTORY_SEPARATOR); if (isDirectory) { fileName = fileName.substring(0, fileName.length() - 1); } // Parse date int linkTagEnd = currentLine.indexOf(LINK_END_TAG) + LINK_END_TAG.length(); String[] dateAndSize = currentLine.substring(linkTagEnd).trim().replaceAll("\\s+", " ").split(" "); String dateAsString = dateAndSize[0] + " " + dateAndSize[1]; Date date; if (dateAsString.length() == DATE_FORMAT_NUMERIC.length()) { date = new SimpleDateFormat(DATE_FORMAT_NUMERIC).parse(dateAsString); } else { date = new SimpleDateFormat(DATE_FORMAT_LITTERAL, Locale.US).parse(dateAsString); } // Parse size long size = 0; if (!isDirectory) { String sizeAsString = dateAndSize[2]; if (sizeAsString.matches("[0-9.]+[KMG]")) { BigDecimal sizeAsBigDecimal = new BigDecimal(sizeAsString.substring(0, sizeAsString.length()-1)); char sizeLastChar = sizeAsString.charAt(sizeAsString.length()-1); switch (sizeLastChar) { case 'K': sizeAsBigDecimal = sizeAsBigDecimal.multiply(BigDecimal.valueOf(ONE_KB)); break; case 'M': sizeAsBigDecimal = sizeAsBigDecimal.multiply(BigDecimal.valueOf(ONE_KB * ONE_KB)); break; case 'G': sizeAsBigDecimal = sizeAsBigDecimal.multiply(BigDecimal.valueOf(ONE_KB * ONE_KB * ONE_KB)); break; } size = sizeAsBigDecimal.longValue(); } else { size = Long.parseLong(sizeAsString); } } // Extract meta-informations FileInfo fileInfo = new FileInfo(); fileInfo.setFileName(fileName); fileInfo.setRelativePath((subPath != null ? subPath + DIRECTORY_SEPARATOR : "") + fileName); fileInfo.setDirectory(isDirectory); fileInfo.setLastModified(date); fileInfo.setFileSize(size); fileInfo.setLogAccessType(LogAccessType.HTTPD); fileInfos.add(fileInfo); } // Return meta-informations about files and directories return fileInfos; } catch (IOException e) { throw new LogAccessException("Error when parsing log files list on " + logAccessConfig, e); } catch (NumberFormatException e) { throw new LogAccessException("Error when parsing log files list on " + logAccessConfig, e); } catch (ParseException e) { throw new LogAccessException("Error when parsing log files list on " + logAccessConfig, e); } finally { IOUtils.closeQuietly(remoteReader); } } }
- always use curl command for HTTPD log access configs (instead of UrlConnection) - add ability to call HTTPD server using HTTP basic authentication - add ability to call HTTPD server through a proxy
src/main/java/org/lognavigator/service/HttpdLogAccessService.java
- always use curl command for HTTPD log access configs (instead of UrlConnection) - add ability to call HTTPD server using HTTP basic authentication - add ability to call HTTPD server through a proxy
<ide><path>rc/main/java/org/lognavigator/service/HttpdLogAccessService.java <ide> import java.io.InputStreamReader; <ide> import java.io.OutputStream; <ide> import java.math.BigDecimal; <del>import java.net.URL; <del>import java.net.URLConnection; <ide> import java.text.ParseException; <ide> import java.text.SimpleDateFormat; <ide> import java.util.Date; <ide> @Qualifier("httpd") <ide> public class HttpdLogAccessService implements LogAccessService { <ide> <del> private static final String CHARSET_PARAM = "charset="; <ide> private static final String TABLE_START = "<pre>"; <ide> private static final String TABLE_END = "</pre>"; <ide> private static final String LINK_HREF_END = "\""; <ide> // Get the LogAccessConfig <ide> LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); <ide> <del> // Replace "curl -s <file>" occurences by "curl -s <full url>" <add> // Generate authentication option (if requested in configuration) <add> String authenticationOption = ""; <add> if (logAccessConfig.getUser() != null && logAccessConfig.getPassword() != null) { <add> authenticationOption = "-u \"" + logAccessConfig.getUser() + ":" + logAccessConfig.getPassword() + "\" "; <add> } <add> <add> // Generate proxy option (if requested in configuration) <add> String proxyOption = ""; <add> if (logAccessConfig.getProxy() != null) { <add> proxyOption = "-x " + logAccessConfig.getProxy() + " "; <add> } <add> <add> // Generate curl command with full url <ide> String urlPrefix = logAccessConfig.getUrl(); <del> String fullUrlShellCommand = shellCommand.replaceFirst(Constants.HTTPD_FILE_VIEW_COMMAND_START, Constants.HTTPD_FILE_VIEW_COMMAND_START + urlPrefix); <add> String fullUrlShellCommand = shellCommand.replaceFirst(Constants.HTTPD_FILE_VIEW_COMMAND_START, Constants.HTTPD_FILE_VIEW_COMMAND_START + authenticationOption + proxyOption + urlPrefix); <ide> <ide> // Execute curl command <ide> return localLogAccessService.executeCommand(logAccessConfigId, fullUrlShellCommand); <ide> <ide> // Get the LogAccessConfig <ide> LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); <del> <del> // Define target url <del> String targetUrl = logAccessConfig.getUrl() + DIRECTORY_SEPARATOR + fileName; <add> <add> // Define curl shell command <add> String shellCommand = Constants.HTTPD_FILE_VIEW_COMMAND_START + fileName; <ide> <ide> // Execute the download <ide> try { <del> URL url = new URL(targetUrl); <del> InputStream remoteInputStream = url.openStream(); <add> InputStream remoteInputStream = executeCommand(logAccessConfigId, shellCommand); <ide> FileCopyUtils.copy(remoteInputStream, downloadOutputStream); <ide> } <ide> catch (IOException e) { <ide> // Get the LogAccessConfig <ide> LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); <ide> <del> // Define target url <del> String targetUrl = logAccessConfig.getUrl(); <add> // Define curl shell command <add> String shellCommand = Constants.HTTPD_FILE_VIEW_COMMAND_START; <ide> if (subPath != null) { <del> targetUrl += DIRECTORY_SEPARATOR + subPath; <del> } <del> if (!targetUrl.endsWith(DIRECTORY_SEPARATOR)) { <del> targetUrl += DIRECTORY_SEPARATOR; <del> } <del> targetUrl += LAST_MODIFIED_SORT; <del> <del> // Connect to URL (provided by Apache Http Server) <add> shellCommand += subPath + DIRECTORY_SEPARATOR; <add> } <add> shellCommand += LAST_MODIFIED_SORT; <add> <add> // Execute command to get file list <ide> BufferedReader remoteReader; <ide> try { <del> URL url = new URL(targetUrl); <del> URLConnection urlConnection = url.openConnection(); <del> urlConnection.connect(); <del> String contentType = urlConnection.getContentType(); <del> String encoding = Constants.ISO_ENCODING; <del> if (contentType != null && contentType.contains(CHARSET_PARAM)) { <del> int encodingStartIndex = contentType.indexOf(CHARSET_PARAM) + CHARSET_PARAM.length(); <del> encoding = contentType.substring(encodingStartIndex); <del> } <del> InputStream remoteInputStream = urlConnection.getInputStream(); <del> remoteReader = new BufferedReader(new InputStreamReader(remoteInputStream, encoding)); <add> InputStream remoteInputStream = executeCommand(logAccessConfigId, shellCommand); <add> remoteReader = new BufferedReader(new InputStreamReader(remoteInputStream, Constants.ISO_ENCODING)); <ide> } <ide> catch (IOException e) { <ide> throw new LogAccessException("Error when connecting to " + logAccessConfig, e); <ide> } <ide> } <ide> if (!isTableStartReached) { <del> throw new LogAccessException("No valid content for log files list on " + logAccessConfig); <add> throw new LogAccessException("Impossible to get log files list on " + logAccessConfig); <ide> } <ide> <ide> // Result meta-informations
JavaScript
mit
400736956d7dca174286c4473977e0eeedf923d0
0
Drathal/redux-playground,Drathal/redux-playground
import React, { Component } from 'react' import { connect } from 'react-redux' import { getProducts } from '../../../api/product' import ProductsList from '../../views/ProductList' import { addProduct, deleteProduct } from '../../../redux/modules/products/actions' @connect((state) => { return {products: state.products.itemList} }, {addProduct, deleteProduct}) export default class ProductListContainer extends Component { _doAddProduct = function() { let id = Math.floor(Math.random() * (100 - 5) + 5); this.props.addProduct({'id': id, 'description': 'product ' + id}) } _doDeleteProduct = function(product) { this.props.deleteProduct(product.id) } componentDidMount = function() { getProducts().then(response => { response.data.map(product=>{ this.props.addProduct(product) }) }); } render() { return (<ProductsList products={ this.props.products } addProduct={ this._doAddProduct.bind(this) } deleteProduct={ this._doDeleteProduct.bind(this) } />) } }
src/components/containers/ProductListContainer/index.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { getProducts } from '../../../api/product' import ProductsList from '../../views/ProductList' import { addProduct, deleteProduct } from '../../../redux/modules/products/actions' @connect((state) => { return {products: state.products.itemList} }, {addProduct, deleteProduct}) export default class ProductListContainer extends Component { _doAddProduct = function() { let id = Math.floor(Math.random() * (100 - 5) + 5); this.props.addProduct({'id': id, 'description': 'product ' + id}) } _doDeleteProduct = function(product) { this.props.deleteProduct(product.id) } componentDidMount = function() { getProducts().then(response => { response.data.map(product=>{ this.props.addProduct(product) }) }); } render() { return (<ProductsList title="My Products" products={ this.props.products } addProduct={ this._doAddProduct.bind(this) } deleteProduct={ this._doDeleteProduct.bind(this) } />) } }
no translation mixing for now
src/components/containers/ProductListContainer/index.js
no translation mixing for now
<ide><path>rc/components/containers/ProductListContainer/index.js <ide> } <ide> <ide> render() { <del> return (<ProductsList title="My Products" <del> products={ this.props.products } <add> return (<ProductsList products={ this.props.products } <ide> addProduct={ this._doAddProduct.bind(this) } <ide> deleteProduct={ this._doDeleteProduct.bind(this) } />) <ide> }
JavaScript
mit
ed2796dc708c1b5a94b637f24337bbf30d9176cc
0
beautify-web/js-beautify,beautify-web/js-beautify,beautify-web/js-beautify,beautify-web/js-beautify
js/src/html/test.js
< div > <span> </span> </div >
fixed typo on contributing file
js/src/html/test.js
fixed typo on contributing file
<ide><path>s/src/html/test.js <del>< div > <span> </span> </div >
Java
mit
fd088db2f44c30946c4f6e672f75fe54e86d50b1
0
thewillchang/VoogaSalad,goose2460/game_author_cs308,kevinli194/voogasalad_BitsPlease
package engine.level; import java.util.Iterator; import authoring.model.collections.ConditionIDsCollection; import authoring.model.collections.GameObjectsCollection; import engine.gameObject.GameObject; /** * A Level of the game. Contains all GameObjects and Actions and coordinates * their interactions for linear progression through the game. * * @author Will Chang * @author Abhishek Balakrishnan */ public class Level { private String myLevelID; private GameObjectsCollection myGameObjects; private ConditionIDsCollection myConditionIDs; /** * Constructor * @param Game Objects Collection */ public Level(GameObjectsCollection gameObjects) { myGameObjects = gameObjects; } /** * Updates all GameObjects. */ public void update() { for (GameObject sprite : myGameObjects) { sprite.update(); } } /** * SET INITIAL VALUES FOR THE MAIN CHARACTER */ public void updateMainCharacter() { } /** * @return Iterator for GameObjectCollection */ public Iterator<GameObject> getGameObjectIterator() { return myGameObjects.iterator(); } /** * @return Iterator for the ConditionIDsCollection */ public Iterator<String> getConditionIDsIterator() { return myConditionIDs.iterator(); } }
src/engine/level/Level.java
package engine.level; import java.util.Iterator; import authoring.model.collections.ConditionsCollection; import authoring.model.collections.GameObjectsCollection; import engine.conditions.Condition; import engine.gameObject.GameObject; /** * A Level of the game. Contains all GameObjects and Actions and coordinates * their interactions for linear progression through the game. * * @author Will Chang * @author Abhishek Balakrishnan */ public class Level { private GameObjectsCollection myGameObjects; // private ConditionsCollection myConditions; /** * Constructor * @param Game Objects Collection */ public Level(GameObjectsCollection gameObjects) { myGameObjects = gameObjects; } /** * Updates all GameObjects. */ public void update() { for (GameObject sprite : myGameObjects) { sprite.update(); } } /** * SET INITIAL VALUES FOR THE MAIN CHARACTER */ public void updateMainCharacter() { } /** * Enables and initializes the Game Objects specified in this Level * * @param sprites */ /* * public void setEnabledGameObjects(List<GameObject> sprites) { * for(GameObject sprite : sprites) { * if(myEnabledGameObjects.get(sprite.getID())) { //sprite.enable(); ?? * //copy of??? //Initialize the sprite to location??? * myGameObjects.add(sprite); } } } /* public void setEnabled(String type, * List<IEnabled> enabledObjects) { * * for(IEnabled enabledObject : enabledObjects) { * if(myEnabledGameObjects.get(sprite.getID()) } } */ /** * Enables the Conditions specified in this Level * * @param conditions */ /* * public void setEnabledConditions(List<Condition> conditions) { * for(Condition condition : conditions) { * //if(myEnabledConditions.get(condition.getID()) { //TODO have Conditions * Implement IEnabled // condition.enable(); //} } } */ /* public void setEnabledConditions(List<Condition> conditions) { for(Condition condition : conditions) { if(myEnabledConditions.get(condition.getID()) { //TODO have Conditions //Implement IEnabled condition.enable(); } } } */ /** * Iterator for the List of enabled Game Objects in the Level * * @return */ public Iterator<GameObject> getGameObjects() { return myGameObjects.iterator(); } /* public Iterator<Condition> getConditions() { return myConditions.iterator(); } */ }
Level updated
src/engine/level/Level.java
Level updated
<ide><path>rc/engine/level/Level.java <ide> <ide> import java.util.Iterator; <ide> <del>import authoring.model.collections.ConditionsCollection; <add>import authoring.model.collections.ConditionIDsCollection; <ide> import authoring.model.collections.GameObjectsCollection; <del>import engine.conditions.Condition; <ide> import engine.gameObject.GameObject; <ide> <ide> /** <ide> <ide> public class Level { <ide> <add> private String myLevelID; <ide> private GameObjectsCollection myGameObjects; <del>// private ConditionsCollection myConditions; <add> private ConditionIDsCollection myConditionIDs; <ide> <ide> /** <ide> * Constructor <ide> public void updateMainCharacter() { <ide> <ide> } <add> <add> /** <add> * @return Iterator for GameObjectCollection <add> */ <add> public Iterator<GameObject> getGameObjectIterator() { <add> return myGameObjects.iterator(); <add> } <ide> <ide> /** <del> * Enables and initializes the Game Objects specified in this Level <del> * <del> * @param sprites <add> * @return Iterator for the ConditionIDsCollection <ide> */ <del> /* <del> * public void setEnabledGameObjects(List<GameObject> sprites) { <del> * for(GameObject sprite : sprites) { <del> * if(myEnabledGameObjects.get(sprite.getID())) { //sprite.enable(); ?? <del> * //copy of??? //Initialize the sprite to location??? <del> * myGameObjects.add(sprite); } } } /* public void setEnabled(String type, <del> * List<IEnabled> enabledObjects) { <del> * <del> * for(IEnabled enabledObject : enabledObjects) { <del> * if(myEnabledGameObjects.get(sprite.getID()) } } <del> */ <add> public Iterator<String> getConditionIDsIterator() { <add> return myConditionIDs.iterator(); <add> } <ide> <del> /** <del> * Enables the Conditions specified in this Level <del> * <del> * @param conditions <del> */ <del> /* <del> * public void setEnabledConditions(List<Condition> conditions) { <del> * for(Condition condition : conditions) { <del> * //if(myEnabledConditions.get(condition.getID()) { //TODO have Conditions <del> * Implement IEnabled // condition.enable(); //} } } <del> */ <del> /* <del> public void setEnabledConditions(List<Condition> conditions) { <del> for(Condition condition : conditions) { <del> if(myEnabledConditions.get(condition.getID()) { //TODO have Conditions <del> //Implement IEnabled <del> condition.enable(); } } } <del>*/ <del> /** <del> * Iterator for the List of enabled Game Objects in the Level <del> * <del> * @return <del> */ <del> public Iterator<GameObject> getGameObjects() { <del> return myGameObjects.iterator(); <del> } <del>/* <del> public Iterator<Condition> getConditions() { <del> return myConditions.iterator(); <del> } */ <ide> }
Java
mit
1a0653888234fe24a2c82f072a6db35d901a6e69
0
joshimoo/gdi1-project
package de.tu_darmstadt.gdi1.gorillas.ui.states; import de.matthiasmann.twl.Alignment; import de.matthiasmann.twl.Button; import de.matthiasmann.twl.slick.BasicTWLGameState; import de.matthiasmann.twl.slick.RootPane; import de.tu_darmstadt.gdi1.gorillas.assets.Assets; import de.tu_darmstadt.gdi1.gorillas.entities.*; import de.tu_darmstadt.gdi1.gorillas.main.Gorillas; import de.tu_darmstadt.gdi1.gorillas.main.Game; import de.tu_darmstadt.gdi1.gorillas.main.Player; import de.tu_darmstadt.gdi1.gorillas.ui.widgets.valueadjuster.AdvancedValueAdjusterInt; import de.tu_darmstadt.gdi1.gorillas.utils.SqlGorillas; import eea.engine.entity.Entity; import eea.engine.entity.StateBasedEntityManager; import org.newdawn.slick.*; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.geom.Circle; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.StateBasedGame; import java.util.ArrayList; import java.util.List; public class GamePlayState extends BasicTWLGameState { // Key Handling private float keyPressDelay = 0; private final float keyPressWaitTime = 0.1f; // wait 100 ms TODO: experiment with these // DEBUG private String throwNumber = null; private String roundWinMessage = null; List<Circle> debugCollisions = new ArrayList<>(32); // UI private RootPane rp; private AdvancedValueAdjusterInt if_speed; // We are using the advanced with the edit callback for tests private AdvancedValueAdjusterInt if_angle; // We are using the advanced with the edit callback for tests private Button btnThrow; // GameState private STATES state; private int windSpeed; private Image background; private Image arrow; private Sound explosionSound; private float gravity = 9.80665f; private String comment = ""; private String score = "Score: 0:0"; // Entities private StateBasedEntityManager entityManager; private Banana banana; private Skyline skyline; private Gorilla gorilla; private Gorilla gorillb; private Sun sun; private Cloud cloud; // Counter private static int totalRoundCounter = 0; public Player getActivePlayer() { return Game.getInstance().getActivePlayer(); } public void setActivePlayer(Player activePlayer) { Game.getInstance().setActivePlayer(activePlayer); } /** Die FSM für das spiel ist eigentlich recht simple: * Im INPUT state werden die Eingaben des aktiven Spieles verarbeitet. Wenn einen * Banane geworfen wird, wechseln wir nach THROW. Hier wird die Banane nach den Physikalichen * vorgaben bewegt und am auf Kollisionen geprüft. Beim Auftreten der Kollision wird nach * DMAMGE gewechselt, der schaden berechnet, auf Sieg geprüft und zu INPUT oder VICTORY * gewechselt. */ private static enum STATES{ INPUT, THROW, DAMAGE, ROUNDVICTORY, VICTORY } @Override public int getID() { return de.tu_darmstadt.gdi1.gorillas.main.Game.GAMEPLAYSTATE; } public Skyline getSkyline(){ return skyline; } public Gorilla getGorilla(int num){ return num == 0 ? gorilla : gorillb; } public Sun getSun(){ return sun; } public GamePlayState() { entityManager = StateBasedEntityManager.getInstance(); } @Override public void init(GameContainer gc, StateBasedGame game) throws SlickException { // Load All Static Content or Ressources (Background Images, Sounds etc) // Lazy Load the UI, this is better for the TestGameContainer if (!Game.getInstance().isTestMode()) { // Don't load anything in TestMode background = Assets.loadImage(Assets.Images.GAMEPLAY_BACKGROUND); arrow = Assets.loadImage(Assets.Images.ARROW); explosionSound = Assets.loadSound(Assets.Sounds.EXPLOSION); } } @Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { super.enter(container, game); startGame(); } public void startGame() { entityManager.clearEntitiesFromState(getID()); debugCollisions.clear(); skyline = new Skyline(6); int x1 = (int)(Math.random() * 3 + 0); int x2 = (int)(Math.random() * 3 + 3); int xx = x1 * (skyline.BUILD_WIDTH) + (skyline.BUILD_WIDTH / 2); int yy = x2 * (skyline.BUILD_WIDTH) + (skyline.BUILD_WIDTH / 2); gorilla = new Gorilla(new Vector2f(xx, Gorillas.FRAME_HEIGHT - skyline.getHeight(x1))); gorillb = new Gorilla(new Vector2f(yy, Gorillas.FRAME_HEIGHT - skyline.getHeight(x2))); sun = new Sun(new Vector2f(400, 60)); windSpeed = Game.getInstance().getWind() ? (int) ((Math.random() * 30) - 15) : 0; cloud = new Cloud(new Vector2f(0, 60), windSpeed); destroyBanana(); setActivePlayer(Game.getInstance().getPlayer(0)); state = STATES.INPUT; } void renderDebugShapes(GameContainer gc, StateBasedGame game, Graphics g) { // TODO: instead of explicitly drawing individual entities, draw all statemanager registered entity //for (Entity e : entityManager.getEntitiesByState(getID())) {g.draw(e.getShape());} g.draw(sun.getShape()); g.draw(skyline.getShape()); g.draw(gorilla.getShape()); g.draw(gorillb.getShape()); g.draw(cloud.getShape()); if (banana != null) g.draw(banana.getShape()); // Draw historical collisions debugCollisions.forEach(g::draw); } @Override public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException { if (Game.getInstance().isTestMode()) { return; } // Don't draw anything in testmode g.drawImage(background, -20, -10); g.setColor(Color.yellow); g.drawString(comment, 450, 20); g.drawString(score, 250, 20); entityManager.renderEntities(gc, game, g); sun.render(gc, game, g); skyline.render(gc, game, g); gorilla.render(gc, game, g); gorillb.render(gc, game, g); cloud.render(gc, game, g); if (Game.getInstance().getDebug()) { renderDebugShapes(gc, game, g); } if(banana != null) { banana.render(gc, game, g); if(banana.getShape().getMaxY() < 0) { g.drawImage(arrow, banana.getPosition().x - 8, 0); } } drawPlayerNames(g); if(state != STATES.THROW) { g.setColor(Color.blue); // Description for the buttons g.drawString("Speed", 20, 10); g.drawString("Angle ", 20, 50); } if(throwNumber != null) { g.setColor(Color.white); g.drawString(throwNumber,this.getRootPane().getWidth()-110,20); } if(roundWinMessage != null) { g.setColor(Color.red); g.drawString(roundWinMessage,this.getRootPane().getWidth()/2 - 150,100); } } /** * Draws text with a dropshadow * @param pos center position of the text */ private void drawTextWithDropShadow(Graphics g, Vector2f pos, String text, Color color) { // Center Text float x = pos.x - g.getFont().getWidth(text) / 2; // TODO: maybe translucent background // Draw Dropshadow g.setColor(Color.black); g.drawString(text, x + 1, pos.y - 1); // Draw Text g.setColor(color); g.drawString(text, x, pos.y); } private void drawPlayerNames(Graphics g) { for (int i = 0; i < Game.getInstance().getPlayers().size(); i++) { // Offset the Text 64 pixels higher then the gorrila // NOTE: Never modify the Vector that is retured from a .getPosition call Vector2f pos = getGorilla(i).getPosition(); Color color = getActivePlayer() == Game.getInstance().getPlayer(i) ? Color.yellow : Color.white; drawTextWithDropShadow(g, new Vector2f(pos.x, pos.y - 64), Game.getInstance().getPlayer(i).getName(), color); } } // TODO: more refactoring private final float MS_TO_S = 1.0f / 1000; private void updateThrowParameters(Input input, int delta) { if (input.isKeyPressed(Input.KEY_RETURN) || input.isKeyPressed(Input.KEY_SPACE)) { throwBanana(); } if(keyPressDelay > 0) { keyPressDelay -= delta * MS_TO_S; } else if (Game.getInstance().getInverseControlKeys()) { if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D)){ if_angle.setValue(if_angle.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A)){ if_angle.setValue(if_angle.getValue() - 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)){ if_speed.setValue(if_speed.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)){ if_speed.setValue(if_speed.getValue() - 1); keyPressDelay = keyPressWaitTime; } } else { if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D)){ if_speed.setValue(if_speed.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A)){ if_speed.setValue(if_speed.getValue() - 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)){ if_angle.setValue(if_angle.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)){ if_angle.setValue(if_angle.getValue() - 1); keyPressDelay = keyPressWaitTime; } } } @Override public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException { // Let the entities update their inputs first // Then process all remaining inputs entityManager.updateEntities(gc, game, delta); Input input = gc.getInput(); gorilla.update(gc, game, delta); gorillb.update(gc, game, delta); cloud.update(gc, game, delta); if(Game.getInstance().isDeveloper()) { /* DEBUG: Reroll the LevelGeneration */ if (input.isKeyPressed(Input.KEY_Q)) { startGame(); } // Win the Game if (input.isKeyPressed(Input.KEY_V) ) { getActivePlayer().setWin(); getActivePlayer().setWin(); getActivePlayer().setWin(); state = STATES.VICTORY; System.out.println("V Cheat"); } } /* Auf [ESC] muss unabhängig vom state reagiert werden */ if(input.isKeyPressed(Input.KEY_ESCAPE) || input.isKeyPressed(Input.KEY_P)) game.enterState(Game.INGAMEPAUSE); if(input.isKeyPressed(Input.KEY_M)) Game.getInstance().toggleMute(); switch (state) { case INPUT: throwNumber = "Throw Nr " + getActivePlayer().getThrow(); toggleUI(true); updateThrowParameters(input, delta); break; case THROW: throwNumber = "Throw Nr " + getActivePlayer().getThrow(); // During the flight disable inputs toggleUI(false); comment = ""; banana.update(gc, game, delta); sun.isCollidding(banana); // Bounds Check if(outsidePlayingField(banana, gc.getWidth(), gc.getHeight())) { state = STATES.DAMAGE; System.out.printf("OutOfBounds: pos(%.0f, %.0f), world(%d, %d)", banana.getPosition().x, banana.getPosition().y, gc.getWidth(), gc.getHeight() ); comment = "..."; } if(getActivePlayer() == Game.getInstance().getPlayer(1) && getGorilla(0).collides(banana)) { state = STATES.ROUNDVICTORY; System.out.println("Hit Player 1"); comment = "Treffer!"; } if(getActivePlayer() == Game.getInstance().getPlayer(0) && getGorilla(1).collides(banana)) { state = STATES.ROUNDVICTORY; System.out.println("Hit Player 2"); comment = "Treffer!"; } if(skyline.isCollidding(banana)) { state = STATES.DAMAGE; debugCollisions.add(new Circle(banana.getPosition().x, banana.getPosition().y, Game.getInstance().getExplosionRadius())); if(getActivePlayer() == Game.getInstance().getPlayer(1)){ if(banana.getPosition().getX() > gorilla.getPosition().getX() + 64) comment = "Viel zu kurz!"; else if(banana.getPosition().getX() < gorilla.getPosition().getX() - 64) comment = "Viel zu weit!"; if(banana.getPosition().getY() > gorilla.getPosition().getY() + 64) comment += " Viel zu tief!"; else if(banana.getPosition().getY() < gorilla.getPosition().getY() - 64) comment += " Viel zu hoch!"; if(comment == "") comment = "Fast getroffen!"; } else{ if(banana.getPosition().getX() > gorillb.getPosition().getX() + 64) comment = "Viel zu weit!"; else if(banana.getPosition().getX() < gorillb.getPosition().getX() - 64) comment = "Viel zu kurz!"; if(banana.getPosition().getY() > gorillb.getPosition().getY() + 64) comment += " Viel zu tief!"; else if(banana.getPosition().getY() < gorillb.getPosition().getY() - 64) comment += " Viel zu hoch!"; if(comment == "") comment = "Fast getroffen!"; } } break; case DAMAGE: System.out.println("Throw " + getActivePlayer().getName() + " Nr" + getActivePlayer().getThrow()); throwNumber = "Throw Nr " + getActivePlayer().getThrow(); // Ueberfluessig Game.getInstance().toggleNextPlayerActive(); if_speed.setValue(getActivePlayer().getLastSpeed()); if_angle.setValue(getActivePlayer().getLastAngle()); skyline.destroy((int)banana.getPosition().x, (int)banana.getPosition().y, Game.getInstance().getExplosionRadius()); playSound(explosionSound); destroyBanana(); // TODO: Claculate PlayerDamage // player1.damage(calcPlayerDamage(banana.getCenterX(), banana.getCenterY(), gorilla)); // player2.damage(calcPlayerDamage(banana.getCenterX(), banana.getCenterY(), gorillb)); state = STATES.INPUT; break; case ROUNDVICTORY: getActivePlayer().setWin(); totalRoundCounter += 1; if(getActivePlayer().getWin() > 2) state = STATES.VICTORY; else { System.out.println("Herzlichen Glückwunsch " + getActivePlayer().getName() + "\nSie haben die Runde gewonnen !"); System.out.println("Win Nr" + getActivePlayer().getWin()); roundWinMessage = "Herzlichen Glückwunsch " + getActivePlayer().getName() + "\nSie haben die Runde gewonnen !\n" + "Sieg Nummer " + getActivePlayer().getWin() + ".\n"+ "Sie benötigten " + getActivePlayer().getThrow() + " Würfe."; // TODO: Save Win and Throw-Number // Restart Game for (Player player : Game.getInstance().getPlayers()) { player.resetThrow(); player.setLastAngle(120); player.setLastSpeed(80); } score = "Score: " + Game.getInstance().getPlayer(0).getWin() + ":" + Game.getInstance().getPlayer(1).getWin(); if_speed.setValue(getActivePlayer().getLastSpeed()); if_angle.setValue(getActivePlayer().getLastAngle()); startGame(); } break; case VICTORY: // TODO: VICTORY System.out.println("Herzlichen Glückwunsch " + getActivePlayer().getName() + "\nSie haben das Spiel gewonnen !"); System.out.println("Win Nr" + getActivePlayer().getWin()); game.enterState(Game.GAMEVICTORY); // Store Win to SQL-DB SqlGorillas db = new SqlGorillas("data_gorillas.hsc","Gorillas"); db.insertHighScore(getActivePlayer().getName(), totalRoundCounter, getActivePlayer().getWin(), getActivePlayer().getTotalThrows()); // Reset Values totalRoundCounter = 0; break; } } /** Plays the passed sound, unless the audio is muted */ private void playSound(Sound sound) { if (!Game.getInstance().isMute() && sound != null) { sound.play(1f,Game.getInstance().getSoundVolume()); } } /** * Checks if the entity has left the playing field * Only checks Left/Right/Bottom */ Boolean outsidePlayingField(Entity entity, int screenWidth, int screenHeight) { return entity.getPosition().x > screenWidth || entity.getPosition().x < 0 || entity.getPosition().y > screenHeight; } @Override protected RootPane createRootPane() { // Needed for adding the new Input-Elements rp = super.createRootPane(); if_speed= new AdvancedValueAdjusterInt(); if_angle = new AdvancedValueAdjusterInt(); btnThrow = new Button("Throw"); if_speed.setMinMaxValue(0,200); if_speed.setValue(80); validVelocity = true; if_angle.setMinMaxValue(0,180); if_angle.setValue(120); validAngle = true; // Wirkungslos btnThrow.setAlignment(Alignment.CENTER); btnThrow.addCallback(GamePlayState.this::throwBanana); // Add the Input-Elements to the RootPane rp.add(if_speed); rp.add(if_angle); rp.add(btnThrow); return rp; } @Override protected void layoutRootPane() { // Set Size and Position of the Input-Elements int basic_x=20; int basic_y=10; int basic_x_c=35; // Labels next to the inputs because of place-conflict the the skyscraper int pos=0; if_speed.setSize(100, 25); if_speed.setPosition(basic_x+60, basic_y+basic_x_c*pos); pos=1; if_angle.setSize(100, 25); if_angle.setPosition(basic_x+60, basic_y+basic_x_c*pos); pos=2; // Button kleiner und verschoben btnThrow.setSize(50, 25); btnThrow.setPosition(basic_x+60+20, basic_y+basic_x_c*pos); } private void toggleUI(Boolean enable) { btnThrow.setVisible(enable); if_speed.setEnabled(enable); if_angle.setEnabled(enable); if_speed.setVisible(enable); if_angle.setVisible(enable); } private void destroyBanana() { if (banana != null) { entityManager.removeEntity(getID(), banana); } banana = null; } /** Creates and assigns the Banana */ private void createBanana(Vector2f pos, float throwAngle, float throwSpeed, float gravity, float windAcceleration) { // Cleanup any remaining, Bananas since at the moment we can only have a maximum of 1 if (banana != null) {entityManager.removeEntity(getID(), banana);} banana = new Banana(pos, (int)throwAngle, (int)throwSpeed, gravity, (int)windAcceleration); entityManager.addEntity(getID(), banana); } /** Generates a Banana at the current Player */ public void throwBanana() { // Save new throw getActivePlayer().setThrow(); int speed = if_speed.getValue(); int angle = if_angle.getValue(); System.out.println("Throw Banana " + speed + " " + angle); getActivePlayer().setLastSpeed(speed); getActivePlayer().setLastAngle(angle); if (getActivePlayer() == Game.getInstance().getPlayer(0)) { Vector2f pos = getGorilla(0).getPosition(); Vector2f size = getGorilla(0).getSize(); createBanana(new Vector2f(pos.x, pos.y - size.y), angle - 90, speed, Game.getInstance().getGravity(), windSpeed); } else { Vector2f pos = getGorilla(1).getPosition(); Vector2f size = getGorilla(1).getSize(); createBanana(new Vector2f(pos.x, pos.y - size.y), 180 - angle + 90, speed, Game.getInstance().getGravity(), windSpeed); } // Remove Win-Message roundWinMessage = null; state = STATES.THROW; } // TESTS // HACK: This is dirty !_! private boolean validVelocity = false; private boolean validAngle = false; public void resetPlayerWidget() { if_speed.setValue(0); if_angle.setValue(0); validVelocity = false; validAngle = false; } public int getVelocity() { return validVelocity ? if_speed.getValue() : -1; } public void fillVelocityInput(char c) { if(verifyInput(if_speed.getValue(), if_speed.getMinValue(), if_speed.getMaxValue(), c)) { if_speed.setValue(if_speed.getValue() * 10 + Character.getNumericValue(c)); validVelocity = true; } } public int getAngle() { return validAngle ? if_angle.getValue() : -1; } public void fillAngleInput(char c) { if(verifyInput(if_angle.getValue(), if_angle.getMinValue(), if_angle.getMaxValue(), c)) { if_angle.setValue(if_angle.getValue() * 10 + Character.getNumericValue(c)); validAngle = true; } } /** This only works for positive numbers */ public boolean verifyInput(int oldValue, int min, int max, char c) { if (Character.isDigit(c)) { int newValue = oldValue * 10 + Character.getNumericValue(c); if (newValue <= max && newValue >= min) { return true; } } return false; } }
src/de/tu_darmstadt/gdi1/gorillas/ui/states/GamePlayState.java
package de.tu_darmstadt.gdi1.gorillas.ui.states; import de.matthiasmann.twl.Alignment; import de.matthiasmann.twl.Button; import de.matthiasmann.twl.slick.BasicTWLGameState; import de.matthiasmann.twl.slick.RootPane; import de.tu_darmstadt.gdi1.gorillas.assets.Assets; import de.tu_darmstadt.gdi1.gorillas.entities.*; import de.tu_darmstadt.gdi1.gorillas.main.Gorillas; import de.tu_darmstadt.gdi1.gorillas.main.Game; import de.tu_darmstadt.gdi1.gorillas.main.Player; import de.tu_darmstadt.gdi1.gorillas.ui.widgets.valueadjuster.AdvancedValueAdjusterInt; import de.tu_darmstadt.gdi1.gorillas.utils.SqlGorillas; import eea.engine.entity.Entity; import eea.engine.entity.StateBasedEntityManager; import org.newdawn.slick.*; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.geom.Circle; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.StateBasedGame; import java.util.ArrayList; import java.util.List; public class GamePlayState extends BasicTWLGameState { // Key Handling private float keyPressDelay = 0; private final float keyPressWaitTime = 0.1f; // wait 100 ms TODO: experiment with these // DEBUG private String throwNumber = null; private String roundWinMessage = null; List<Circle> debugCollisions = new ArrayList<>(32); // UI private RootPane rp; private AdvancedValueAdjusterInt if_speed; // We are using the advanced with the edit callback for tests private AdvancedValueAdjusterInt if_angle; // We are using the advanced with the edit callback for tests private Button btnThrow; // GameState private STATES state; private int windSpeed; private Image background; private Image arrow; private Sound explosionSound; private float gravity = 9.80665f; private String comment = ""; private String score = "Score: 0:0"; // Entities private StateBasedEntityManager entityManager; private Banana banana; private Skyline skyline; private Gorilla gorilla; private Gorilla gorillb; private Sun sun; private Cloud cloud; // Counter private static int totalRoundCounter = 0; public Player getActivePlayer() { return Game.getInstance().getActivePlayer(); } public void setActivePlayer(Player activePlayer) { Game.getInstance().setActivePlayer(activePlayer); } /** Die FSM für das spiel ist eigentlich recht simple: * Im INPUT state werden die Eingaben des aktiven Spieles verarbeitet. Wenn einen * Banane geworfen wird, wechseln wir nach THROW. Hier wird die Banane nach den Physikalichen * vorgaben bewegt und am auf Kollisionen geprüft. Beim Auftreten der Kollision wird nach * DMAMGE gewechselt, der schaden berechnet, auf Sieg geprüft und zu INPUT oder VICTORY * gewechselt. */ private static enum STATES{ INPUT, THROW, DAMAGE, ROUNDVICTORY, VICTORY } @Override public int getID() { return de.tu_darmstadt.gdi1.gorillas.main.Game.GAMEPLAYSTATE; } public Skyline getSkyline(){ return skyline; } public Gorilla getGorilla(int num){ return num == 0 ? gorilla : gorillb; } public Sun getSun(){ return sun; } public GamePlayState() { entityManager = StateBasedEntityManager.getInstance(); } @Override public void init(GameContainer gc, StateBasedGame game) throws SlickException { // Load All Static Content or Ressources (Background Images, Sounds etc) // Lazy Load the UI, this is better for the TestGameContainer if (!Game.getInstance().isTestMode()) { // Don't load anything in TestMode background = Assets.loadImage(Assets.Images.GAMEPLAY_BACKGROUND); arrow = Assets.loadImage(Assets.Images.ARROW); explosionSound = Assets.loadSound(Assets.Sounds.EXPLOSION); } } @Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { super.enter(container, game); startGame(); } public void startGame() { entityManager.clearEntitiesFromState(getID()); debugCollisions.clear(); skyline = new Skyline(6); int x1 = (int)(Math.random() * 3 + 0); int x2 = (int)(Math.random() * 3 + 3); int xx = x1 * (skyline.BUILD_WIDTH) + (skyline.BUILD_WIDTH / 2); int yy = x2 * (skyline.BUILD_WIDTH) + (skyline.BUILD_WIDTH / 2); gorilla = new Gorilla(new Vector2f(xx, Gorillas.FRAME_HEIGHT - skyline.getHeight(x1))); gorillb = new Gorilla(new Vector2f(yy, Gorillas.FRAME_HEIGHT - skyline.getHeight(x2))); sun = new Sun(new Vector2f(400, 60)); windSpeed = Game.getInstance().getWind() ? (int) ((Math.random() * 30) - 15) : 0; cloud = new Cloud(new Vector2f(0, 60), windSpeed); destroyBanana(); setActivePlayer(Game.getInstance().getPlayer(0)); state = STATES.INPUT; } void renderDebugShapes(GameContainer gc, StateBasedGame game, Graphics g) { // TODO: instead of explicitly drawing individual entities, draw all statemanager registered entity //for (Entity e : entityManager.getEntitiesByState(getID())) {g.draw(e.getShape());} g.draw(sun.getShape()); g.draw(skyline.getShape()); g.draw(gorilla.getShape()); g.draw(gorillb.getShape()); g.draw(cloud.getShape()); if (banana != null) g.draw(banana.getShape()); // Draw historical collisions debugCollisions.forEach(g::draw); } @Override public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException { if (Game.getInstance().isTestMode()) { return; } // Don't draw anything in testmode g.drawImage(background, -20, -10); g.setColor(Color.yellow); g.drawString(comment, 450, 20); g.drawString(score, 250, 20); entityManager.renderEntities(gc, game, g); sun.render(gc, game, g); skyline.render(gc, game, g); gorilla.render(gc, game, g); gorillb.render(gc, game, g); cloud.render(gc, game, g); if (Game.getInstance().getDebug()) { renderDebugShapes(gc, game, g); } if(banana != null) { banana.render(gc, game, g); if(banana.getShape().getMaxY() < 0) { g.drawImage(arrow, banana.getPosition().x - 8, 0); } } drawPlayerNames(g); if(state != STATES.THROW) { g.setColor(Color.blue); // Description for the buttons g.drawString("Speed", 20, 10); g.drawString("Angle ", 20, 50); } if(throwNumber != null) { g.setColor(Color.white); g.drawString(throwNumber,this.getRootPane().getWidth()-110,20); } if(roundWinMessage != null) { g.setColor(Color.red); g.drawString(roundWinMessage,this.getRootPane().getWidth()/2 - 150,100); } } /** * Draws text with a dropshadow * @param pos center position of the text */ private void drawTextWithDropShadow(Graphics g, Vector2f pos, String text, Color color) { // Center Text float x = pos.x - g.getFont().getWidth(text) / 2; // TODO: maybe translucent background // Draw Dropshadow g.setColor(Color.black); g.drawString(text, x + 1, pos.y - 1); // Draw Text g.setColor(color); g.drawString(text, x, pos.y); } private void drawPlayerNames(Graphics g) { for (int i = 0; i < Game.getInstance().getPlayers().size(); i++) { // Offset the Text 64 pixels higher then the gorrila // NOTE: Never modify the Vector that is retured from a .getPosition call Vector2f pos = getGorilla(i).getPosition(); Color color = getActivePlayer() == Game.getInstance().getPlayer(i) ? Color.yellow : Color.white; drawTextWithDropShadow(g, new Vector2f(pos.x, pos.y - 64), Game.getInstance().getPlayer(i).getName(), color); } } // TODO: more refactoring private final float MS_TO_S = 1.0f / 1000; private void updateThrowParameters(Input input, int delta) { if (input.isKeyPressed(Input.KEY_RETURN) || input.isKeyPressed(Input.KEY_SPACE)) { throwBanana(); } if(keyPressDelay > 0) { keyPressDelay -= delta * MS_TO_S; } else if (Game.getInstance().getInverseControlKeys()) { if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D)){ if_angle.setValue(if_angle.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A)){ if_angle.setValue(if_angle.getValue() - 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)){ if_speed.setValue(if_speed.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)){ if_speed.setValue(if_speed.getValue() - 1); keyPressDelay = keyPressWaitTime; } } else { if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D)){ if_speed.setValue(if_speed.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A)){ if_speed.setValue(if_speed.getValue() - 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)){ if_angle.setValue(if_angle.getValue() + 1); keyPressDelay = keyPressWaitTime; } if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)){ if_angle.setValue(if_angle.getValue() - 1); keyPressDelay = keyPressWaitTime; } } } @Override public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException { // Let the entities update their inputs first // Then process all remaining inputs entityManager.updateEntities(gc, game, delta); Input input = gc.getInput(); gorilla.update(gc, game, delta); gorillb.update(gc, game, delta); cloud.update(gc, game, delta); if(Game.getInstance().isDeveloper()) { /* DEBUG: Reroll the LevelGeneration */ if (input.isKeyPressed(Input.KEY_Q)) { startGame(); } // Win the Game if (input.isKeyPressed(Input.KEY_V) ) { getActivePlayer().setWin(); getActivePlayer().setWin(); getActivePlayer().setWin(); state = STATES.VICTORY; System.out.println("V Cheat"); } } /* Auf [ESC] muss unabhängig vom state reagiert werden */ if(input.isKeyPressed(Input.KEY_ESCAPE) || input.isKeyPressed(Input.KEY_P)) game.enterState(Game.INGAMEPAUSE); if(input.isKeyPressed(Input.KEY_M)) Game.getInstance().toggleMute(); switch (state) { case INPUT: throwNumber = "Throw Nr " + getActivePlayer().getThrow(); toggleUI(true); updateThrowParameters(input, delta); break; case THROW: throwNumber = "Throw Nr " + getActivePlayer().getThrow(); // During the flight disable inputs toggleUI(false); comment = ""; banana.update(gc, game, delta); sun.isCollidding(banana); // Bounds Check if(outsidePlayingField(banana, gc.getWidth(), gc.getHeight())) { state = STATES.DAMAGE; System.out.printf("OutOfBounds: pos(%.0f, %.0f), world(%d, %d)", banana.getPosition().x, banana.getPosition().y, gc.getWidth(), gc.getHeight() ); comment = "..."; } if(getActivePlayer() == Game.getInstance().getPlayer(1) && getGorilla(0).collides(banana)) { state = STATES.ROUNDVICTORY; System.out.println("Hit Player 1"); comment = "Treffer!"; } if(getActivePlayer() == Game.getInstance().getPlayer(0) && getGorilla(1).collides(banana)) { state = STATES.ROUNDVICTORY; System.out.println("Hit Player 2"); comment = "Treffer!"; } if(skyline.isCollidding(banana)) { state = STATES.DAMAGE; debugCollisions.add(new Circle(banana.getPosition().x, banana.getPosition().y, Game.getInstance().getExplosionRadius())); if(getActivePlayer() == Game.getInstance().getPlayer(1)){ if(banana.getPosition().getX() > gorilla.getPosition().getX() + 64) comment = "Viel zu kurz!"; else if(banana.getPosition().getX() < gorilla.getPosition().getX() - 64) comment = "Viel zu weit!"; if(banana.getPosition().getY() > gorilla.getPosition().getY() + 64) comment += " Viel zu tief!"; else if(banana.getPosition().getY() < gorilla.getPosition().getY() - 64) comment += " Viel zu hoch!"; if(comment == "") comment = "Fast getroffen!"; } else{ if(banana.getPosition().getX() > gorillb.getPosition().getX() + 64) comment = "Viel zu weit!"; else if(banana.getPosition().getX() < gorillb.getPosition().getX() - 64) comment = "Viel zu kurz!"; if(banana.getPosition().getY() > gorillb.getPosition().getY() + 64) comment += " Viel zu tief!"; else if(banana.getPosition().getY() < gorillb.getPosition().getY() - 64) comment += " Viel zu hoch!"; if(comment == "") comment = "Fast getroffen!"; } } break; case DAMAGE: System.out.println("Throw " + getActivePlayer().getName() + " Nr" + getActivePlayer().getThrow()); throwNumber = "Throw Nr " + getActivePlayer().getThrow(); // Ueberfluessig Game.getInstance().toggleNextPlayerActive(); if_speed.setValue(getActivePlayer().getLastSpeed()); if_angle.setValue(getActivePlayer().getLastAngle()); skyline.destroy((int)banana.getPosition().x, (int)banana.getPosition().y, Game.getInstance().getExplosionRadius()); playSound(explosionSound); destroyBanana(); // TODO: Claculate PlayerDamage // player1.damage(calcPlayerDamage(banana.getCenterX(), banana.getCenterY(), gorilla)); // player2.damage(calcPlayerDamage(banana.getCenterX(), banana.getCenterY(), gorillb)); state = STATES.INPUT; break; case ROUNDVICTORY: getActivePlayer().setWin(); totalRoundCounter += 1; if(getActivePlayer().getWin() > 2) state = STATES.VICTORY; else { System.out.println("Herzlichen Glückwunsch " + getActivePlayer().getName() + "\nSie haben die Runde gewonnen !"); System.out.println("Win Nr" + getActivePlayer().getWin()); roundWinMessage = "Herzlichen Glückwunsch " + getActivePlayer().getName() + "\nSie haben die Runde gewonnen !\n" + "Sieg Nummer " + getActivePlayer().getWin() + ".\n"+ "Sie benötigten " + getActivePlayer().getThrow() + " Würfe."; // TODO: Save Win and Throw-Number // Restart Game for (Player player : Game.getInstance().getPlayers()) { player.resetThrow(); player.setLastAngle(120); player.setLastSpeed(80); } score = "Score: " + Game.getInstance().getPlayer(0).getWin() + ":" + Game.getInstance().getPlayer(1).getWin(); if_speed.setValue(getActivePlayer().getLastSpeed()); if_angle.setValue(getActivePlayer().getLastAngle()); startGame(); } break; case VICTORY: // TODO: VICTORY System.out.println("Herzlichen Glückwunsch " + getActivePlayer().getName() + "\nSie haben das Spiel gewonnen !"); System.out.println("Win Nr" + getActivePlayer().getWin()); game.enterState(Game.GAMEVICTORY); // Store Win to SQL-DB SqlGorillas db = new SqlGorillas("data_gorillas.hsc","Gorillas"); db.insertHighScore(getActivePlayer().getName(), totalRoundCounter, getActivePlayer().getWin(), getActivePlayer().getTotalThrows()); // Reset Values totalRoundCounter = 0; break; } } /** Plays the passed sound, unless the audio is muted */ private void playSound(Sound sound) { if (!Game.getInstance().isMute() && sound != null) { sound.play(1f,Game.getInstance().getSoundVolume()); } } /** * Checks if the entity has left the playing field * Only checks Left/Right/Bottom */ Boolean outsidePlayingField(Entity entity, int screenWidth, int screenHeight) { return entity.getPosition().x > screenWidth || entity.getPosition().x < 0 || entity.getPosition().y > screenHeight; } @Override protected RootPane createRootPane() { // Needed for adding the new Input-Elements rp = super.createRootPane(); if_speed= new AdvancedValueAdjusterInt(); if_angle = new AdvancedValueAdjusterInt(); btnThrow = new Button("Throw"); if_speed.setMinMaxValue(0, 200); if_speed.setValue(80); validVelocity = true; if_angle.setMinMaxValue(0,180); if_angle.setValue(120); validAngle = true; // Wirkungslos btnThrow.setAlignment(Alignment.CENTER); btnThrow.addCallback(GamePlayState.this::throwBanana); // Add the Input-Elements to the RootPane rp.add(if_speed); rp.add(if_angle); rp.add(btnThrow); return rp; } @Override protected void layoutRootPane() { // Set Size and Position of the Input-Elements int basic_x=20; int basic_y=10; int basic_x_c=35; // Labels next to the inputs because of place-conflict the the skyscraper int pos=0; if_speed.setSize(100, 25); if_speed.setPosition(basic_x+60, basic_y+basic_x_c*pos); pos=1; if_angle.setSize(100, 25); if_angle.setPosition(basic_x+60, basic_y+basic_x_c*pos); pos=2; // Button kleiner und verschoben btnThrow.setSize(50, 25); btnThrow.setPosition(basic_x+60+20, basic_y+basic_x_c*pos); } private void toggleUI(Boolean enable) { btnThrow.setVisible(enable); if_speed.setEnabled(enable); if_angle.setEnabled(enable); if_speed.setVisible(enable); if_angle.setVisible(enable); } private void destroyBanana() { if (banana != null) { entityManager.removeEntity(getID(), banana); } banana = null; } /** Creates and assigns the Banana */ private void createBanana(Vector2f pos, float throwAngle, float throwSpeed, float gravity, float windAcceleration) { // Cleanup any remaining, Bananas since at the moment we can only have a maximum of 1 if (banana != null) {entityManager.removeEntity(getID(), banana);} banana = new Banana(pos, (int)throwAngle, (int)throwSpeed, gravity, (int)windAcceleration); entityManager.addEntity(getID(), banana); } /** Generates a Banana at the current Player */ public void throwBanana() { // Save new throw getActivePlayer().setThrow(); int speed = if_speed.getValue(); int angle = if_angle.getValue(); System.out.println("Throw Banana " + speed + " " + angle); getActivePlayer().setLastSpeed(speed); getActivePlayer().setLastAngle(angle); if (getActivePlayer() == Game.getInstance().getPlayer(0)) { Vector2f pos = getGorilla(0).getPosition(); Vector2f size = getGorilla(0).getSize(); createBanana(new Vector2f(pos.x, pos.y - size.y), angle - 90, speed, Game.getInstance().getGravity(), windSpeed); } else { Vector2f pos = getGorilla(1).getPosition(); Vector2f size = getGorilla(1).getSize(); createBanana(new Vector2f(pos.x, pos.y - size.y), 180 - angle + 90, speed, Game.getInstance().getGravity(), windSpeed); } // Remove Win-Message roundWinMessage = null; state = STATES.THROW; } // TESTS // HACK: This is dirty !_! private boolean validVelocity = false; private boolean validAngle = false; public void resetPlayerWidget() { if_speed.setValue(0); if_angle.setValue(0); validVelocity = false; validAngle = false; } public int getVelocity() { return validVelocity ? if_speed.getValue() : -1; } public void fillVelocityInput(char c) { if(verifyInput(if_speed.getValue(), if_speed.getMinValue(), if_speed.getMaxValue(), c)) { if_speed.setValue(if_speed.getValue() * 10 + Character.getNumericValue(c)); validVelocity = true; } } public int getAngle() { return validAngle ? if_angle.getValue() : -1; } public void fillAngleInput(char c) { if(verifyInput(if_angle.getValue(), if_angle.getMinValue(), if_angle.getMaxValue(), c)) { if_angle.setValue(if_angle.getValue() * 10 + Character.getNumericValue(c)); validAngle = true; } } /** This only works for positive numbers */ public boolean verifyInput(int oldValue, int min, int max, char c) { if (Character.isDigit(c)) { int newValue = oldValue * 10 + Character.getNumericValue(c); if (newValue <= max && newValue >= min) { return true; } } return false; } }
Sound insert
src/de/tu_darmstadt/gdi1/gorillas/ui/states/GamePlayState.java
Sound insert
<ide><path>rc/de/tu_darmstadt/gdi1/gorillas/ui/states/GamePlayState.java <ide> if_angle = new AdvancedValueAdjusterInt(); <ide> btnThrow = new Button("Throw"); <ide> <del> if_speed.setMinMaxValue(0, 200); <add> if_speed.setMinMaxValue(0,200); <ide> if_speed.setValue(80); <ide> validVelocity = true; <ide>
Java
lgpl-2.1
60dfe55dd653c2997a2c95da890ab72d1f218df3
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2007 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope.pattern; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import com.exedio.cope.AbstractLibTest; import com.exedio.cope.Feature; import com.exedio.cope.Model; import com.exedio.cope.StringField; public class MD5Test extends AbstractLibTest { public/*for web.xml*/ static final Model MODEL = new Model(MD5Item.TYPE); public MD5Test() { super(MODEL); } MD5Item item; @Override public void setUp() throws Exception { super.setUp(); deleteOnTearDown(item = new MD5Item()); } public void testMD5() { assertEquals("000ff0aa", JavaSecurityHash.encodeBytes(new byte[]{0x00, 0x0F, (byte)0xF0, (byte)0xAA})); assertEquals("0123456789abcdef", JavaSecurityHash.encodeBytes(new byte[]{0x01, 0x23, 0x45, 0x67, (byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef})); assertEquals(Arrays.asList(new Feature[]{ item.TYPE.getThis(), item.password, item.password.getStorage(), item.hashed1MD5, item.hashed1, item.hashed1Latin, }), item.TYPE.getFeatures()); assertEquals(item.TYPE, item.password.getType()); assertEquals("password", item.password.getName()); assertEquals(item.TYPE, item.password.getStorage().getType()); assertEquals("passwordHash", item.password.getStorage().getName()); assertEquals(false, item.password.getStorage().isFinal()); assertEquals(false, item.password.getStorage().isMandatory()); assertEquals(32, item.password.getStorage().getMinimumLength()); assertEquals(32, item.password.getStorage().getMaximumLength()); assertEqualsUnmodifiable(list(item.password), item.password.getStorage().getPatterns()); assertEquals(false, item.password.isInitial()); assertEquals(false, item.password.isFinal()); assertEquals(false, item.password.isMandatory()); assertContains(item.password.getSetterExceptions()); assertEquals("utf8", item.password.getEncoding()); assertEquals(item.TYPE, item.hashed1.getType()); assertEquals(item.TYPE, item.hashed1Latin.getType()); assertEquals("hashed1", item.hashed1.getName()); assertEquals("hashed1Latin", item.hashed1Latin.getName()); assertEquals(item.hashed1MD5, item.hashed1.getStorage()); assertEquals(item.hashed1MD5, item.hashed1Latin.getStorage()); assertEqualsUnmodifiable(list(item.hashed1, item.hashed1Latin), item.hashed1MD5.getPatterns()); assertEquals(false, item.hashed1.isInitial()); assertEquals(false, item.hashed1Latin.isInitial()); assertEquals(false, item.hashed1.isFinal()); assertEquals(false, item.hashed1Latin.isFinal()); assertEquals(false, item.hashed1.isMandatory()); assertEquals(false, item.hashed1Latin.isMandatory()); assertContains(item.hashed1.getSetterExceptions()); assertContains(item.hashed1Latin.getSetterExceptions()); assertEquals("utf8", item.hashed1.getEncoding()); assertEquals("ISO-8859-1", item.hashed1Latin.getEncoding()); try { new MD5Hash(new StringField(), "nixus"); fail(); } catch(IllegalArgumentException e) { assertEquals(UnsupportedEncodingException.class.getName()+": nixus", e.getMessage()); assertEquals(UnsupportedEncodingException.class, e.getCause().getClass()); } try { new JavaSecurityHash(new StringField(), "NIXUS"); fail(); } catch(IllegalArgumentException e) { assertEquals(NoSuchAlgorithmException.class.getName()+": NIXUS MessageDigest not available", e.getMessage()); assertEquals(NoSuchAlgorithmException.class, e.getCause().getClass()); } assertNull(item.getHashed1MD5()); assertTrue(item.checkHashed1(null)); assertTrue(!item.checkHashed1("bing")); assertContains(item, item.TYPE.search(item.hashed1.equal(null))); assertContains(item.TYPE.search(item.hashed1.equal("bing"))); item.setHashed1MD5("bello"); assertEquals("bello", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertContains(item.TYPE.search(item.hashed1.equal(null))); assertContains(item.TYPE.search(item.hashed1.equal("bello"))); item.setHashed1("knollo"); assertEquals("ad373a47d81949f466552edf29499b32", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertTrue(item.checkHashed1("knollo")); assertContains(item.TYPE.search(item.hashed1.equal(null))); assertContains(item.TYPE.search(item.hashed1.equal("bello"))); assertContains(item, item.TYPE.search(item.hashed1.equal("knollo"))); final String longPlainText = "knolloknolloknolloknolloknolloknolloknolloknolloknolloknolloknollo" + "knolloknolloknolloknolloknolloknolloknolloknolloknolloknolloknollo" + "knolloknolloknolloknolloknollo"; item.setHashed1(longPlainText); assertEquals("6ce62d0dbd8e8b3f453ba742c102cd0b", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertTrue(item.checkHashed1(longPlainText)); // Test, that special characters produce different hashes // with different pre-MD5 encodings. final String specialPlainText = "Viele Gr\u00fc\u00dfe"; item.setHashed1(specialPlainText); assertEquals("b6f7c12664a57ad17298068b62c9053c", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertTrue(item.checkHashed1(specialPlainText)); assertTrue(!item.checkHashed1Latin(specialPlainText)); item.setHashed1Latin(specialPlainText); assertEquals("f80281c9b755508af7c42f585ed76e23", item.getHashed1MD5()); assertTrue(!item.checkHashed1Latin(null)); assertTrue(!item.checkHashed1Latin("bello")); assertTrue(item.checkHashed1Latin(specialPlainText)); assertTrue(!item.checkHashed1(specialPlainText)); } /** * reference example from http://de.wikipedia.org/wiki/MD5 */ public void testWikipedia() { final String appendix = "ranz jagt im komplett verwahrlosten Taxi quer durch Bayern"; final String upper = "F" + appendix; final String lower = "f" + appendix; assertEquals(null, item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertTrue(item.checkPassword(null)); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item, item.TYPE.search(item.password.equal(null))); assertContains(item.TYPE.search(item.password.notEqual(upper))); assertContains(item.TYPE.search(item.password.notEqual(lower))); assertContains(item.TYPE.search(item.password.notEqual(""))); assertContains(item.TYPE.search(item.password.notEqual(null))); item.setPassword(upper); assertEquals("a3cca2b2aa1e3b5b3b5aad99a8529074", item.getPasswordHash()); assertTrue(item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertTrue(!item.checkPassword(null)); assertContains(item, item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item.TYPE.search(item.password.equal(null))); assertContains(item.TYPE.search(item.password.notEqual(upper))); assertContains(item, item.TYPE.search(item.password.notEqual(lower))); assertContains(item, item.TYPE.search(item.password.notEqual(""))); assertContains(item, item.TYPE.search(item.password.notEqual(null))); item.setPassword(lower); assertEquals("4679e94e07f9a61f42b3d7f50cae0aef", item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertTrue(!item.checkPassword(null)); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item, item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item.TYPE.search(item.password.equal(null))); assertContains(item, item.TYPE.search(item.password.notEqual(upper))); assertContains(item.TYPE.search(item.password.notEqual(lower))); assertContains(item, item.TYPE.search(item.password.notEqual(""))); assertContains(item, item.TYPE.search(item.password.notEqual(null))); item.setPasswordHash("12345678901234567890123456789012"); assertEquals("12345678901234567890123456789012", item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertTrue(!item.checkPassword(null)); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item.TYPE.search(item.password.equal(null))); assertContains(item, item.TYPE.search(item.password.notEqual(upper))); assertContains(item, item.TYPE.search(item.password.notEqual(lower))); assertContains(item, item.TYPE.search(item.password.notEqual(""))); assertContains(item, item.TYPE.search(item.password.notEqual(null))); item.setPassword(""); assertEquals("d41d8cd98f00b204e9800998ecf8427e", item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(item.checkPassword("")); assertTrue(!item.checkPassword(null)); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item, item.TYPE.search(item.password.equal(""))); assertContains(item.TYPE.search(item.password.equal(null))); assertContains(item, item.TYPE.search(item.password.notEqual(upper))); assertContains(item, item.TYPE.search(item.password.notEqual(lower))); assertContains(item.TYPE.search(item.password.notEqual(""))); assertContains(item, item.TYPE.search(item.password.notEqual(null))); } }
runtime/testsrc/com/exedio/cope/pattern/MD5Test.java
/* * Copyright (C) 2004-2007 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope.pattern; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import com.exedio.cope.AbstractLibTest; import com.exedio.cope.Feature; import com.exedio.cope.Model; import com.exedio.cope.StringField; public class MD5Test extends AbstractLibTest { public/*for web.xml*/ static final Model MODEL = new Model(MD5Item.TYPE); public MD5Test() { super(MODEL); } MD5Item item; @Override public void setUp() throws Exception { super.setUp(); deleteOnTearDown(item = new MD5Item()); } public void testMD5() { assertEquals("000ff0aa", JavaSecurityHash.encodeBytes(new byte[]{0x00, 0x0F, (byte)0xF0, (byte)0xAA})); assertEquals("0123456789abcdef", JavaSecurityHash.encodeBytes(new byte[]{0x01, 0x23, 0x45, 0x67, (byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef})); assertEquals(Arrays.asList(new Feature[]{ item.TYPE.getThis(), item.password, item.password.getStorage(), item.hashed1MD5, item.hashed1, item.hashed1Latin, }), item.TYPE.getFeatures()); assertEquals(item.TYPE, item.password.getType()); assertEquals("password", item.password.getName()); assertEquals(item.TYPE, item.password.getStorage().getType()); assertEquals("passwordHash", item.password.getStorage().getName()); assertEquals(false, item.password.getStorage().isFinal()); assertEquals(false, item.password.getStorage().isMandatory()); assertEquals(32, item.password.getStorage().getMinimumLength()); assertEquals(32, item.password.getStorage().getMaximumLength()); assertEqualsUnmodifiable(list(item.password), item.password.getStorage().getPatterns()); assertEquals(false, item.password.isInitial()); assertEquals(false, item.password.isFinal()); assertEquals(false, item.password.isMandatory()); assertContains(item.password.getSetterExceptions()); assertEquals("utf8", item.password.getEncoding()); assertEquals(item.TYPE, item.hashed1.getType()); assertEquals(item.TYPE, item.hashed1Latin.getType()); assertEquals("hashed1", item.hashed1.getName()); assertEquals("hashed1Latin", item.hashed1Latin.getName()); assertEquals(item.hashed1MD5, item.hashed1.getStorage()); assertEquals(item.hashed1MD5, item.hashed1Latin.getStorage()); assertEqualsUnmodifiable(list(item.hashed1, item.hashed1Latin), item.hashed1MD5.getPatterns()); assertEquals(false, item.hashed1.isInitial()); assertEquals(false, item.hashed1Latin.isInitial()); assertEquals(false, item.hashed1.isFinal()); assertEquals(false, item.hashed1Latin.isFinal()); assertEquals(false, item.hashed1.isMandatory()); assertEquals(false, item.hashed1Latin.isMandatory()); assertContains(item.hashed1.getSetterExceptions()); assertContains(item.hashed1Latin.getSetterExceptions()); assertEquals("utf8", item.hashed1.getEncoding()); assertEquals("ISO-8859-1", item.hashed1Latin.getEncoding()); try { new MD5Hash(new StringField(), "nixus"); fail(); } catch(IllegalArgumentException e) { assertEquals(UnsupportedEncodingException.class.getName()+": nixus", e.getMessage()); assertEquals(UnsupportedEncodingException.class, e.getCause().getClass()); } try { new JavaSecurityHash(new StringField(), "NIXUS"); fail(); } catch(IllegalArgumentException e) { assertEquals(NoSuchAlgorithmException.class.getName()+": NIXUS MessageDigest not available", e.getMessage()); assertEquals(NoSuchAlgorithmException.class, e.getCause().getClass()); } assertNull(item.getHashed1MD5()); assertTrue(item.checkHashed1(null)); assertTrue(!item.checkHashed1("bing")); assertContains(item, item.TYPE.search(item.hashed1.equal(null))); assertContains(item.TYPE.search(item.hashed1.equal("bing"))); item.setHashed1MD5("bello"); assertEquals("bello", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertContains(item.TYPE.search(item.hashed1.equal(null))); assertContains(item.TYPE.search(item.hashed1.equal("bello"))); item.setHashed1("knollo"); assertEquals("ad373a47d81949f466552edf29499b32", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertTrue(item.checkHashed1("knollo")); assertContains(item.TYPE.search(item.hashed1.equal(null))); assertContains(item.TYPE.search(item.hashed1.equal("bello"))); assertContains(item, item.TYPE.search(item.hashed1.equal("knollo"))); final String longPlainText = "knolloknolloknolloknolloknolloknolloknolloknolloknolloknolloknollo" + "knolloknolloknolloknolloknolloknolloknolloknolloknolloknolloknollo" + "knolloknolloknolloknolloknollo"; item.setHashed1(longPlainText); assertEquals("6ce62d0dbd8e8b3f453ba742c102cd0b", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertTrue(item.checkHashed1(longPlainText)); // Test, that special characters produce different hashes // with different pre-MD5 encodings. final String specialPlainText = "Viele Gr\u00fc\u00dfe"; item.setHashed1(specialPlainText); assertEquals("b6f7c12664a57ad17298068b62c9053c", item.getHashed1MD5()); assertTrue(!item.checkHashed1(null)); assertTrue(!item.checkHashed1("bello")); assertTrue(item.checkHashed1(specialPlainText)); assertTrue(!item.checkHashed1Latin(specialPlainText)); item.setHashed1Latin(specialPlainText); assertEquals("f80281c9b755508af7c42f585ed76e23", item.getHashed1MD5()); assertTrue(!item.checkHashed1Latin(null)); assertTrue(!item.checkHashed1Latin("bello")); assertTrue(item.checkHashed1Latin(specialPlainText)); assertTrue(!item.checkHashed1(specialPlainText)); } /** * reference example from http://de.wikipedia.org/wiki/MD5 */ public void testWikipedia() { final String appendix = "ranz jagt im komplett verwahrlosten Taxi quer durch Bayern"; final String upper = "F" + appendix; final String lower = "f" + appendix; assertEquals(null, item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item.TYPE.search(item.password.notEqual(upper))); assertContains(item.TYPE.search(item.password.notEqual(lower))); assertContains(item.TYPE.search(item.password.notEqual(""))); item.setPassword(upper); assertEquals("a3cca2b2aa1e3b5b3b5aad99a8529074", item.getPasswordHash()); assertTrue(item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertContains(item, item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item.TYPE.search(item.password.notEqual(upper))); assertContains(item, item.TYPE.search(item.password.notEqual(lower))); assertContains(item, item.TYPE.search(item.password.notEqual(""))); item.setPassword(lower); assertEquals("4679e94e07f9a61f42b3d7f50cae0aef", item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item, item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item, item.TYPE.search(item.password.notEqual(upper))); assertContains(item.TYPE.search(item.password.notEqual(lower))); assertContains(item, item.TYPE.search(item.password.notEqual(""))); item.setPasswordHash("12345678901234567890123456789012"); assertEquals("12345678901234567890123456789012", item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(!item.checkPassword("")); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item.TYPE.search(item.password.equal(""))); assertContains(item, item.TYPE.search(item.password.notEqual(upper))); assertContains(item, item.TYPE.search(item.password.notEqual(lower))); assertContains(item, item.TYPE.search(item.password.notEqual(""))); item.setPassword(""); assertEquals("d41d8cd98f00b204e9800998ecf8427e", item.getPasswordHash()); assertTrue(!item.checkPassword(upper)); assertTrue(!item.checkPassword(lower)); assertTrue(item.checkPassword("")); assertContains(item.TYPE.search(item.password.equal(upper))); assertContains(item.TYPE.search(item.password.equal(lower))); assertContains(item, item.TYPE.search(item.password.equal(""))); assertContains(item, item.TYPE.search(item.password.notEqual(upper))); assertContains(item, item.TYPE.search(item.password.notEqual(lower))); assertContains(item.TYPE.search(item.password.notEqual(""))); } }
test with null (2) git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@8663 e7d4fc99-c606-0410-b9bf-843393a9eab7
runtime/testsrc/com/exedio/cope/pattern/MD5Test.java
test with null (2)
<ide><path>untime/testsrc/com/exedio/cope/pattern/MD5Test.java <ide> assertTrue(!item.checkPassword(upper)); <ide> assertTrue(!item.checkPassword(lower)); <ide> assertTrue(!item.checkPassword("")); <del> assertContains(item.TYPE.search(item.password.equal(upper))); <del> assertContains(item.TYPE.search(item.password.equal(lower))); <del> assertContains(item.TYPE.search(item.password.equal(""))); <add> assertTrue(item.checkPassword(null)); <add> assertContains(item.TYPE.search(item.password.equal(upper))); <add> assertContains(item.TYPE.search(item.password.equal(lower))); <add> assertContains(item.TYPE.search(item.password.equal(""))); <add> assertContains(item, item.TYPE.search(item.password.equal(null))); <ide> assertContains(item.TYPE.search(item.password.notEqual(upper))); <ide> assertContains(item.TYPE.search(item.password.notEqual(lower))); <ide> assertContains(item.TYPE.search(item.password.notEqual(""))); <add> assertContains(item.TYPE.search(item.password.notEqual(null))); <ide> <ide> item.setPassword(upper); <ide> assertEquals("a3cca2b2aa1e3b5b3b5aad99a8529074", item.getPasswordHash()); <ide> assertTrue(item.checkPassword(upper)); <ide> assertTrue(!item.checkPassword(lower)); <ide> assertTrue(!item.checkPassword("")); <add> assertTrue(!item.checkPassword(null)); <ide> assertContains(item, item.TYPE.search(item.password.equal(upper))); <ide> assertContains(item.TYPE.search(item.password.equal(lower))); <ide> assertContains(item.TYPE.search(item.password.equal(""))); <add> assertContains(item.TYPE.search(item.password.equal(null))); <ide> assertContains(item.TYPE.search(item.password.notEqual(upper))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(lower))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(""))); <add> assertContains(item, item.TYPE.search(item.password.notEqual(null))); <ide> <ide> item.setPassword(lower); <ide> assertEquals("4679e94e07f9a61f42b3d7f50cae0aef", item.getPasswordHash()); <ide> assertTrue(!item.checkPassword(upper)); <ide> assertTrue(item.checkPassword(lower)); <ide> assertTrue(!item.checkPassword("")); <add> assertTrue(!item.checkPassword(null)); <ide> assertContains(item.TYPE.search(item.password.equal(upper))); <ide> assertContains(item, item.TYPE.search(item.password.equal(lower))); <ide> assertContains(item.TYPE.search(item.password.equal(""))); <add> assertContains(item.TYPE.search(item.password.equal(null))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(upper))); <ide> assertContains(item.TYPE.search(item.password.notEqual(lower))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(""))); <add> assertContains(item, item.TYPE.search(item.password.notEqual(null))); <ide> <ide> item.setPasswordHash("12345678901234567890123456789012"); <ide> assertEquals("12345678901234567890123456789012", item.getPasswordHash()); <ide> assertTrue(!item.checkPassword(upper)); <ide> assertTrue(!item.checkPassword(lower)); <ide> assertTrue(!item.checkPassword("")); <del> assertContains(item.TYPE.search(item.password.equal(upper))); <del> assertContains(item.TYPE.search(item.password.equal(lower))); <del> assertContains(item.TYPE.search(item.password.equal(""))); <add> assertTrue(!item.checkPassword(null)); <add> assertContains(item.TYPE.search(item.password.equal(upper))); <add> assertContains(item.TYPE.search(item.password.equal(lower))); <add> assertContains(item.TYPE.search(item.password.equal(""))); <add> assertContains(item.TYPE.search(item.password.equal(null))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(upper))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(lower))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(""))); <add> assertContains(item, item.TYPE.search(item.password.notEqual(null))); <ide> <ide> item.setPassword(""); <ide> assertEquals("d41d8cd98f00b204e9800998ecf8427e", item.getPasswordHash()); <ide> assertTrue(!item.checkPassword(upper)); <ide> assertTrue(!item.checkPassword(lower)); <ide> assertTrue(item.checkPassword("")); <add> assertTrue(!item.checkPassword(null)); <ide> assertContains(item.TYPE.search(item.password.equal(upper))); <ide> assertContains(item.TYPE.search(item.password.equal(lower))); <ide> assertContains(item, item.TYPE.search(item.password.equal(""))); <add> assertContains(item.TYPE.search(item.password.equal(null))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(upper))); <ide> assertContains(item, item.TYPE.search(item.password.notEqual(lower))); <ide> assertContains(item.TYPE.search(item.password.notEqual(""))); <add> assertContains(item, item.TYPE.search(item.password.notEqual(null))); <ide> } <ide> }
Java
bsd-3-clause
bcb6e9267b3a55d39729e160fa1f36a47a95d471
0
yushan87/RESOLVE,yushan87/RESOLVE,ClemsonRSRG/RESOLVE,NighatYasmin/RESOLVE,ClemsonRSRG/RESOLVE,NighatYasmin/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE
/* * VerificationContext.java * --------------------------------- * Copyright (c) 2017 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.rsrg.vcgeneration.utilities; import edu.clemson.cs.rsrg.absyn.clauses.AssertionClause; import edu.clemson.cs.rsrg.absyn.declarations.Dec; import edu.clemson.cs.rsrg.absyn.declarations.facilitydecl.FacilityDec; import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.*; import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ConstantParamDec; import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ModuleParameterDec; import edu.clemson.cs.rsrg.absyn.declarations.sharedstatedecl.SharedStateDec; import edu.clemson.cs.rsrg.absyn.declarations.sharedstatedecl.SharedStateRealizationDec; import edu.clemson.cs.rsrg.absyn.declarations.typedecl.AbstractTypeRepresentationDec; import edu.clemson.cs.rsrg.absyn.declarations.typedecl.TypeFamilyDec; import edu.clemson.cs.rsrg.absyn.declarations.variabledecl.MathVarDec; import edu.clemson.cs.rsrg.absyn.expressions.Exp; import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.VarExp; import edu.clemson.cs.rsrg.absyn.rawtypes.NameTy; import edu.clemson.cs.rsrg.init.CompileEnvironment; import edu.clemson.cs.rsrg.parsing.data.BasicCapabilities; import edu.clemson.cs.rsrg.parsing.data.Location; import edu.clemson.cs.rsrg.parsing.data.LocationDetailModel; import edu.clemson.cs.rsrg.parsing.data.PosSymbol; import edu.clemson.cs.rsrg.typeandpopulate.entry.ProgramTypeEntry; import edu.clemson.cs.rsrg.typeandpopulate.entry.SymbolTableEntry; import edu.clemson.cs.rsrg.typeandpopulate.exception.NoSuchSymbolException; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.MathSymbolTableBuilder; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.ModuleScope; import edu.clemson.cs.rsrg.typeandpopulate.utilities.ModuleIdentifier; import edu.clemson.cs.rsrg.vcgeneration.utilities.formaltoactual.InstantiatedFacilityDecl; import java.util.*; import static edu.clemson.cs.rsrg.vcgeneration.VCGenerator.FLAG_ADD_CONSTRAINT; /** * <p>This class contains all the module-level items relevant to the * file we are generating VCs for.</p> * * @author Yu-Shan Sun * @version 1.0 */ public class VerificationContext implements BasicCapabilities, Cloneable { // =========================================================== // Member Fields // =========================================================== /** <p>The symbol table we are currently building.</p> */ private final MathSymbolTableBuilder myBuilder; /** * <p>The current job's compilation environment * that stores all necessary objects and flags.</p> */ private final CompileEnvironment myCompileEnvironment; /** * <p>The module scope for the file we are generating * {@code VCs} for.</p> */ private final ModuleScope myCurrentModuleScope; /** <p>The name of the current module we are generating VCs for.</p> */ private final PosSymbol myName; // ----------------------------------------------------------- // Module Level Requires and Constraint Clauses // ----------------------------------------------------------- /** * <p>A list that stores all the module level {@code constraint} * clauses for the various different declarations.</p> */ private final Map<Dec, List<AssertionClause>> myModuleLevelConstraints; /** * <p>A map that stores all the details associated with * a particular module level {@link AssertionClause}.</p> */ private final Map<AssertionClause, LocationDetailModel> myModuleLevelLocationDetails; /** * <p>A list that stores all the module level {@code requires} * clauses.</p> */ private final List<AssertionClause> myModuleLevelRequires; // ----------------------------------------------------------- // Processed Facility Declarations // ----------------------------------------------------------- /** <p>The list of processed {@link InstantiatedFacilityDecl}. </p> */ private final List<InstantiatedFacilityDecl> myProcessedInstFacilityDecls; // ----------------------------------------------------------- // Shared State Declarations and Representations // ----------------------------------------------------------- /** <p>This contains all the shared state declared by the {@code Concept}.</p> */ private final List<SharedStateDec> myConceptSharedStates; /** * <p>If our current module scope allows us to introduce new shared state realizations, * this will contain all the {@link SharedStateRealizationDec}. Otherwise, * this list will be empty.</p> */ private final List<SharedStateRealizationDec> myLocalSharedStateRealizationDecs; // ----------------------------------------------------------- // Type Declarations and Representations // ----------------------------------------------------------- /** * <p>This contains all the types declared by the {@code Concept} * associated with the current module. Note that if we are in a * {@code Facility}, this list will be empty.</p> */ private final List<TypeFamilyDec> myConceptDeclaredTypes; /** * <p>If our current module scope allows us to introduce new type implementations, * this will contain all the {@link AbstractTypeRepresentationDec}. Otherwise, * this list will be empty.</p> */ private final List<AbstractTypeRepresentationDec> myLocalTypeRepresentationDecs; // =========================================================== // Constructors // =========================================================== /** * <p>This creates a verification context that stores all * the relevant information related to the module we are generating * {@code VCs} for.</p> * * @param name Name of the module we are generating VCs for. * @param moduleScope The module scope associated with {@code name}. * @param builder A scope builder for a symbol table. * @param compileEnvironment The current job's compilation environment * that stores all necessary objects and flags. */ public VerificationContext(PosSymbol name, ModuleScope moduleScope, MathSymbolTableBuilder builder, CompileEnvironment compileEnvironment) { myBuilder = builder; myCompileEnvironment = compileEnvironment; myConceptDeclaredTypes = new LinkedList<>(); myConceptSharedStates = new LinkedList<>(); myCurrentModuleScope = moduleScope; myLocalSharedStateRealizationDecs = new LinkedList<>(); myLocalTypeRepresentationDecs = new LinkedList<>(); myModuleLevelConstraints = new LinkedHashMap<>(); myModuleLevelLocationDetails = new LinkedHashMap<>(); myModuleLevelRequires = new LinkedList<>(); myName = name; myProcessedInstFacilityDecls = new LinkedList<>(); } // =========================================================== // Public Methods // =========================================================== /** * <p>This method creates a special indented * text version of the instantiated object.</p> * * @param indentSize The base indentation to the first line * of the text. * @param innerIndentInc The additional indentation increment * for the subsequent lines. * * @return A formatted text string of the class. */ @Override public final String asString(int indentSize, int innerIndentInc) { return ""; } /** * <p>This method uses all the {@code requires} and {@code constraint} * clauses from the various different sources (see below for complete list) * and builds the appropriate {@code assume} clause that goes at the * beginning an {@link AssertiveCodeBlock}.</p> * * <p>List of different places where clauses can originate from:</p> * <ul> * <li>{@code Concept}'s {@code requires} clause.</li> * <li>{@code Concept}'s module {@code constraint} clause.</li> * <li>{@code Shared Variables}' {@code constraint} clause.</li> * <li>{@code Concept Realization}'s {@code requires} clause.</li> * <li>{@code Shared Variables}' {@code convention} clause.</li> * <li>{@code Shared Variables}' {@code correspondence} clause.</li> * <li>{@code constraint} clauses for all the parameters with the * appropriate substitutions made.</li> * <li>Any {@code which_entails} expressions that originated from any of the * clauses above.</li> * </ul> * * @param loc The location in the AST that we are * currently visiting. * @param addSharedConventionFlag A flag that indicates whether or not we need * to add the {@code Shared Variable}'s {@code convention}. * @param addSharedCorrespondenceFlag A flag that indicates whether or not we need * to add the {@code Shared Variable}'s {@code correspondence}. * * @return The top-level assumed expression. */ public final Exp createTopLevelAssumeExpFromContext(Location loc, boolean addSharedConventionFlag, boolean addSharedCorrespondenceFlag) { Exp retExp = null; // Add all the module level requires clause. for (AssertionClause clause : myModuleLevelRequires) { retExp = Utilities.formConjunct(loc, retExp, clause, myModuleLevelLocationDetails.get(clause)); } // Add all the module level constraint clauses. for (Dec dec : myModuleLevelConstraints.keySet()) { for (AssertionClause clause : myModuleLevelConstraints.get(dec)) { retExp = Utilities.formConjunct(loc, retExp, clause, myModuleLevelLocationDetails.get(clause)); } } // Add all share variable's constraints. // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { // Add any facility instantiated shared state constraints for (InstantiatedFacilityDecl facilityDecl : myProcessedInstFacilityDecls) { for (SharedStateDec stateDec : facilityDecl .getConceptSharedStates()) { AssertionClause stateConstraintClause = stateDec.getConstraint(); // All shared variables should be add facilityDecl's name. Map<Exp, Exp> substitutions = new LinkedHashMap<>(); for (MathVarDec mathVarDec : stateDec.getAbstractStateVars()) { // Convert mathVarDec to VarExp. Also create a new qualified version of it. VarExp mathVarDecAsVarExp = Utilities.createVarExp(mathVarDec.getLocation().clone(), null, mathVarDec.getName().clone(), mathVarDec.getMathType(), null); VarExp qualifiedVarExp = (VarExp) mathVarDecAsVarExp.clone(); qualifiedVarExp.setQualifier(facilityDecl.getInstantiatedFacilityName().clone()); // Put them into our substitutions map. substitutions.put(mathVarDecAsVarExp, qualifiedVarExp); } // Generate the proper facility qualified constraint // and which_entails clauses (if any). Exp modifiedConstraint = stateConstraintClause.getAssertionExp().substitute(substitutions); Exp modifiedWhichEntails = stateConstraintClause.getWhichEntailsExp(); if (modifiedWhichEntails != null) { modifiedWhichEntails = modifiedWhichEntails.substitute(substitutions); } // Create the modified state constraint clause and add it to the retExp. AssertionClause modifiedStateConstraintClause = new AssertionClause(stateConstraintClause.getLocation().clone(), stateConstraintClause.getClauseType(), modifiedConstraint, modifiedWhichEntails); retExp = Utilities.formConjunct(loc, retExp, modifiedStateConstraintClause, myModuleLevelLocationDetails .get(stateConstraintClause)); } } // Add concept shared state constraints for (SharedStateDec stateDec : myConceptSharedStates) { AssertionClause stateConstraintClause = stateDec.getConstraint(); retExp = Utilities.formConjunct(loc, retExp, stateConstraintClause, myModuleLevelLocationDetails .get(stateConstraintClause)); } } // Process any local shared state realizations for (SharedStateRealizationDec sharedStateRealizationDec : myLocalSharedStateRealizationDecs) { // Add the share variable realization's convention if requested. if (addSharedConventionFlag) { AssertionClause stateConventionClause = sharedStateRealizationDec.getConvention(); retExp = Utilities.formConjunct(loc, retExp, stateConventionClause, myModuleLevelLocationDetails .get(stateConventionClause)); } // Add the shared variable realization's correspondence if requested. if (addSharedCorrespondenceFlag) { AssertionClause stateCorrespondenceClause = sharedStateRealizationDec.getCorrespondence(); retExp = Utilities.formConjunct(loc, retExp, stateCorrespondenceClause, myModuleLevelLocationDetails .get(stateCorrespondenceClause)); } } return retExp; } /** * <p>This method returns a list containing the various * {@link TypeFamilyDec TypeFamilyDecs} in the current context.</p> * * @return A list containing {@link TypeFamilyDec TypeFamilyDecs}. */ public final List<TypeFamilyDec> getConceptDeclaredTypes() { return myConceptDeclaredTypes; } /** * <p>This method returns a list containing the various * {@link SharedStateDec SharedStateDecs} in the current context.</p> * * @return A list containing {@link SharedStateDec SharedStateDecs}. */ public final List<SharedStateDec> getConceptSharedVars() { return myConceptSharedStates; } /** * <p>This method returns a list containing the various * {@link SharedStateRealizationDec SharedStateRealizationDecs} * in the current context.</p> * * @return A list containing {@link SharedStateRealizationDec SharedStateRealizationDecs}. */ public final List<SharedStateRealizationDec> getLocalSharedStateRealizationDecs() { return myLocalSharedStateRealizationDecs; } /** * <p>This method returns a list containing the various * {@link AbstractTypeRepresentationDec AbstractTypeRepresentationDecs} * in the current context.</p> * * @return A list containing {@link AbstractTypeRepresentationDec AbstractTypeRepresentationDecs}. */ public final List<AbstractTypeRepresentationDec> getLocalTypeRepresentationDecs() { return myLocalTypeRepresentationDecs; } /** * <p>This method returns a list of all instantiated {@code Facilities}.</p> * * @return A list of {@link InstantiatedFacilityDecl} containing all the information. */ public final List<InstantiatedFacilityDecl> getProcessedInstFacilityDecls() { return myProcessedInstFacilityDecls; } /** * <p>This method stores a {@code concept}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code concept}. * @param id A {@link ModuleIdentifier} referring to a * {@code concept}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeConceptAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { ConceptModuleDec conceptModuleDec = (ConceptModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if the concept didn't originate from // a facility declaration. if (!isFacilityImport) { // Store the concept's requires clause storeRequiresClause(conceptModuleDec.getName().getName(), conceptModuleDec.getRequires()); // Store the concept's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(conceptModuleDec .getLocation(), conceptModuleDec.getParameterDecs()); } } // Store the concept's module constraints and // its associated location detail for future use. if (!conceptModuleDec.getConstraints().isEmpty()) { myModuleLevelConstraints.put(conceptModuleDec, conceptModuleDec .getConstraints()); for (AssertionClause constraint : conceptModuleDec .getConstraints()) { Location constraintLoc = constraint.getAssertionExp().getLocation(); myModuleLevelLocationDetails.put(constraint, new LocationDetailModel(constraintLoc.clone(), constraintLoc.clone(), "Constraint Clause of " + conceptModuleDec.getName())); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code concept realization}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code concept realization}. * @param id A {@link ModuleIdentifier} referring to a * {@code concept realization}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeConceptRealizAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { ConceptRealizModuleDec realizModuleDec = (ConceptRealizModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if they are part of a FacilityDec if (!isFacilityImport) { // Store the concept realization's requires clause storeRequiresClause(realizModuleDec.getName().getName(), realizModuleDec.getRequires()); // Store the concept realization's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(realizModuleDec .getLocation(), realizModuleDec.getParameterDecs()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code concept's} * {@code Shared Variables} declarations for future use.</p> * * @param dec A {@link SharedStateDec} declared in a {@code Concept}. */ public final void storeConceptSharedStateDec(SharedStateDec dec) { myConceptSharedStates.add((SharedStateDec) dec.clone()); } /** * <p>This method stores the imported {@code concept's} * {@code Shared Variables} declarations for future use.</p> * * @param loc The location of the imported {@code module}. * @param id A {@link ModuleIdentifier} referring to an * importing {@code concept}. */ public final void storeConceptSharedStateDecs(Location loc, ModuleIdentifier id) { try { ConceptModuleDec conceptModuleDec = (ConceptModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); List<Dec> decs = conceptModuleDec.getDecList(); for (Dec dec : decs) { if (dec instanceof SharedStateDec) { myConceptSharedStates.add((SharedStateDec) dec.clone()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code concept's} * {@code Type Family} declarations for future use.</p> * * @param dec A type family declared in a {@code Concept}. */ public final void storeConceptTypeFamilyDec(TypeFamilyDec dec) { myConceptDeclaredTypes.add((TypeFamilyDec) dec.clone()); } /** * <p>This method stores the imported {@code concept's} * {@code Type Family} declarations for future use.</p> * * @param loc The location of the imported {@code module}. * @param id A {@link ModuleIdentifier} referring to an * importing {@code concept}. */ public final void storeConceptTypeFamilyDecs(Location loc, ModuleIdentifier id) { try { ConceptModuleDec conceptModuleDec = (ConceptModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); List<Dec> decs = conceptModuleDec.getDecList(); for (Dec dec : decs) { if (dec instanceof TypeFamilyDec) { myConceptDeclaredTypes.add((TypeFamilyDec) dec.clone()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code enhancement}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code enhancement}. * @param id A {@link ModuleIdentifier} referring to a * {@code enhancement}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeEnhancementAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { EnhancementModuleDec enhancementModuleDec = (EnhancementModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if they are part of a FacilityDec if (!isFacilityImport) { // Store the enhancement's requires clause storeRequiresClause(enhancementModuleDec.getName().getName(), enhancementModuleDec.getRequires()); // Store the enhancement's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(enhancementModuleDec .getLocation(), enhancementModuleDec .getParameterDecs()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code enhancement realization}'s module level * {@code requires} and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code enhancement realization}. * @param id A {@link ModuleIdentifier} referring to a * {@code enhancement realization}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeEnhancementRealizAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { EnhancementRealizModuleDec realizModuleDec = (EnhancementRealizModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if they are part of a FacilityDec if (!isFacilityImport) { // Store the enhancement realization's requires clause storeRequiresClause(realizModuleDec.getName().getName(), realizModuleDec.getRequires()); // Store the enhancement realization's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(realizModuleDec .getLocation(), realizModuleDec.getParameterDecs()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code facility}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code facility}. * @param id A {@link ModuleIdentifier} referring to a * {@code facility}. */ public final void storeFacilityModuleAssertionClauses(Location loc, ModuleIdentifier id) { try { FacilityModuleDec facilityModuleDec = (FacilityModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // Store the facility's requires clause storeRequiresClause(facilityModuleDec.getName().getName(), facilityModuleDec.getRequires()); // Store the facility's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(facilityModuleDec .getLocation(), facilityModuleDec.getParameterDecs()); } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores an object that records all relevant information * of an instantiated {@code Facility} for future use.</p> * * @param decl A {@link InstantiatedFacilityDecl} containing all the information. */ public final void storeInstantiatedFacilityDecl( InstantiatedFacilityDecl decl) { myProcessedInstFacilityDecls.add(decl); } /** * <p>This method stores a shared realization declaration * for future use.</p> * * @param dec A shared state realization. */ public final void storeLocalSharedRealizationDec( SharedStateRealizationDec dec) { myLocalSharedStateRealizationDecs.add((SharedStateRealizationDec) dec .clone()); } /** * <p>This method stores a type representation declaration * for future use.</p> * * @param dec A type representation. */ public final void storeLocalTypeRepresentationDec( AbstractTypeRepresentationDec dec) { myLocalTypeRepresentationDecs.add((AbstractTypeRepresentationDec) dec .clone()); } /** * <p>This method returns the object in string format.</p> * * @return Object as a string. */ @Override public final String toString() { return asString(0, 4); } // =========================================================== // Private Methods // =========================================================== /** * <p>An helper method for storing all the {@code constraint} clauses * for a list of {@link ModuleParameterDec ModuleParameterDecs}.</p> * * @param loc The location of the {@code module} that contains the * module parameters. * @param moduleParameterDecs A list of {@link ModuleParameterDec}. */ private void storeModuleParameterTypeConstraints(Location loc, List<ModuleParameterDec> moduleParameterDecs) { for (ModuleParameterDec m : moduleParameterDecs) { Dec wrappedDec = m.getWrappedDec(); if (wrappedDec instanceof ConstantParamDec) { ConstantParamDec dec = (ConstantParamDec) wrappedDec; ProgramTypeEntry typeEntry; if (dec.getVarDec().getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) dec.getVarDec().getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toTypeRepresentationEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeFamilyDec) { // Obtain the original dec from the AST TypeFamilyDec type = (TypeFamilyDec) typeEntry.getDefiningElement(); if (!VarExp.isLiteralTrue(type.getConstraint() .getAssertionExp())) { AssertionClause constraintClause = type.getConstraint(); AssertionClause modifiedConstraint = Utilities.getTypeConstraintClause( constraintClause, dec.getLocation(), null, dec .getName(), type .getExemplar(), typeEntry .getModelType(), null); // Store the constraint and its associated location detail for future use Location constraintLoc = modifiedConstraint.getLocation(); myModuleLevelLocationDetails.put( modifiedConstraint, new LocationDetailModel(constraintLoc, constraintLoc, "Constraint Clause of " + dec.getName())); myModuleLevelConstraints.put(dec, Collections .singletonList(modifiedConstraint)); } } } else { Utilities.tyNotHandled(dec.getVarDec().getTy(), loc); } } } } /** * <p>An helper method for storing a {@code requires} clause and its * associated location detail for future use.</p> * * @param decName Name of the declaration that contains * the {@code requiresClause}. * @param requiresClause An {@link AssertionClause} containing a {@code requires} clause. */ private void storeRequiresClause(String decName, AssertionClause requiresClause) { if (!VarExp.isLiteralTrue(requiresClause.getAssertionExp())) { myModuleLevelRequires.add(requiresClause); // Add the location details for the requires clause Location assertionLoc = requiresClause.getAssertionExp().getLocation(); myModuleLevelLocationDetails.put(requiresClause, new LocationDetailModel(assertionLoc.clone(), assertionLoc .clone(), "Requires Clause of " + decName)); } } }
src/main/java/edu/clemson/cs/rsrg/vcgeneration/utilities/VerificationContext.java
/* * VerificationContext.java * --------------------------------- * Copyright (c) 2017 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.rsrg.vcgeneration.utilities; import edu.clemson.cs.rsrg.absyn.clauses.AssertionClause; import edu.clemson.cs.rsrg.absyn.declarations.Dec; import edu.clemson.cs.rsrg.absyn.declarations.facilitydecl.FacilityDec; import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.*; import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ConstantParamDec; import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ModuleParameterDec; import edu.clemson.cs.rsrg.absyn.declarations.sharedstatedecl.SharedStateDec; import edu.clemson.cs.rsrg.absyn.declarations.sharedstatedecl.SharedStateRealizationDec; import edu.clemson.cs.rsrg.absyn.declarations.typedecl.AbstractTypeRepresentationDec; import edu.clemson.cs.rsrg.absyn.declarations.typedecl.TypeFamilyDec; import edu.clemson.cs.rsrg.absyn.declarations.variabledecl.MathVarDec; import edu.clemson.cs.rsrg.absyn.expressions.Exp; import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.VarExp; import edu.clemson.cs.rsrg.absyn.rawtypes.NameTy; import edu.clemson.cs.rsrg.init.CompileEnvironment; import edu.clemson.cs.rsrg.parsing.data.BasicCapabilities; import edu.clemson.cs.rsrg.parsing.data.Location; import edu.clemson.cs.rsrg.parsing.data.LocationDetailModel; import edu.clemson.cs.rsrg.parsing.data.PosSymbol; import edu.clemson.cs.rsrg.typeandpopulate.entry.ProgramTypeEntry; import edu.clemson.cs.rsrg.typeandpopulate.entry.SymbolTableEntry; import edu.clemson.cs.rsrg.typeandpopulate.exception.NoSuchSymbolException; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.MathSymbolTableBuilder; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.ModuleScope; import edu.clemson.cs.rsrg.typeandpopulate.utilities.ModuleIdentifier; import edu.clemson.cs.rsrg.vcgeneration.utilities.formaltoactual.InstantiatedFacilityDecl; import java.util.*; import static edu.clemson.cs.rsrg.vcgeneration.VCGenerator.FLAG_ADD_CONSTRAINT; /** * <p>This class contains all the module-level items relevant to the * file we are generating VCs for.</p> * * @author Yu-Shan Sun * @version 1.0 */ public class VerificationContext implements BasicCapabilities, Cloneable { // =========================================================== // Member Fields // =========================================================== /** <p>The symbol table we are currently building.</p> */ private final MathSymbolTableBuilder myBuilder; /** * <p>The current job's compilation environment * that stores all necessary objects and flags.</p> */ private final CompileEnvironment myCompileEnvironment; /** * <p>The module scope for the file we are generating * {@code VCs} for.</p> */ private final ModuleScope myCurrentModuleScope; /** <p>The name of the current module we are generating VCs for.</p> */ private final PosSymbol myName; // ----------------------------------------------------------- // Module Level Requires and Constraint Clauses // ----------------------------------------------------------- /** * <p>A list that stores all the module level {@code constraint} * clauses for the various different declarations.</p> */ private final Map<Dec, List<AssertionClause>> myModuleLevelConstraints; /** * <p>A map that stores all the details associated with * a particular module level {@link AssertionClause}.</p> */ private final Map<AssertionClause, LocationDetailModel> myModuleLevelLocationDetails; /** * <p>A list that stores all the module level {@code requires} * clauses.</p> */ private final List<AssertionClause> myModuleLevelRequires; // ----------------------------------------------------------- // Processed Facility Declarations // ----------------------------------------------------------- /** <p>The list of processed {@link InstantiatedFacilityDecl}. </p> */ private final List<InstantiatedFacilityDecl> myProcessedInstFacilityDecls; // ----------------------------------------------------------- // Shared State Declarations and Representations // ----------------------------------------------------------- /** <p>This contains all the shared state declared by the {@code Concept}.</p> */ private final List<SharedStateDec> myConceptSharedStates; /** * <p>If our current module scope allows us to introduce new shared state realizations, * this will contain all the {@link SharedStateRealizationDec}. Otherwise, * this list will be empty.</p> */ private final List<SharedStateRealizationDec> myLocalSharedStateRealizationDecs; // ----------------------------------------------------------- // Type Declarations and Representations // ----------------------------------------------------------- /** * <p>This contains all the types declared by the {@code Concept} * associated with the current module. Note that if we are in a * {@code Facility}, this list will be empty.</p> */ private final List<TypeFamilyDec> myConceptDeclaredTypes; /** * <p>If our current module scope allows us to introduce new type implementations, * this will contain all the {@link AbstractTypeRepresentationDec}. Otherwise, * this list will be empty.</p> */ private final List<AbstractTypeRepresentationDec> myLocalTypeRepresentationDecs; // =========================================================== // Constructors // =========================================================== /** * <p>This creates a verification context that stores all * the relevant information related to the module we are generating * {@code VCs} for.</p> * * @param name Name of the module we are generating VCs for. * @param moduleScope The module scope associated with {@code name}. * @param builder A scope builder for a symbol table. * @param compileEnvironment The current job's compilation environment * that stores all necessary objects and flags. */ public VerificationContext(PosSymbol name, ModuleScope moduleScope, MathSymbolTableBuilder builder, CompileEnvironment compileEnvironment) { myBuilder = builder; myCompileEnvironment = compileEnvironment; myConceptDeclaredTypes = new LinkedList<>(); myConceptSharedStates = new LinkedList<>(); myCurrentModuleScope = moduleScope; myLocalSharedStateRealizationDecs = new LinkedList<>(); myLocalTypeRepresentationDecs = new LinkedList<>(); myModuleLevelConstraints = new LinkedHashMap<>(); myModuleLevelLocationDetails = new LinkedHashMap<>(); myModuleLevelRequires = new LinkedList<>(); myName = name; myProcessedInstFacilityDecls = new LinkedList<>(); } // =========================================================== // Public Methods // =========================================================== /** * <p>This method creates a special indented * text version of the instantiated object.</p> * * @param indentSize The base indentation to the first line * of the text. * @param innerIndentInc The additional indentation increment * for the subsequent lines. * * @return A formatted text string of the class. */ @Override public final String asString(int indentSize, int innerIndentInc) { return ""; } /** * <p>This method uses all the {@code requires} and {@code constraint} * clauses from the various different sources (see below for complete list) * and builds the appropriate {@code assume} clause that goes at the * beginning an {@link AssertiveCodeBlock}.</p> * * <p>List of different places where clauses can originate from:</p> * <ul> * <li>{@code Concept}'s {@code requires} clause.</li> * <li>{@code Concept}'s module {@code constraint} clause.</li> * <li>{@code Shared Variables}' {@code constraint} clause.</li> * <li>{@code Concept Realization}'s {@code requires} clause.</li> * <li>{@code Shared Variables}' {@code convention} clause.</li> * <li>{@code Shared Variables}' {@code correspondence} clause.</li> * <li>{@code constraint} clauses for all the parameters with the * appropriate substitutions made.</li> * <li>Any {@code which_entails} expressions that originated from any of the * clauses above.</li> * </ul> * * @param loc The location in the AST that we are * currently visiting. * @param addSharedConventionFlag A flag that indicates whether or not we need * to add the {@code Shared Variable}'s {@code convention}. * @param addSharedCorrespondenceFlag A flag that indicates whether or not we need * to add the {@code Shared Variable}'s {@code correspondence}. * * @return The top-level assumed expression. */ public final Exp createTopLevelAssumeExpFromContext(Location loc, boolean addSharedConventionFlag, boolean addSharedCorrespondenceFlag) { Exp retExp = null; // Add all the module level requires clause. for (AssertionClause clause : myModuleLevelRequires) { retExp = Utilities.formConjunct(loc, retExp, clause, myModuleLevelLocationDetails.get(clause)); } // Add all the module level constraint clauses. for (Dec dec : myModuleLevelConstraints.keySet()) { for (AssertionClause clause : myModuleLevelConstraints.get(dec)) { retExp = Utilities.formConjunct(loc, retExp, clause, myModuleLevelLocationDetails.get(clause)); } } // Add all share variable's constraints. // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { // Add any facility instantiated shared state constraints for (InstantiatedFacilityDecl facilityDecl : myProcessedInstFacilityDecls) { for (SharedStateDec stateDec : facilityDecl .getConceptSharedStates()) { AssertionClause stateConstraintClause = stateDec.getConstraint(); // All shared variables should be add facilityDecl's name. Map<Exp, Exp> substitutions = new LinkedHashMap<>(); for (MathVarDec mathVarDec : stateDec.getAbstractStateVars()) { // Convert mathVarDec to VarExp. Also create a new qualified version of it. VarExp mathVarDecAsVarExp = Utilities.createVarExp(mathVarDec.getLocation().clone(), null, mathVarDec.getName().clone(), mathVarDec.getMathType(), null); VarExp qualifiedVarExp = (VarExp) mathVarDecAsVarExp.clone(); qualifiedVarExp.setQualifier(facilityDecl.getInstantiatedFacilityName().clone()); // Put them into our substitutions map. substitutions.put(mathVarDecAsVarExp, qualifiedVarExp); } // Generate the proper facility qualified constraint // and which_entails clauses (if any). Exp modifiedConstraint = stateConstraintClause.getAssertionExp().substitute(substitutions); Exp modifiedWhichEntails = stateConstraintClause.getWhichEntailsExp(); if (modifiedWhichEntails != null) { modifiedWhichEntails = modifiedWhichEntails.substitute(substitutions); } // Create the modified state constraint clause and add it to the retExp. AssertionClause modifiedStateConstraintClause = new AssertionClause(stateConstraintClause.getLocation().clone(), stateConstraintClause.getClauseType(), modifiedConstraint, modifiedWhichEntails); retExp = Utilities.formConjunct(loc, retExp, modifiedStateConstraintClause, myModuleLevelLocationDetails .get(stateConstraintClause)); } } // Add concept shared state constraints for (SharedStateDec stateDec : myConceptSharedStates) { AssertionClause stateConstraintClause = stateDec.getConstraint(); retExp = Utilities.formConjunct(loc, retExp, stateConstraintClause, myModuleLevelLocationDetails .get(stateConstraintClause)); } } // Add the share variable realization's convention. if (addSharedConventionFlag) { // TODO: Add any shared variable's convention here. } // Add the shared variable realization's correspondence. if (addSharedCorrespondenceFlag) { // TODO: Add any shared variable's correspondence here. } return retExp; } /** * <p>This method returns a list containing the various * {@link TypeFamilyDec TypeFamilyDecs} in the current context.</p> * * @return A list containing {@link TypeFamilyDec TypeFamilyDecs}. */ public final List<TypeFamilyDec> getConceptDeclaredTypes() { return myConceptDeclaredTypes; } /** * <p>This method returns a list containing the various * {@link SharedStateDec SharedStateDecs} in the current context.</p> * * @return A list containing {@link SharedStateDec SharedStateDecs}. */ public final List<SharedStateDec> getConceptSharedVars() { return myConceptSharedStates; } /** * <p>This method returns a list containing the various * {@link SharedStateRealizationDec SharedStateRealizationDecs} * in the current context.</p> * * @return A list containing {@link SharedStateRealizationDec SharedStateRealizationDecs}. */ public final List<SharedStateRealizationDec> getLocalSharedStateRealizationDecs() { return myLocalSharedStateRealizationDecs; } /** * <p>This method returns a list containing the various * {@link AbstractTypeRepresentationDec AbstractTypeRepresentationDecs} * in the current context.</p> * * @return A list containing {@link AbstractTypeRepresentationDec AbstractTypeRepresentationDecs}. */ public final List<AbstractTypeRepresentationDec> getLocalTypeRepresentationDecs() { return myLocalTypeRepresentationDecs; } /** * <p>This method returns a list of all instantiated {@code Facilities}.</p> * * @return A list of {@link InstantiatedFacilityDecl} containing all the information. */ public final List<InstantiatedFacilityDecl> getProcessedInstFacilityDecls() { return myProcessedInstFacilityDecls; } /** * <p>This method stores a {@code concept}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code concept}. * @param id A {@link ModuleIdentifier} referring to a * {@code concept}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeConceptAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { ConceptModuleDec conceptModuleDec = (ConceptModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if the concept didn't originate from // a facility declaration. if (!isFacilityImport) { // Store the concept's requires clause storeRequiresClause(conceptModuleDec.getName().getName(), conceptModuleDec.getRequires()); // Store the concept's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(conceptModuleDec .getLocation(), conceptModuleDec.getParameterDecs()); } } // Store the concept's module constraints and // its associated location detail for future use. if (!conceptModuleDec.getConstraints().isEmpty()) { myModuleLevelConstraints.put(conceptModuleDec, conceptModuleDec .getConstraints()); for (AssertionClause constraint : conceptModuleDec .getConstraints()) { Location constraintLoc = constraint.getAssertionExp().getLocation(); myModuleLevelLocationDetails.put(constraint, new LocationDetailModel(constraintLoc.clone(), constraintLoc.clone(), "Constraint Clause of " + conceptModuleDec.getName())); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code concept realization}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code concept realization}. * @param id A {@link ModuleIdentifier} referring to a * {@code concept realization}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeConceptRealizAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { ConceptRealizModuleDec realizModuleDec = (ConceptRealizModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if they are part of a FacilityDec if (!isFacilityImport) { // Store the concept realization's requires clause storeRequiresClause(realizModuleDec.getName().getName(), realizModuleDec.getRequires()); // Store the concept realization's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(realizModuleDec .getLocation(), realizModuleDec.getParameterDecs()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code concept's} * {@code Shared Variables} declarations for future use.</p> * * @param dec A {@link SharedStateDec} declared in a {@code Concept}. */ public final void storeConceptSharedStateDec(SharedStateDec dec) { myConceptSharedStates.add((SharedStateDec) dec.clone()); } /** * <p>This method stores the imported {@code concept's} * {@code Shared Variables} declarations for future use.</p> * * @param loc The location of the imported {@code module}. * @param id A {@link ModuleIdentifier} referring to an * importing {@code concept}. */ public final void storeConceptSharedStateDecs(Location loc, ModuleIdentifier id) { try { ConceptModuleDec conceptModuleDec = (ConceptModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); List<Dec> decs = conceptModuleDec.getDecList(); for (Dec dec : decs) { if (dec instanceof SharedStateDec) { myConceptSharedStates.add((SharedStateDec) dec.clone()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code concept's} * {@code Type Family} declarations for future use.</p> * * @param dec A type family declared in a {@code Concept}. */ public final void storeConceptTypeFamilyDec(TypeFamilyDec dec) { myConceptDeclaredTypes.add((TypeFamilyDec) dec.clone()); } /** * <p>This method stores the imported {@code concept's} * {@code Type Family} declarations for future use.</p> * * @param loc The location of the imported {@code module}. * @param id A {@link ModuleIdentifier} referring to an * importing {@code concept}. */ public final void storeConceptTypeFamilyDecs(Location loc, ModuleIdentifier id) { try { ConceptModuleDec conceptModuleDec = (ConceptModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); List<Dec> decs = conceptModuleDec.getDecList(); for (Dec dec : decs) { if (dec instanceof TypeFamilyDec) { myConceptDeclaredTypes.add((TypeFamilyDec) dec.clone()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code enhancement}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code enhancement}. * @param id A {@link ModuleIdentifier} referring to a * {@code enhancement}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeEnhancementAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { EnhancementModuleDec enhancementModuleDec = (EnhancementModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if they are part of a FacilityDec if (!isFacilityImport) { // Store the enhancement's requires clause storeRequiresClause(enhancementModuleDec.getName().getName(), enhancementModuleDec.getRequires()); // Store the enhancement's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(enhancementModuleDec .getLocation(), enhancementModuleDec .getParameterDecs()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code enhancement realization}'s module level * {@code requires} and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code enhancement realization}. * @param id A {@link ModuleIdentifier} referring to a * {@code enhancement realization}. * @param isFacilityImport A flag that indicates whether or not * we are storing information that originated * from a {@link FacilityDec}. */ public final void storeEnhancementRealizAssertionClauses(Location loc, ModuleIdentifier id, boolean isFacilityImport) { try { EnhancementRealizModuleDec realizModuleDec = (EnhancementRealizModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // We only need to store these if they are part of a FacilityDec if (!isFacilityImport) { // Store the enhancement realization's requires clause storeRequiresClause(realizModuleDec.getName().getName(), realizModuleDec.getRequires()); // Store the enhancement realization's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(realizModuleDec .getLocation(), realizModuleDec.getParameterDecs()); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores a {@code facility}'s module level {@code requires} * and {@code constraint} clauses for future use.</p> * * @param loc The location of where we found the {@code facility}. * @param id A {@link ModuleIdentifier} referring to a * {@code facility}. */ public final void storeFacilityModuleAssertionClauses(Location loc, ModuleIdentifier id) { try { FacilityModuleDec facilityModuleDec = (FacilityModuleDec) myBuilder.getModuleScope(id) .getDefiningElement(); // Store the facility's requires clause storeRequiresClause(facilityModuleDec.getName().getName(), facilityModuleDec.getRequires()); // Store the facility's type constraints from the module parameters // YS: We are not adding these automatically. Most of the time, these // constraints wouldn't really help us prove any of the VCs. If you // are ever interested in adding these to the givens list, use the // "addConstraints" flag. Note that these constraints still need to be // processed by the parsimonious step, so there is no guarantee that they // will show up in all of the VCs. if (myCompileEnvironment.flags.isFlagSet(FLAG_ADD_CONSTRAINT)) { storeModuleParameterTypeConstraints(facilityModuleDec .getLocation(), facilityModuleDec.getParameterDecs()); } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(loc); } } /** * <p>This method stores an object that records all relevant information * of an instantiated {@code Facility} for future use.</p> * * @param decl A {@link InstantiatedFacilityDecl} containing all the information. */ public final void storeInstantiatedFacilityDecl( InstantiatedFacilityDecl decl) { myProcessedInstFacilityDecls.add(decl); } /** * <p>This method stores a shared realization declaration * for future use.</p> * * @param dec A shared state realization. */ public final void storeLocalSharedRealizationDec( SharedStateRealizationDec dec) { myLocalSharedStateRealizationDecs.add((SharedStateRealizationDec) dec .clone()); } /** * <p>This method stores a type representation declaration * for future use.</p> * * @param dec A type representation. */ public final void storeLocalTypeRepresentationDec( AbstractTypeRepresentationDec dec) { myLocalTypeRepresentationDecs.add((AbstractTypeRepresentationDec) dec .clone()); } /** * <p>This method returns the object in string format.</p> * * @return Object as a string. */ @Override public final String toString() { return asString(0, 4); } // =========================================================== // Private Methods // =========================================================== /** * <p>An helper method for storing all the {@code constraint} clauses * for a list of {@link ModuleParameterDec ModuleParameterDecs}.</p> * * @param loc The location of the {@code module} that contains the * module parameters. * @param moduleParameterDecs A list of {@link ModuleParameterDec}. */ private void storeModuleParameterTypeConstraints(Location loc, List<ModuleParameterDec> moduleParameterDecs) { for (ModuleParameterDec m : moduleParameterDecs) { Dec wrappedDec = m.getWrappedDec(); if (wrappedDec instanceof ConstantParamDec) { ConstantParamDec dec = (ConstantParamDec) wrappedDec; ProgramTypeEntry typeEntry; if (dec.getVarDec().getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) dec.getVarDec().getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toTypeRepresentationEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeFamilyDec) { // Obtain the original dec from the AST TypeFamilyDec type = (TypeFamilyDec) typeEntry.getDefiningElement(); if (!VarExp.isLiteralTrue(type.getConstraint() .getAssertionExp())) { AssertionClause constraintClause = type.getConstraint(); AssertionClause modifiedConstraint = Utilities.getTypeConstraintClause( constraintClause, dec.getLocation(), null, dec .getName(), type .getExemplar(), typeEntry .getModelType(), null); // Store the constraint and its associated location detail for future use Location constraintLoc = modifiedConstraint.getLocation(); myModuleLevelLocationDetails.put( modifiedConstraint, new LocationDetailModel(constraintLoc, constraintLoc, "Constraint Clause of " + dec.getName())); myModuleLevelConstraints.put(dec, Collections .singletonList(modifiedConstraint)); } } } else { Utilities.tyNotHandled(dec.getVarDec().getTy(), loc); } } } } /** * <p>An helper method for storing a {@code requires} clause and its * associated location detail for future use.</p> * * @param decName Name of the declaration that contains * the {@code requiresClause}. * @param requiresClause An {@link AssertionClause} containing a {@code requires} clause. */ private void storeRequiresClause(String decName, AssertionClause requiresClause) { if (!VarExp.isLiteralTrue(requiresClause.getAssertionExp())) { myModuleLevelRequires.add(requiresClause); // Add the location details for the requires clause Location assertionLoc = requiresClause.getAssertionExp().getLocation(); myModuleLevelLocationDetails.put(requiresClause, new LocationDetailModel(assertionLoc.clone(), assertionLoc .clone(), "Requires Clause of " + decName)); } } }
Add shared state realization convention/correspondence if requested
src/main/java/edu/clemson/cs/rsrg/vcgeneration/utilities/VerificationContext.java
Add shared state realization convention/correspondence if requested
<ide><path>rc/main/java/edu/clemson/cs/rsrg/vcgeneration/utilities/VerificationContext.java <ide> } <ide> } <ide> <del> // Add the share variable realization's convention. <del> if (addSharedConventionFlag) { <del> // TODO: Add any shared variable's convention here. <del> } <del> <del> // Add the shared variable realization's correspondence. <del> if (addSharedCorrespondenceFlag) { <del> // TODO: Add any shared variable's correspondence here. <add> // Process any local shared state realizations <add> for (SharedStateRealizationDec sharedStateRealizationDec : myLocalSharedStateRealizationDecs) { <add> // Add the share variable realization's convention if requested. <add> if (addSharedConventionFlag) { <add> AssertionClause stateConventionClause = <add> sharedStateRealizationDec.getConvention(); <add> retExp = <add> Utilities.formConjunct(loc, retExp, <add> stateConventionClause, <add> myModuleLevelLocationDetails <add> .get(stateConventionClause)); <add> } <add> <add> // Add the shared variable realization's correspondence if requested. <add> if (addSharedCorrespondenceFlag) { <add> AssertionClause stateCorrespondenceClause = <add> sharedStateRealizationDec.getCorrespondence(); <add> retExp = <add> Utilities.formConjunct(loc, retExp, <add> stateCorrespondenceClause, <add> myModuleLevelLocationDetails <add> .get(stateCorrespondenceClause)); <add> } <ide> } <ide> <ide> return retExp;
Java
apache-2.0
dcdb7e2cd354de189a415eb5138a77b9ad10c6bb
0
Am3o/eShop,Am3o/eShop
package de.hska.iwi.microservice.catalog.client; import de.hska.iwi.microservice.catalog.client.api.ProductService; import de.hska.iwi.microservice.catalog.entity.Product; import org.apache.log4j.Logger; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.net.URISyntaxException; import java.util.List; /** * Created by ameo on 13.11.16. */ public class ProductServiceClient implements ProductService { private static final Logger logger = Logger.getLogger(ProductServiceClient.class); private final String serviceUrl; private final RestTemplate restClient = new RestTemplate(); public ProductServiceClient(String serviceUrl) { this.serviceUrl = serviceUrl; } @Override public List<Product> getProducts(int categoryId) { URI destUri = null; try { destUri = new URI(serviceUrl); } catch (URISyntaxException ex) { logger.error("Fehler beim auflösen der URI", ex); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(destUri).queryParam("categoryId", categoryId); HttpEntity<String> entity = new HttpEntity<String>(headers); ResponseEntity<List> result = restClient.exchange(uriBuilder.build().encode().toUri(), HttpMethod.GET, entity, List.class); return result.getBody(); } @Override public Product getProduct(int id) { return restClient.getForObject(String.format("%s/%d", serviceUrl, id), Product.class); } @Override public Product createProduct(Product product) { return restClient.postForEntity(String.format("%s/", serviceUrl), product, Product.class).getBody(); } @Override public Product updateProduct(int id, Product product) { restClient.put(String.format("%s/%d", serviceUrl, id), product); return this.getProduct(id); } @Override public Boolean deleteProduct(int id) { restClient.delete(String.format("%s/%d", serviceUrl, id)); return !(this.getProduct(id) instanceof Product); } }
Microservice/Catalog/src/main/java/de/hska/iwi/microservice/catalog/client/ProductServiceClient.java
package de.hska.iwi.microservice.catalog.client; import de.hska.iwi.microservice.catalog.client.api.ProductService; import de.hska.iwi.microservice.catalog.entity.Product; import org.apache.log4j.Logger; import org.springframework.web.client.RestTemplate; import java.util.List; /** * Created by ameo on 13.11.16. */ public class ProductServiceClient implements ProductService { private static final Logger logger = Logger.getLogger(ProductServiceClient.class); private final String serviceUrl; private final RestTemplate restClient = new RestTemplate(); public ProductServiceClient(String serviceUrl) { this.serviceUrl = serviceUrl; } @Override public List<Product> getProducts(int categoryId) { return restClient.getForObject(String.format("%s/?categoryId=%d", serviceUrl, categoryId), List.class); } @Override public Product getProduct(int id) { return restClient.getForObject(String.format("%s/%d", serviceUrl, id), Product.class); } @Override public Product createProduct(Product product) { return restClient.postForEntity(String.format("%s/", serviceUrl), product, Product.class).getBody(); } @Override public Product updateProduct(int id, Product product) { restClient.put(String.format("%s/%d", serviceUrl, id), product); return this.getProduct(id); } @Override public Boolean deleteProduct(int id) { restClient.delete(String.format("%s/%d", serviceUrl, id)); return !(this.getProduct(id) instanceof Product); } }
Anpassung der Product-Schnittstelle
Microservice/Catalog/src/main/java/de/hska/iwi/microservice/catalog/client/ProductServiceClient.java
Anpassung der Product-Schnittstelle
<ide><path>icroservice/Catalog/src/main/java/de/hska/iwi/microservice/catalog/client/ProductServiceClient.java <ide> import de.hska.iwi.microservice.catalog.client.api.ProductService; <ide> import de.hska.iwi.microservice.catalog.entity.Product; <ide> import org.apache.log4j.Logger; <add>import org.springframework.http.*; <ide> import org.springframework.web.client.RestTemplate; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> <add>import java.net.URI; <add>import java.net.URISyntaxException; <ide> import java.util.List; <ide> <ide> /** <ide> <ide> @Override <ide> public List<Product> getProducts(int categoryId) { <del> return restClient.getForObject(String.format("%s/?categoryId=%d", serviceUrl, categoryId), List.class); <add> URI destUri = null; <add> try { <add> destUri = new URI(serviceUrl); <add> } catch (URISyntaxException ex) { <add> logger.error("Fehler beim auflösen der URI", ex); <add> <add> } <add> HttpHeaders headers = new HttpHeaders(); <add> headers.setContentType(MediaType.APPLICATION_JSON); <add> <add> UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(destUri).queryParam("categoryId", categoryId); <add> <add> HttpEntity<String> entity = new HttpEntity<String>(headers); <add> <add> ResponseEntity<List> result = restClient.exchange(uriBuilder.build().encode().toUri(), <add> HttpMethod.GET, <add> entity, <add> List.class); <add> return result.getBody(); <ide> } <ide> <ide> @Override
Java
lgpl-2.1
c5cdb51aa8810ca21c92adf00ab98b900eeddd23
0
threerings/nenya,threerings/nenya
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.openal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.nio.IntBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.openal.AL; import org.lwjgl.openal.AL10; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.samskivert.util.IntListUtil; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.samskivert.util.RunQueue; import com.threerings.openal.ClipBuffer.Observer; import static com.threerings.openal.Log.log; /** * An interface to the OpenAL library that provides a number of additional services: * * <ul> * <li> an object oriented interface to the OpenAL system * <li> a mechanism for loading a group of sounds and freeing their resources all at once * <li> a mechanism for loading sounds in a background thread and preloading sounds that are likely * to be needed soon * </ul> * * <p><em>Note:</em> the sound manager is not thread safe (other than during its interactions with * its internal background loading thread). It assumes that all sound loading and play requests * will be made from a single thread. */ public class SoundManager { /** * Creates, initializes and returns the singleton sound manager instance. * * @param rqueue a queue that the sound manager can use to post short runnables that must be * executed on the same thread from which all other sound methods will be called. */ public static SoundManager createSoundManager (RunQueue rqueue) { if (_soundmgr != null) { throw new IllegalStateException("A sound manager has already been created."); } _soundmgr = new SoundManager(rqueue); return _soundmgr; } /** * Shuts down the sound manager. */ public void shutdown () { if (isInitialized()) { AL.destroy(); } } /** * Returns true if we were able to initialize the sound system. */ public boolean isInitialized () { return (_toLoad != null); } /** * Configures the size of our sound cache. If this value is larger than memory available to the * underlying sound system, it will be reduced when OpenAL first tells us we're out of memory. */ public void setCacheSize (int bytes) { _clips.setMaxSize(bytes); } /** * Returns a reference to the listener object. */ public Listener getListener () { return _listener; } /** * Configures the base gain (which must be a value between 0 and 1.0) which is multiplied to * the individual gain assigned to sound effects (but not music). */ public void setBaseGain (float gain) { if (_baseGain == gain) { return; } _baseGain = gain; // alert the groups that inherite the gain for (int ii = 0, nn = _groups.size(); ii < nn; ii++) { SoundGroup group = _groups.get(ii); if (group.getBaseGain() < 0f) { group.baseGainChanged(); } } } /** * Returns the base gain used for sound effects (not music). */ public float getBaseGain () { return _baseGain; } /** * Creates an object that can be used to manage and play a group of sounds. <em>Note:</em> the * sound group <em>must</em> be disposed when it is no longer needed via a call to {@link * SoundGroup#dispose}. * * @param provider indicates from where the sound group will load its sounds. * @param sources indicates the maximum number of simultaneous sounds that can play in this * group. */ public SoundGroup createGroup (ClipProvider provider, int sources) { return new SoundGroup(this, provider, sources); } /** * Returns a reference to the list of active streams. */ public ArrayList<Stream> getStreams () { return _streams; } /** * Updates all of the streams controlled by the manager. This should be called once per frame * by the application. * * @param time the number of seconds elapsed since the last update */ public void updateStreams (float time) { // iterate backwards through the list so that streams can dispose of themselves during // their update for (int ii = _streams.size() - 1; ii >= 0; ii--) { _streams.get(ii).update(time); } // delete any finalized objects deleteFinalizedObjects(); } /** * Loads a clip buffer for the sound clip loaded via the specified provider with the * specified path. The loaded clip is placed in the cache. */ public void loadClip (ClipProvider provider, String path) { loadClip(provider, path, null); } /** * Loads a clip buffer for the sound clip loaded via the specified provider with the * specified path. The loaded clip is placed in the cache. */ public void loadClip (ClipProvider provider, String path, Observer observer) { getClip(provider, path, observer); } /** * Creates a sound manager and initializes the OpenAL sound subsystem. */ protected SoundManager (RunQueue rqueue) { _rqueue = rqueue; // initialize the OpenAL sound system try { AL.create("", 44100, 15, false); } catch (Exception e) { log.warning("Failed to initialize sound system.", e); // don't start the background loading thread return; } int errno = AL10.alGetError(); if (errno != AL10.AL_NO_ERROR) { log.warning("Failed to initialize sound system [errno=" + errno + "]."); // don't start the background loading thread return; } // configure our LRU map with a removal observer _clips.setRemovalObserver(new LRUHashMap.RemovalObserver<String, ClipBuffer>() { public void removedFromMap (LRUHashMap<String, ClipBuffer> map, final ClipBuffer item) { _rqueue.postRunnable(new Runnable() { public void run () { log.debug("Flushing " + item.getKey()); item.dispose(); } }); } }); // create our loading queue _toLoad = new Queue<ClipBuffer>(); // start up the background loader thread _loader.setDaemon(true); _loader.start(); } /** * Creates a clip buffer for the sound clip loaded via the specified provider with the * specified path. The clip buffer may come from the cache, and it will immediately be queued * for loading if it is not already loaded. */ protected ClipBuffer getClip (ClipProvider provider, String path) { return getClip(provider, path, null); } /** * Creates a clip buffer for the sound clip loaded via the specified provider with the * specified path. The clip buffer may come from the cache, and it will immediately be queued * for loading if it is not already loaded. */ protected ClipBuffer getClip (ClipProvider provider, String path, Observer observer) { String ckey = ClipBuffer.makeKey(provider, path); ClipBuffer buffer = _clips.get(ckey); try { if (buffer == null) { // check to see if this clip is currently loading buffer = _loading.get(ckey); if (buffer == null) { buffer = new ClipBuffer(this, provider, path); _loading.put(ckey, buffer); } } buffer.resolve(observer); return buffer; } catch (Throwable t) { log.warning("Failure resolving buffer [key=" + ckey + "].", t); return null; } } /** * Queues the supplied clip buffer up for resolution. The {@link Clip} will be loaded into * memory and then bound into OpenAL on the background thread. */ protected void queueClipLoad (ClipBuffer buffer) { if (_toLoad != null) { _toLoad.append(buffer); } } /** * Queues the supplied clip buffer up using our {@link RunQueue} to notify its observers that * it failed to load. */ protected void queueClipFailure (final ClipBuffer buffer) { _rqueue.postRunnable(new Runnable() { public void run () { _loading.remove(buffer.getKey()); buffer.failed(); } }); } /** * Adds the supplied clip buffer back to the cache after it has been marked for disposal and * subsequently re-requested. */ protected void restoreClip (ClipBuffer buffer) { _clips.put(buffer.getKey(), buffer); } /** * Adds a stream to the list maintained by the manager. Called by streams when they are * created. */ protected void addStream (Stream stream) { _streams.add(stream); } /** * Removes a stream from the list maintained by the manager. Called by streams when they are * disposed. */ protected void removeStream (Stream stream) { _streams.remove(stream); } /** * Adds a group to the list maintained by the manager. Called by groups when they are created. */ protected void addGroup (SoundGroup group) { _groups.add(group); } /** * Removes a group from the list maintained by the manager. Called by groups when they are * disposed. */ protected void removeGroup (SoundGroup group) { _groups.remove(group); } /** * Called when a source has been finalized. */ protected synchronized void sourceFinalized (int id) { _finalizedSources = IntListUtil.add(_finalizedSources, id); } /** * Called when a buffer has been finalized. */ protected synchronized void bufferFinalized (int id) { _finalizedBuffers = IntListUtil.add(_finalizedBuffers, id); } /** * Deletes all finalized objects. */ protected synchronized void deleteFinalizedObjects () { if (_finalizedSources != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedSources.length); idbuf.put(_finalizedSources).rewind(); AL10.alDeleteSources(idbuf); _finalizedSources = null; } if (_finalizedBuffers != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedBuffers.length); idbuf.put(_finalizedBuffers).rewind(); AL10.alDeleteBuffers(idbuf); _finalizedBuffers = null; } } /** The thread that loads up sound clips in the background. */ protected Thread _loader = new Thread("SoundManager.Loader") { @Override public void run () { while (true) { final ClipBuffer buffer = _toLoad.get(); try { log.debug("Loading " + buffer.getKey() + "."); final Clip clip = buffer.load(); _rqueue.postRunnable(new Runnable() { public void run () { String ckey = buffer.getKey(); log.debug("Loaded " + ckey + "."); _loading.remove(ckey); if (buffer.bind(clip)) { _clips.put(ckey, buffer); } else { // TODO: shrink the cache size if the bind failed due to // OUT_OF_MEMORY } } }); } catch (Throwable t) { log.warning("Failed to load clip [key=" + buffer.getKey() + "].", t); // let the clip and its observers know that we are a miserable failure queueClipFailure(buffer); } } } }; /** Used to get back from the background thread to our "main" thread. */ protected RunQueue _rqueue; /** The listener object. */ protected Listener _listener = new Listener(); /** A base gain that is multiplied by the individual gain assigned to sounds. */ protected float _baseGain = 1; /** Contains a mapping of all currently-loading clips. */ protected HashMap<String, ClipBuffer> _loading = Maps.newHashMap(); /** Contains a mapping of all loaded clips. */ protected LRUHashMap<String, ClipBuffer> _clips = new LRUHashMap<String, ClipBuffer>(DEFAULT_CACHE_SIZE, _sizer); /** Contains a queue of clip buffers waiting to be loaded. */ protected Queue<ClipBuffer> _toLoad; /** The list of active streams. */ protected ArrayList<Stream> _streams = Lists.newArrayList(); /** The list of active groups. */ protected List<SoundGroup> _groups = Lists.newArrayList(); /** The list of sources to be deleted. */ protected int[] _finalizedSources; /** The list of buffers to be deleted. */ protected int[] _finalizedBuffers; /** The one and only sound manager, here for an exclusive performance by special request. * Available for all your sound playing needs. */ protected static SoundManager _soundmgr; /** Used to compute the in-memory size of sound samples. */ protected static LRUHashMap.ItemSizer<ClipBuffer> _sizer = new LRUHashMap.ItemSizer<ClipBuffer>() { public int computeSize (ClipBuffer item) { return item.getSize(); } }; /** Default to a cache size of one megabyte. */ protected static final int DEFAULT_CACHE_SIZE = 8 * 1024 * 1024; }
src/main/java/com/threerings/openal/SoundManager.java
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.openal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.nio.IntBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.openal.AL; import org.lwjgl.openal.AL10; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.samskivert.util.IntListUtil; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.samskivert.util.RunQueue; import com.threerings.openal.ClipBuffer.Observer; import static com.threerings.openal.Log.log; /** * An interface to the OpenAL library that provides a number of additional services: * * <ul> * <li> an object oriented interface to the OpenAL system * <li> a mechanism for loading a group of sounds and freeing their resources all at once * <li> a mechanism for loading sounds in a background thread and preloading sounds that are likely * to be needed soon * </ul> * * <p><em>Note:</em> the sound manager is not thread safe (other than during its interactions with * its internal background loading thread). It assumes that all sound loading and play requests * will be made from a single thread. */ public class SoundManager { /** * Creates, initializes and returns the singleton sound manager instance. * * @param rqueue a queue that the sound manager can use to post short runnables that must be * executed on the same thread from which all other sound methods will be called. */ public static SoundManager createSoundManager (RunQueue rqueue) { if (_soundmgr != null) { throw new IllegalStateException("A sound manager has already been created."); } _soundmgr = new SoundManager(rqueue); return _soundmgr; } /** * Shuts down the sound manager. */ public void shutdown () { if (isInitialized()) { AL.destroy(); } } /** * Returns true if we were able to initialize the sound system. */ public boolean isInitialized () { return (_toLoad != null); } /** * Configures the size of our sound cache. If this value is larger than memory available to the * underlying sound system, it will be reduced when OpenAL first tells us we're out of memory. */ public void setCacheSize (int bytes) { _clips.setMaxSize(bytes); } /** * Returns a reference to the listener object. */ public Listener getListener () { return _listener; } /** * Configures the base gain (which must be a value between 0 and 1.0) which is multiplied to * the individual gain assigned to sound effects (but not music). */ public void setBaseGain (float gain) { if (_baseGain == gain) { return; } _baseGain = gain; // alert the groups that inherite the gain for (int ii = 0, nn = _groups.size(); ii < nn; ii++) { SoundGroup group = _groups.get(ii); if (group.getBaseGain() < 0f) { group.baseGainChanged(); } } } /** * Returns the base gain used for sound effects (not music). */ public float getBaseGain () { return _baseGain; } /** * Creates an object that can be used to manage and play a group of sounds. <em>Note:</em> the * sound group <em>must</em> be disposed when it is no longer needed via a call to {@link * SoundGroup#dispose}. * * @param provider indicates from where the sound group will load its sounds. * @param sources indicates the maximum number of simultaneous sounds that can play in this * group. */ public SoundGroup createGroup (ClipProvider provider, int sources) { return new SoundGroup(this, provider, sources); } /** * Returns a reference to the list of active streams. */ public ArrayList<Stream> getStreams () { return _streams; } /** * Updates all of the streams controlled by the manager. This should be called once per frame * by the application. * * @param time the number of seconds elapsed since the last update */ public void updateStreams (float time) { // iterate backwards through the list so that streams can dispose of themselves during // their update for (int ii = _streams.size() - 1; ii >= 0; ii--) { _streams.get(ii).update(time); } // delete any finalized objects deleteFinalizedObjects(); } /** * Loads a clip buffer for the sound clip loaded via the specified provider with the * specified path. The loaded clip is placed in the cache. */ public void loadClip (ClipProvider provider, String path) { loadClip(provider, path, null); } /** * Loads a clip buffer for the sound clip loaded via the specified provider with the * specified path. The loaded clip is placed in the cache. */ public void loadClip (ClipProvider provider, String path, Observer observer) { getClip(provider, path, observer); } /** * Creates a sound manager and initializes the OpenAL sound subsystem. */ protected SoundManager (RunQueue rqueue) { _rqueue = rqueue; AL10.alGetError(); // throw away any unchecked error prior to an op we want to check // initialize the OpenAL sound system try { AL.create("", 44100, 15, false); } catch (Exception e) { log.warning("Failed to initialize sound system.", e); // don't start the background loading thread return; } int errno = AL10.alGetError(); if (errno != AL10.AL_NO_ERROR) { log.warning("Failed to initialize sound system [errno=" + errno + "]."); // don't start the background loading thread return; } // configure our LRU map with a removal observer _clips.setRemovalObserver(new LRUHashMap.RemovalObserver<String, ClipBuffer>() { public void removedFromMap (LRUHashMap<String, ClipBuffer> map, final ClipBuffer item) { _rqueue.postRunnable(new Runnable() { public void run () { log.debug("Flushing " + item.getKey()); item.dispose(); } }); } }); // create our loading queue _toLoad = new Queue<ClipBuffer>(); // start up the background loader thread _loader.setDaemon(true); _loader.start(); } /** * Creates a clip buffer for the sound clip loaded via the specified provider with the * specified path. The clip buffer may come from the cache, and it will immediately be queued * for loading if it is not already loaded. */ protected ClipBuffer getClip (ClipProvider provider, String path) { return getClip(provider, path, null); } /** * Creates a clip buffer for the sound clip loaded via the specified provider with the * specified path. The clip buffer may come from the cache, and it will immediately be queued * for loading if it is not already loaded. */ protected ClipBuffer getClip (ClipProvider provider, String path, Observer observer) { String ckey = ClipBuffer.makeKey(provider, path); ClipBuffer buffer = _clips.get(ckey); try { if (buffer == null) { // check to see if this clip is currently loading buffer = _loading.get(ckey); if (buffer == null) { buffer = new ClipBuffer(this, provider, path); _loading.put(ckey, buffer); } } buffer.resolve(observer); return buffer; } catch (Throwable t) { log.warning("Failure resolving buffer [key=" + ckey + "].", t); return null; } } /** * Queues the supplied clip buffer up for resolution. The {@link Clip} will be loaded into * memory and then bound into OpenAL on the background thread. */ protected void queueClipLoad (ClipBuffer buffer) { if (_toLoad != null) { _toLoad.append(buffer); } } /** * Queues the supplied clip buffer up using our {@link RunQueue} to notify its observers that * it failed to load. */ protected void queueClipFailure (final ClipBuffer buffer) { _rqueue.postRunnable(new Runnable() { public void run () { _loading.remove(buffer.getKey()); buffer.failed(); } }); } /** * Adds the supplied clip buffer back to the cache after it has been marked for disposal and * subsequently re-requested. */ protected void restoreClip (ClipBuffer buffer) { _clips.put(buffer.getKey(), buffer); } /** * Adds a stream to the list maintained by the manager. Called by streams when they are * created. */ protected void addStream (Stream stream) { _streams.add(stream); } /** * Removes a stream from the list maintained by the manager. Called by streams when they are * disposed. */ protected void removeStream (Stream stream) { _streams.remove(stream); } /** * Adds a group to the list maintained by the manager. Called by groups when they are created. */ protected void addGroup (SoundGroup group) { _groups.add(group); } /** * Removes a group from the list maintained by the manager. Called by groups when they are * disposed. */ protected void removeGroup (SoundGroup group) { _groups.remove(group); } /** * Called when a source has been finalized. */ protected synchronized void sourceFinalized (int id) { _finalizedSources = IntListUtil.add(_finalizedSources, id); } /** * Called when a buffer has been finalized. */ protected synchronized void bufferFinalized (int id) { _finalizedBuffers = IntListUtil.add(_finalizedBuffers, id); } /** * Deletes all finalized objects. */ protected synchronized void deleteFinalizedObjects () { if (_finalizedSources != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedSources.length); idbuf.put(_finalizedSources).rewind(); AL10.alDeleteSources(idbuf); _finalizedSources = null; } if (_finalizedBuffers != null) { IntBuffer idbuf = BufferUtils.createIntBuffer(_finalizedBuffers.length); idbuf.put(_finalizedBuffers).rewind(); AL10.alDeleteBuffers(idbuf); _finalizedBuffers = null; } } /** The thread that loads up sound clips in the background. */ protected Thread _loader = new Thread("SoundManager.Loader") { @Override public void run () { while (true) { final ClipBuffer buffer = _toLoad.get(); try { log.debug("Loading " + buffer.getKey() + "."); final Clip clip = buffer.load(); _rqueue.postRunnable(new Runnable() { public void run () { String ckey = buffer.getKey(); log.debug("Loaded " + ckey + "."); _loading.remove(ckey); if (buffer.bind(clip)) { _clips.put(ckey, buffer); } else { // TODO: shrink the cache size if the bind failed due to // OUT_OF_MEMORY } } }); } catch (Throwable t) { log.warning("Failed to load clip [key=" + buffer.getKey() + "].", t); // let the clip and its observers know that we are a miserable failure queueClipFailure(buffer); } } } }; /** Used to get back from the background thread to our "main" thread. */ protected RunQueue _rqueue; /** The listener object. */ protected Listener _listener = new Listener(); /** A base gain that is multiplied by the individual gain assigned to sounds. */ protected float _baseGain = 1; /** Contains a mapping of all currently-loading clips. */ protected HashMap<String, ClipBuffer> _loading = Maps.newHashMap(); /** Contains a mapping of all loaded clips. */ protected LRUHashMap<String, ClipBuffer> _clips = new LRUHashMap<String, ClipBuffer>(DEFAULT_CACHE_SIZE, _sizer); /** Contains a queue of clip buffers waiting to be loaded. */ protected Queue<ClipBuffer> _toLoad; /** The list of active streams. */ protected ArrayList<Stream> _streams = Lists.newArrayList(); /** The list of active groups. */ protected List<SoundGroup> _groups = Lists.newArrayList(); /** The list of sources to be deleted. */ protected int[] _finalizedSources; /** The list of buffers to be deleted. */ protected int[] _finalizedBuffers; /** The one and only sound manager, here for an exclusive performance by special request. * Available for all your sound playing needs. */ protected static SoundManager _soundmgr; /** Used to compute the in-memory size of sound samples. */ protected static LRUHashMap.ItemSizer<ClipBuffer> _sizer = new LRUHashMap.ItemSizer<ClipBuffer>() { public int computeSize (ClipBuffer item) { return item.getSize(); } }; /** Default to a cache size of one megabyte. */ protected static final int DEFAULT_CACHE_SIZE = 8 * 1024 * 1024; }
Scratch this one, calling getError prior to initializing the openAL sound system doesn't work. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@1178 ed5b42cb-e716-0410-a449-f6a68f950b19
src/main/java/com/threerings/openal/SoundManager.java
Scratch this one, calling getError prior to initializing the openAL sound system doesn't work.
<ide><path>rc/main/java/com/threerings/openal/SoundManager.java <ide> protected SoundManager (RunQueue rqueue) <ide> { <ide> _rqueue = rqueue; <del> <del> AL10.alGetError(); // throw away any unchecked error prior to an op we want to check <ide> <ide> // initialize the OpenAL sound system <ide> try {
Java
apache-2.0
8f4dc21b7b4f31fcdb21a907278c3e34e09ad907
0
jerkar/jerkar,jerkar/jerkar,jerkar/jerkar
package org.jerkar.tool.builtins.eclipse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.jerkar.api.depmanagement.JkAttachedArtifacts; import org.jerkar.api.depmanagement.JkDependencies; import org.jerkar.api.depmanagement.JkDependency; import org.jerkar.api.depmanagement.JkDependencyResolver; import org.jerkar.api.depmanagement.JkFileSystemDependency; import org.jerkar.api.depmanagement.JkModuleDepFile; import org.jerkar.api.depmanagement.JkModuleDependency; import org.jerkar.api.depmanagement.JkModuleId; import org.jerkar.api.depmanagement.JkResolveResult; import org.jerkar.api.depmanagement.JkScope; import org.jerkar.api.depmanagement.JkScopedDependency; import org.jerkar.api.depmanagement.JkVersionedModule; import org.jerkar.api.file.JkFileTree; import org.jerkar.api.file.JkFileTreeSet; import org.jerkar.api.system.JkLocator; import org.jerkar.api.utils.JkUtilsFile; import org.jerkar.api.utils.JkUtilsIterable; import org.jerkar.api.utils.JkUtilsString; import org.jerkar.api.utils.JkUtilsThrowable; import org.jerkar.tool.JkConstants; import org.jerkar.tool.JkOptions; import org.jerkar.tool.builtins.javabuild.JkJavaBuild; /** * Provides method to generate and read Eclipse metadata files. */ final class DotClasspathGenerator { private static final String ENCODING = "UTF-8"; static final String OPTION_VAR_PREFIX = "eclipse.var."; private final File projectDir; /** default to projectDir/.classpath */ public File outputFile; /** optional */ public String jreContainer; /** attach javadoc to the lib dependencies */ public boolean includeJavadoc = true; /** Used to generate JRE container */ public String sourceJavaVersion; /** Can be empty but not null */ public JkFileTreeSet sources = JkFileTreeSet.empty(); /** Can be empty but not null */ public JkFileTreeSet testSources = JkFileTreeSet.empty(); /** Directory where are compiled test classes */ public File testClassDir; /** Dependency resolver to fetch module dependencies */ public JkDependencyResolver dependencyResolver; /** Dependency resolver to fetch module dependencies for build classes */ public JkDependencyResolver buildDefDependencyResolver; /** Can be empty but not null */ public Iterable<File> projectDependencies = JkUtilsIterable.listOf(); /** * Constructs a {@link JkDotClasspathGenerator} from the project base * directory */ public DotClasspathGenerator(File projectDir) { super(); this.projectDir = projectDir; this.outputFile = new File(projectDir, ".classpath"); } /** Generate the .classpath file */ public void generate() { try { _generate(); } catch (final Exception e) { throw JkUtilsThrowable.unchecked(e); } } void _generate() throws IOException, XMLStreamException, FactoryConfigurationError { // final OutputStream fos = new FileOutputStream(outputFile); final ByteArrayOutputStream fos = new ByteArrayOutputStream(); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fos, ENCODING); writer.writeStartDocument(ENCODING, "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("classpath"); writer.writeCharacters("\n"); final Set<String> paths = new HashSet<String>(); generateJava(writer, paths); writeJre(writer); // Build class sources if (new File(projectDir, JkConstants.BUILD_DEF_DIR).exists()) { writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("path", JkConstants.BUILD_DEF_DIR); writer.writeAttribute("output", JkConstants.BUILD_DEF_BIN_DIR); writer.writeCharacters("\n"); } // Write entries for dependencies located under build/libs final Iterable<File> files = buildDefDependencyResolver.dependenciesToResolve().localFileDependencies(); writeFileEntries(files, writer, paths); // Write project dependencies for (final File depProjectDir : projectDependencies) { writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("exported", "true"); writer.writeAttribute("path", "/" + depProjectDir.getName()); writer.writeCharacters("\n"); } // Write output writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "output"); writer.writeAttribute("path", "bin"); writer.writeCharacters("\n"); writer.writeEndDocument(); writer.flush(); writer.close(); outputFile.delete(); JkUtilsFile.writeStringAtTop(outputFile, fos.toString(ENCODING)); } private static String eclipseJavaVersion(String compilerVersion) { if ("7".equals(compilerVersion)) { return "1.7"; } if ("8".equals(compilerVersion)) { return "1.8"; } return compilerVersion; } private void writeFileEntries(Iterable<File> fileDeps, XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { for (final File file : fileDeps) { writeFileEntry(file, writer, paths); } } private void writeJre(XMLStreamWriter writer) throws XMLStreamException { writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "con"); final String container; if (jreContainer != null) { container = jreContainer; } else { container = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-" + eclipseJavaVersion(sourceJavaVersion); } writer.writeAttribute("path", container); writer.writeCharacters("\n"); } private void writeFileEntry(File file, XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { final String name = JkUtilsString.substringBeforeLast(file.getName(), ".jar"); File source = new File(file.getParentFile(), name + "-sources.jar"); if (!source.exists()) { source = new File(file.getParentFile(), "../../libs-sources/" + name + "-sources.jar"); } if (!source.exists()) { source = new File(file.getParentFile(), "libs-sources/" + name + "-sources.jar"); } File javadoc = new File(file.getParentFile(), name + "-javadoc.jar"); if (!javadoc.exists()) { javadoc = new File(file.getParentFile(), "../../libs-javadoc/" + name + "-javadoc.jar"); } if (!javadoc.exists()) { javadoc = new File(file.getParentFile(), "libs-javadoc/" + name + "-javadoc.jar"); } writeClasspathEntry(writer, file, source, javadoc, paths); } private void generateJava(XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { // Sources final Set<String> sourcePaths = new HashSet<String>(); // Test Sources for (final JkFileTree jkFileTree : testSources.fileTrees()) { if (!jkFileTree.root().exists()) { continue; } final String path = JkUtilsFile.getRelativePath(projectDir, jkFileTree.root()).replace(File.separator, "/"); if (sourcePaths.contains(path)) { continue; } sourcePaths.add(path); writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("output", JkUtilsFile.getRelativePath(projectDir, testClassDir).replace(File.separator, "/")); writer.writeAttribute("path", path); writer.writeCharacters("\n"); } for (final JkFileTree jkFileTree : sources.fileTrees()) { if (!jkFileTree.root().exists()) { continue; } final String path = JkUtilsFile.getRelativePath(projectDir, jkFileTree.root()).replace(File.separator, "/"); if (sourcePaths.contains(path)) { continue; } sourcePaths.add(path); writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("path", path); writer.writeCharacters("\n"); } // Write entries for dependencies writeDependenciesEntries(writer, paths); } // private void writeDependenciesEntriesOld(XMLStreamWriter writer) throws XMLStreamException { // if (dependencyResolver.dependenciesToResolve().containsModules()) { // final JkResolveResult resolveResult = dependencyResolver.resolve(JkJavaBuild.COMPILE, JkJavaBuild.RUNTIME, // JkJavaBuild.PROVIDED, JkJavaBuild.TEST); // writeExternalModuleEntries(dependencyResolver, writer, resolveResult); // } // if (buildDefDependencyResolver.dependenciesToResolve().containsModules()) { // final JkResolveResult buildresolve = buildDefDependencyResolver.resolve(); // writeExternalModuleEntries(buildDefDependencyResolver, writer, buildresolve); // } // } private void writeDependenciesEntries(XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { final JkResolveResult resolveResult = dependencyResolver.resolve(allScopes()) .and(buildDefDependencyResolver.resolve()); final JkDependencies allDeps = this.dependencyResolver.dependenciesToResolve() .and(this.buildDefDependencyResolver.dependenciesToResolve()); final JkAttachedArtifacts attachedArtifacts; if (dependencyResolver.dependenciesToResolve().containsModules()) { attachedArtifacts = dependencyResolver.getAttachedArtifacts( new HashSet<JkVersionedModule>(resolveResult.involvedModules()), JkJavaBuild.SOURCES, JkJavaBuild.JAVADOC); } else { attachedArtifacts = null; } for (final JkScopedDependency scopedDependency : allDeps) { final JkDependency dependency = scopedDependency.dependency(); if (dependency instanceof JkModuleDependency) { final JkModuleDependency moduleDependency = (JkModuleDependency) dependency; writeModuleEntry(moduleDependency.moduleId(), writer, resolveResult, attachedArtifacts, paths); } else if (dependency instanceof JkFileSystemDependency) { final JkFileSystemDependency fileSystemDependency = (JkFileSystemDependency) dependency; writeFileEntries(fileSystemDependency.files(), writer, paths); } } writeExternalModuleEntries(attachedArtifacts, writer, resolveResult, paths); } private void writeExternalModuleEntries(JkAttachedArtifacts attachedArtifacts, final XMLStreamWriter writer, JkResolveResult resolveResult, Set<String> paths) throws XMLStreamException { for (final JkVersionedModule versionedModule : resolveResult.involvedModules()) { writeModuleEntry(versionedModule.moduleId(), writer, resolveResult, attachedArtifacts, paths); } } private void writeModuleEntry(JkModuleId moduleId, XMLStreamWriter writer, JkResolveResult resolveResult, JkAttachedArtifacts jkAttachedArtifacts, Set<String> paths) throws XMLStreamException { File source = null; File javadoc = null; if (jkAttachedArtifacts != null) { final Set<JkModuleDepFile> sourcesArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.SOURCES); if (!sourcesArtifacts.isEmpty()) { source = sourcesArtifacts.iterator().next().localFile(); } final Set<JkModuleDepFile> javadocArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.JAVADOC); if (!javadocArtifacts.isEmpty() && includeJavadoc) { javadoc = javadocArtifacts.iterator().next().localFile(); } } writeClasspathEntry(writer, resolveResult.filesOf(moduleId).get(0), source, javadoc, paths); } private void writeClasspathEntry(XMLStreamWriter writer, File bin, File source, File javadoc, Set<String> paths) throws XMLStreamException { final VarReplacement binReplacement = new VarReplacement(bin); if (binReplacement.skiped) { return; } final String binPath = binReplacement.path; if (paths.contains(binPath)) { return; } paths.add(binPath); writer.writeCharacters("\t"); if (javadoc == null || !javadoc.exists()) { writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); } else { writer.writeStartElement(DotClasspathModel.CLASSPATHENTRY); } if (binReplacement.replaced) { writer.writeAttribute("kind", "var"); } else { writer.writeAttribute("kind", "lib"); } writer.writeAttribute("path", binPath); if (source != null && source.exists()) { final VarReplacement sourceReplacement = new VarReplacement(source); writer.writeAttribute("sourcepath", sourceReplacement.path); } if (javadoc != null && javadoc.exists()) { writer.writeCharacters("\n\t\t"); writer.writeStartElement("attributes"); writer.writeCharacters("\n\t\t\t"); writer.writeEmptyElement("attribute"); writer.writeAttribute("name", "javadoc_location"); writer.writeAttribute("value", "jar:file:/" + JkUtilsFile.canonicalPath(javadoc).replace(File.separator, "/")); writer.writeCharacters("\n\t\t"); writer.writeEndElement(); writer.writeCharacters("\n\t"); writer.writeEndElement(); } writer.writeCharacters("\n"); } private static JkScope[] allScopes() { return new JkScope[] {JkJavaBuild.COMPILE, JkJavaBuild.PROVIDED, JkJavaBuild.RUNTIME, JkJavaBuild.TEST}; } private class VarReplacement { public final boolean replaced; public final String path; public final boolean skiped; public VarReplacement(File file) { final Map<String, String> map = JkOptions.getAllStartingWith(DotClasspathGenerator.OPTION_VAR_PREFIX); map.put(DotClasspathGenerator.OPTION_VAR_PREFIX + DotClasspathModel.JERKAR_REPO, JkLocator.jerkarRepositoryCache().getAbsolutePath()); if (!JkLocator.jerkarJarFile().isDirectory()) { map.put(DotClasspathGenerator.OPTION_VAR_PREFIX + DotClasspathModel.JERKAR_HOME, JkLocator.jerkarHome().getAbsolutePath()); } boolean replaced = false; String path = JkUtilsFile.canonicalPath(file).replace(File.separator, "/"); // replace with var for (final Map.Entry<String, String> entry : map.entrySet()) { final File varDir = new File(entry.getValue()); if (JkUtilsFile.isAncestor(varDir, file)) { final String relativePath = JkUtilsFile.getRelativePath(varDir, file); replaced = true; path = entry.getKey().substring(DotClasspathGenerator.OPTION_VAR_PREFIX.length()) + "/" + relativePath; path = path.replace(File.separator, "/"); break; } } // Replace with relative path if (!replaced) { final String relpPath = toDependendeeProjectRelativePath(file); if (relpPath != null) { if (file.getName().toLowerCase().endsWith(".jar")) { skiped = true; } else { skiped = false; path = relpPath; } } else { path = toRelativePath(file); skiped = false; } } else { skiped = false; } this.path = path; this.replaced = replaced; } } private String toDependendeeProjectRelativePath(File file) { for (final File projectFile : this.projectDependencies) { if (JkUtilsFile.isAncestor(projectFile, file)) { final String relativePath = JkUtilsFile.getRelativePath(projectFile, projectFile); final Project project = Project.of(new File(projectFile, ".project")); return "/" + project.name + "/" + relativePath; } } return null; } private String toRelativePath(File file) { if (JkUtilsFile.isAncestor(this.projectDir, file)) { return JkUtilsFile.getRelativePath(projectDir, file).replace(File.separatorChar, '/'); } return JkUtilsFile.canonicalPath(file); } private static String toPatternString(List<String> pattern) { return JkUtilsString.join(pattern, "|"); } }
org.jerkar.core/src/main/java/org/jerkar/tool/builtins/eclipse/DotClasspathGenerator.java
package org.jerkar.tool.builtins.eclipse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.jerkar.api.depmanagement.JkAttachedArtifacts; import org.jerkar.api.depmanagement.JkDependencies; import org.jerkar.api.depmanagement.JkDependency; import org.jerkar.api.depmanagement.JkDependencyResolver; import org.jerkar.api.depmanagement.JkFileSystemDependency; import org.jerkar.api.depmanagement.JkModuleDepFile; import org.jerkar.api.depmanagement.JkModuleDependency; import org.jerkar.api.depmanagement.JkModuleId; import org.jerkar.api.depmanagement.JkResolveResult; import org.jerkar.api.depmanagement.JkScope; import org.jerkar.api.depmanagement.JkScopedDependency; import org.jerkar.api.depmanagement.JkVersionedModule; import org.jerkar.api.file.JkFileTree; import org.jerkar.api.file.JkFileTreeSet; import org.jerkar.api.system.JkLocator; import org.jerkar.api.utils.JkUtilsFile; import org.jerkar.api.utils.JkUtilsIterable; import org.jerkar.api.utils.JkUtilsString; import org.jerkar.api.utils.JkUtilsThrowable; import org.jerkar.tool.JkConstants; import org.jerkar.tool.JkOptions; import org.jerkar.tool.builtins.javabuild.JkJavaBuild; /** * Provides method to generate and read Eclipse metadata files. */ final class DotClasspathGenerator { private static final String ENCODING = "UTF-8"; static final String OPTION_VAR_PREFIX = "eclipse.var."; private final File projectDir; /** default to projectDir/.classpath */ public File outputFile; /** optional */ public String jreContainer; /** attach javadoc to the lib dependencies */ public boolean includeJavadoc = true; /** Used to generate JRE container */ public String sourceJavaVersion; /** Can be empty but not null */ public JkFileTreeSet sources = JkFileTreeSet.empty(); /** Can be empty but not null */ public JkFileTreeSet testSources = JkFileTreeSet.empty(); /** Directory where are compiled test classes */ public File testClassDir; /** Dependency resolver to fetch module dependencies */ public JkDependencyResolver dependencyResolver; /** Dependency resolver to fetch module dependencies for build classes */ public JkDependencyResolver buildDefDependencyResolver; /** Can be empty but not null */ public Iterable<File> projectDependencies = JkUtilsIterable.listOf(); /** * Constructs a {@link JkDotClasspathGenerator} from the project base * directory */ public DotClasspathGenerator(File projectDir) { super(); this.projectDir = projectDir; this.outputFile = new File(projectDir, ".classpath"); } /** Generate the .classpath file */ public void generate() { try { _generate(); } catch (final Exception e) { throw JkUtilsThrowable.unchecked(e); } } void _generate() throws IOException, XMLStreamException, FactoryConfigurationError { // final OutputStream fos = new FileOutputStream(outputFile); final ByteArrayOutputStream fos = new ByteArrayOutputStream(); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fos, ENCODING); writer.writeStartDocument(ENCODING, "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("classpath"); writer.writeCharacters("\n"); final Set<String> paths = new HashSet<String>(); generateJava(writer, paths); writeJre(writer); // Build class sources if (new File(projectDir, JkConstants.BUILD_DEF_DIR).exists()) { writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("path", JkConstants.BUILD_DEF_DIR); writer.writeAttribute("output", JkConstants.BUILD_DEF_BIN_DIR); writer.writeCharacters("\n"); } // Write entries for dependencies located under build/libs final Iterable<File> files = buildDefDependencyResolver.dependenciesToResolve().localFileDependencies(); writeFileEntries(files, writer, paths); // Write project dependencies for (final File depProjectDir : projectDependencies) { writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("exported", "true"); writer.writeAttribute("path", "/" + depProjectDir.getName()); writer.writeCharacters("\n"); } // Write output writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "output"); writer.writeAttribute("path", "bin"); writer.writeCharacters("\n"); writer.writeEndDocument(); writer.flush(); writer.close(); outputFile.delete(); JkUtilsFile.writeStringAtTop(outputFile, fos.toString(ENCODING)); } private static String eclipseJavaVersion(String compilerVersion) { if ("7".equals(compilerVersion)) { return "1.7"; } if ("8".equals(compilerVersion)) { return "1.8"; } return compilerVersion; } private void writeFileEntries(Iterable<File> fileDeps, XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { for (final File file : fileDeps) { writeFileEntry(file, writer, paths); } } private void writeJre(XMLStreamWriter writer) throws XMLStreamException { writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "con"); final String container; if (jreContainer != null) { container = jreContainer; } else { container = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-" + eclipseJavaVersion(sourceJavaVersion); } writer.writeAttribute("path", container); writer.writeCharacters("\n"); } private void writeFileEntry(File file, XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { final String name = JkUtilsString.substringBeforeLast(file.getName(), ".jar"); File source = new File(file.getParentFile(), name + "-sources.jar"); if (!source.exists()) { source = new File(file.getParentFile(), "../../libs-sources/" + name + "-sources.jar"); } if (!source.exists()) { source = new File(file.getParentFile(), "libs-sources/" + name + "-sources.jar"); } File javadoc = new File(file.getParentFile(), name + "-javadoc.jar"); if (!javadoc.exists()) { javadoc = new File(file.getParentFile(), "../../libs-javadoc/" + name + "-javadoc.jar"); } if (!javadoc.exists()) { javadoc = new File(file.getParentFile(), "libs-javadoc/" + name + "-javadoc.jar"); } writeClasspathEntry(writer, file, source, javadoc, paths); } private void generateJava(XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { // Sources final Set<String> sourcePaths = new HashSet<String>(); // Test Sources for (final JkFileTree jkFileTree : testSources.fileTrees()) { if (!jkFileTree.root().exists()) { continue; } final String path = JkUtilsFile.getRelativePath(projectDir, jkFileTree.root()).replace(File.separator, "/"); if (sourcePaths.contains(path)) { continue; } sourcePaths.add(path); writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("output", JkUtilsFile.getRelativePath(projectDir, testClassDir).replace(File.separator, "/")); writer.writeAttribute("path", path); writer.writeCharacters("\n"); } for (final JkFileTree jkFileTree : sources.fileTrees()) { if (!jkFileTree.root().exists()) { continue; } final String path = JkUtilsFile.getRelativePath(projectDir, jkFileTree.root()).replace(File.separator, "/"); if (sourcePaths.contains(path)) { continue; } sourcePaths.add(path); writer.writeCharacters("\t"); writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); writer.writeAttribute("kind", "src"); writer.writeAttribute("path", path); writer.writeCharacters("\n"); } // Write entries for dependencies writeDependenciesEntries(writer, paths); } // private void writeDependenciesEntriesOld(XMLStreamWriter writer) throws XMLStreamException { // if (dependencyResolver.dependenciesToResolve().containsModules()) { // final JkResolveResult resolveResult = dependencyResolver.resolve(JkJavaBuild.COMPILE, JkJavaBuild.RUNTIME, // JkJavaBuild.PROVIDED, JkJavaBuild.TEST); // writeExternalModuleEntries(dependencyResolver, writer, resolveResult); // } // if (buildDefDependencyResolver.dependenciesToResolve().containsModules()) { // final JkResolveResult buildresolve = buildDefDependencyResolver.resolve(); // writeExternalModuleEntries(buildDefDependencyResolver, writer, buildresolve); // } // } private void writeDependenciesEntries(XMLStreamWriter writer, Set<String> paths) throws XMLStreamException { final JkResolveResult resolveResult = dependencyResolver.resolve(allScopes()) .and(buildDefDependencyResolver.resolve()); final JkDependencies allDeps = this.dependencyResolver.dependenciesToResolve() .and(this.buildDefDependencyResolver.dependenciesToResolve()); final JkAttachedArtifacts attachedArtifacts; if (dependencyResolver.dependenciesToResolve().containsModules()) { attachedArtifacts = dependencyResolver.getAttachedArtifacts( new HashSet<JkVersionedModule>(resolveResult.involvedModules()), JkJavaBuild.SOURCES, JkJavaBuild.JAVADOC); } else { attachedArtifacts = null; } for (final JkScopedDependency scopedDependency : allDeps) { final JkDependency dependency = scopedDependency.dependency(); if (dependency instanceof JkModuleDependency) { final JkModuleDependency moduleDependency = (JkModuleDependency) dependency; writeModuleEntry(moduleDependency.moduleId(), writer, resolveResult, attachedArtifacts, paths); } else if (dependency instanceof JkFileSystemDependency) { final JkFileSystemDependency fileSystemDependency = (JkFileSystemDependency) dependency; writeFileEntries(fileSystemDependency.files(), writer, paths); } } writeExternalModuleEntries(attachedArtifacts, writer, resolveResult, paths); } private void writeExternalModuleEntries(JkAttachedArtifacts attachedArtifacts, final XMLStreamWriter writer, JkResolveResult resolveResult, Set<String> paths) throws XMLStreamException { for (final JkVersionedModule versionedModule : resolveResult.involvedModules()) { writeModuleEntry(versionedModule.moduleId(), writer, resolveResult, attachedArtifacts, paths); } } private void writeModuleEntry(JkModuleId moduleId, XMLStreamWriter writer, JkResolveResult resolveResult, JkAttachedArtifacts jkAttachedArtifacts, Set<String> paths) throws XMLStreamException { final Set<JkModuleDepFile> sourcesArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.SOURCES); final File source; if (!sourcesArtifacts.isEmpty()) { source = sourcesArtifacts.iterator().next().localFile(); } else { source = null; } final Set<JkModuleDepFile> javadocArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.JAVADOC); final File javadoc; if (!javadocArtifacts.isEmpty() && includeJavadoc) { javadoc = javadocArtifacts.iterator().next().localFile(); } else { javadoc = null; } writeClasspathEntry(writer, resolveResult.filesOf(moduleId).get(0), source, javadoc, paths); } private void writeClasspathEntry(XMLStreamWriter writer, File bin, File source, File javadoc, Set<String> paths) throws XMLStreamException { final VarReplacement binReplacement = new VarReplacement(bin); if (binReplacement.skiped) { return; } final String binPath = binReplacement.path; if (paths.contains(binPath)) { return; } paths.add(binPath); writer.writeCharacters("\t"); if (javadoc == null || !javadoc.exists()) { writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY); } else { writer.writeStartElement(DotClasspathModel.CLASSPATHENTRY); } if (binReplacement.replaced) { writer.writeAttribute("kind", "var"); } else { writer.writeAttribute("kind", "lib"); } writer.writeAttribute("path", binPath); if (source != null && source.exists()) { final VarReplacement sourceReplacement = new VarReplacement(source); writer.writeAttribute("sourcepath", sourceReplacement.path); } if (javadoc != null && javadoc.exists()) { writer.writeCharacters("\n\t\t"); writer.writeStartElement("attributes"); writer.writeCharacters("\n\t\t\t"); writer.writeEmptyElement("attribute"); writer.writeAttribute("name", "javadoc_location"); writer.writeAttribute("value", "jar:file:/" + JkUtilsFile.canonicalPath(javadoc).replace(File.separator, "/")); writer.writeCharacters("\n\t\t"); writer.writeEndElement(); writer.writeCharacters("\n\t"); writer.writeEndElement(); } writer.writeCharacters("\n"); } private static JkScope[] allScopes() { return new JkScope[] {JkJavaBuild.COMPILE, JkJavaBuild.PROVIDED, JkJavaBuild.RUNTIME, JkJavaBuild.TEST}; } private class VarReplacement { public final boolean replaced; public final String path; public final boolean skiped; public VarReplacement(File file) { final Map<String, String> map = JkOptions.getAllStartingWith(DotClasspathGenerator.OPTION_VAR_PREFIX); map.put(DotClasspathGenerator.OPTION_VAR_PREFIX + DotClasspathModel.JERKAR_REPO, JkLocator.jerkarRepositoryCache().getAbsolutePath()); if (!JkLocator.jerkarJarFile().isDirectory()) { map.put(DotClasspathGenerator.OPTION_VAR_PREFIX + DotClasspathModel.JERKAR_HOME, JkLocator.jerkarHome().getAbsolutePath()); } boolean replaced = false; String path = JkUtilsFile.canonicalPath(file).replace(File.separator, "/"); // replace with var for (final Map.Entry<String, String> entry : map.entrySet()) { final File varDir = new File(entry.getValue()); if (JkUtilsFile.isAncestor(varDir, file)) { final String relativePath = JkUtilsFile.getRelativePath(varDir, file); replaced = true; path = entry.getKey().substring(DotClasspathGenerator.OPTION_VAR_PREFIX.length()) + "/" + relativePath; path = path.replace(File.separator, "/"); break; } } // Replace with relative path if (!replaced) { final String relpPath = toDependendeeProjectRelativePath(file); if (relpPath != null) { if (file.getName().toLowerCase().endsWith(".jar")) { skiped = true; } else { skiped = false; path = relpPath; } } else { path = toRelativePath(file); skiped = false; } } else { skiped = false; } this.path = path; this.replaced = replaced; } } private String toDependendeeProjectRelativePath(File file) { for (final File projectFile : this.projectDependencies) { if (JkUtilsFile.isAncestor(projectFile, file)) { final String relativePath = JkUtilsFile.getRelativePath(projectFile, projectFile); final Project project = Project.of(new File(projectFile, ".project")); return "/" + project.name + "/" + relativePath; } } return null; } private String toRelativePath(File file) { if (JkUtilsFile.isAncestor(this.projectDir, file)) { return JkUtilsFile.getRelativePath(projectDir, file).replace(File.separatorChar, '/'); } return JkUtilsFile.canonicalPath(file); } private static String toPatternString(List<String> pattern) { return JkUtilsString.join(pattern, "|"); } }
fixes #52
org.jerkar.core/src/main/java/org/jerkar/tool/builtins/eclipse/DotClasspathGenerator.java
fixes #52
<ide><path>rg.jerkar.core/src/main/java/org/jerkar/tool/builtins/eclipse/DotClasspathGenerator.java <ide> <ide> private void writeModuleEntry(JkModuleId moduleId, XMLStreamWriter writer, JkResolveResult resolveResult, <ide> JkAttachedArtifacts jkAttachedArtifacts, Set<String> paths) throws XMLStreamException { <del> final Set<JkModuleDepFile> sourcesArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.SOURCES); <del> final File source; <del> if (!sourcesArtifacts.isEmpty()) { <del> source = sourcesArtifacts.iterator().next().localFile(); <del> } else { <del> source = null; <del> } <del> final Set<JkModuleDepFile> javadocArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.JAVADOC); <del> final File javadoc; <del> if (!javadocArtifacts.isEmpty() && includeJavadoc) { <del> javadoc = javadocArtifacts.iterator().next().localFile(); <del> } else { <del> javadoc = null; <add> File source = null; <add> File javadoc = null; <add> if (jkAttachedArtifacts != null) { <add> final Set<JkModuleDepFile> sourcesArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.SOURCES); <add> if (!sourcesArtifacts.isEmpty()) { <add> source = sourcesArtifacts.iterator().next().localFile(); <add> } <add> final Set<JkModuleDepFile> javadocArtifacts = jkAttachedArtifacts.getArtifacts(moduleId, JkJavaBuild.JAVADOC); <add> if (!javadocArtifacts.isEmpty() && includeJavadoc) { <add> javadoc = javadocArtifacts.iterator().next().localFile(); <add> } <ide> } <ide> writeClasspathEntry(writer, resolveResult.filesOf(moduleId).get(0), source, javadoc, paths); <ide> }
Java
apache-2.0
223ef9d742fe9813d564b4722d69a02607174f3e
0
allotria/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,allotria/intellij-community,FHannes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,FHannes/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,retomerz/intellij-community,da1z/intellij-community,signed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,allotria/intellij-community,semonte/intellij-community,semonte/intellij-community,retomerz/intellij-community,fitermay/intellij-community,retomerz/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,retomerz/intellij-community,hurricup/intellij-community,asedunov/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,hurricup/intellij-community,hurricup/intellij-community,semonte/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,fitermay/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,allotria/intellij-community,apixandru/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,fitermay/intellij-community,signed/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,xfournet/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,signed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,hurricup/intellij-community,asedunov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,signed/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,signed/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,retomerz/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,allotria/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,apixandru/intellij-community,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,signed/intellij-community,fitermay/intellij-community,signed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,hurricup/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,signed/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,asedunov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,semonte/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,fitermay/intellij-community,allotria/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ibinti/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,retomerz/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,xfournet/intellij-community,semonte/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,signed/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,fitermay/intellij-community,FHannes/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.util.io; import com.intellij.CommonBundle; import com.intellij.Patches; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.*; import com.intellij.util.concurrency.FixedFuture; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.io.URLUtil; import com.intellij.util.text.FilePathHashingStrategy; import com.intellij.util.text.StringFactory; import gnu.trove.TObjectHashingStrategy; import org.intellij.lang.annotations.RegExp; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.*; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.RunnableFuture; import java.util.regex.Pattern; @SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"}) public class FileUtil extends FileUtilRt { static { if (!Patches.USE_REFLECTION_TO_ACCESS_JDK7) throw new RuntimeException("Please migrate FileUtilRt to JDK8"); } public static final String ASYNC_DELETE_EXTENSION = ".__del__"; public static final int REGEX_PATTERN_FLAGS = SystemInfo.isFileSystemCaseSensitive ? 0 : Pattern.CASE_INSENSITIVE; public static final TObjectHashingStrategy<String> PATH_HASHING_STRATEGY = FilePathHashingStrategy.create(); public static final TObjectHashingStrategy<File> FILE_HASHING_STRATEGY = SystemInfo.isFileSystemCaseSensitive ? ContainerUtil.<File>canonicalStrategy() : new TObjectHashingStrategy<File>() { @Override public int computeHashCode(File object) { return fileHashCode(object); } @Override public boolean equals(File o1, File o2) { return filesEqual(o1, o2); } }; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil"); @NotNull public static String join(@NotNull final String... parts) { return StringUtil.join(parts, File.separator); } @Nullable public static String getRelativePath(File base, File file) { return FileUtilRt.getRelativePath(base, file); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) { return FileUtilRt.getRelativePath(basePath, filePath, separator); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator, final boolean caseSensitive) { return FileUtilRt.getRelativePath(basePath, filePath, separator, caseSensitive); } public static boolean isAbsolute(@NotNull String path) { return new File(path).isAbsolute(); } /** * Check if the {@code ancestor} is an ancestor of {@code file}. * * @param ancestor supposed ancestor. * @param file supposed descendant. * @param strict if {@code false} then this method returns {@code true} if {@code ancestor} equals to {@code file}. * @return {@code true} if {@code ancestor} is parent of {@code file}; {@code false} otherwise. */ public static boolean isAncestor(@NotNull File ancestor, @NotNull File file, boolean strict) { return isAncestor(ancestor.getPath(), file.getPath(), strict); } public static boolean isAncestor(@NotNull String ancestor, @NotNull String file, boolean strict) { return !ThreeState.NO.equals(isAncestorThreeState(ancestor, file, strict)); } /** * Checks if the {@code ancestor} is an ancestor of the {@code file}, and if it is an immediate parent or not. * * @param ancestor supposed ancestor. * @param file supposed descendant. * @param strict if {@code false}, the file can be ancestor of itself, * i.e. the method returns {@code ThreeState.YES} if {@code ancestor} equals to {@code file}. * * @return {@code ThreeState.YES} if ancestor is an immediate parent of the file, * {@code ThreeState.UNSURE} if ancestor is not immediate parent of the file, * {@code ThreeState.NO} if ancestor is not a parent of the file at all. */ @NotNull public static ThreeState isAncestorThreeState(@NotNull String ancestor, @NotNull String file, boolean strict) { String ancestorPath = toCanonicalPath(ancestor); String filePath = toCanonicalPath(file); return startsWith(filePath, ancestorPath, strict, SystemInfo.isFileSystemCaseSensitive, true); } public static boolean startsWith(@NotNull String path, @NotNull String start) { return !ThreeState.NO.equals(startsWith(path, start, false, SystemInfo.isFileSystemCaseSensitive, false)); } public static boolean startsWith(@NotNull String path, @NotNull String start, boolean caseSensitive) { return !ThreeState.NO.equals(startsWith(path, start, false, caseSensitive, false)); } @NotNull private static ThreeState startsWith(@NotNull String path, @NotNull String prefix, boolean strict, boolean caseSensitive, boolean checkImmediateParent) { final int pathLength = path.length(); final int prefixLength = prefix.length(); if (prefixLength == 0) return pathLength == 0 ? ThreeState.YES : ThreeState.UNSURE; if (prefixLength > pathLength) return ThreeState.NO; if (!path.regionMatches(!caseSensitive, 0, prefix, 0, prefixLength)) return ThreeState.NO; if (pathLength == prefixLength) { return strict ? ThreeState.NO : ThreeState.YES; } char lastPrefixChar = prefix.charAt(prefixLength - 1); int slashOrSeparatorIdx = prefixLength; if (lastPrefixChar == '/' || lastPrefixChar == File.separatorChar) { slashOrSeparatorIdx = prefixLength - 1; } char next1 = path.charAt(slashOrSeparatorIdx); if (next1 == '/' || next1 == File.separatorChar) { if (!checkImmediateParent) return ThreeState.YES; if (slashOrSeparatorIdx == pathLength - 1) return ThreeState.YES; int idxNext = path.indexOf(next1, slashOrSeparatorIdx + 1); idxNext = idxNext == -1 ? path.indexOf(next1 == '/' ? '\\' : '/', slashOrSeparatorIdx + 1) : idxNext; return idxNext == -1 ? ThreeState.YES : ThreeState.UNSURE; } else { return ThreeState.NO; } } /** * @param removeProcessor parent, child */ public static <T> Collection<T> removeAncestors(final Collection<T> files, final Convertor<T, String> convertor, final PairProcessor<T, T> removeProcessor) { if (files.isEmpty()) return files; final TreeMap<String, T> paths = new TreeMap<String, T>(); for (T file : files) { final String path = convertor.convert(file); assert path != null; final String canonicalPath = toCanonicalPath(path); paths.put(canonicalPath, file); } final List<Map.Entry<String, T>> ordered = new ArrayList<Map.Entry<String, T>>(paths.entrySet()); final List<T> result = new ArrayList<T>(ordered.size()); result.add(ordered.get(0).getValue()); for (int i = 1; i < ordered.size(); i++) { final Map.Entry<String, T> entry = ordered.get(i); final String child = entry.getKey(); boolean parentNotFound = true; for (int j = i - 1; j >= 0; j--) { // possible parents final String parent = ordered.get(j).getKey(); if (parent == null) continue; if (startsWith(child, parent) && removeProcessor.process(ordered.get(j).getValue(), entry.getValue())) { parentNotFound = false; break; } } if (parentNotFound) { result.add(entry.getValue()); } } return result; } @Nullable public static File getParentFile(@NotNull File file) { return FileUtilRt.getParentFile(file); } @NotNull public static byte[] loadFileBytes(@NotNull File file) throws IOException { byte[] bytes; final InputStream stream = new FileInputStream(file); try { final long len = file.length(); if (len < 0) { throw new IOException("File length reported negative, probably doesn't exist"); } if (isTooLarge(len)) { throw new FileTooBigException("Attempt to load '" + file + "' in memory buffer, file length is " + len + " bytes."); } bytes = loadBytes(stream, (int)len); } finally { stream.close(); } return bytes; } @NotNull public static byte[] loadFirst(@NotNull InputStream stream, int maxLength) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); copy(stream, maxLength, buffer); buffer.close(); return buffer.toByteArray(); } @NotNull public static String loadTextAndClose(@NotNull InputStream stream) throws IOException { //noinspection IOResourceOpenedButNotSafelyClosed return loadTextAndClose(new InputStreamReader(stream)); } @NotNull public static String loadTextAndClose(@NotNull Reader reader) throws IOException { try { return StringFactory.createShared(adaptiveLoadText(reader)); } finally { reader.close(); } } @NotNull public static char[] adaptiveLoadText(@NotNull Reader reader) throws IOException { char[] chars = new char[4096]; List<char[]> buffers = null; int count = 0; int total = 0; while (true) { int n = reader.read(chars, count, chars.length - count); if (n <= 0) break; count += n; if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + reader); total += n; if (count == chars.length) { if (buffers == null) { buffers = new ArrayList<char[]>(); } buffers.add(chars); int newLength = Math.min(1024 * 1024, chars.length * 2); chars = new char[newLength]; count = 0; } } char[] result = new char[total]; if (buffers != null) { for (char[] buffer : buffers) { System.arraycopy(buffer, 0, result, result.length - total, buffer.length); total -= buffer.length; } } System.arraycopy(chars, 0, result, result.length - total, total); return result; } @NotNull public static byte[] adaptiveLoadBytes(@NotNull InputStream stream) throws IOException { byte[] bytes = getThreadLocalBuffer(); List<byte[]> buffers = null; int count = 0; int total = 0; while (true) { int n = stream.read(bytes, count, bytes.length - count); if (n <= 0) break; count += n; if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + stream); total += n; if (count == bytes.length) { if (buffers == null) { buffers = new ArrayList<byte[]>(); } buffers.add(bytes); int newLength = Math.min(1024 * 1024, bytes.length * 2); bytes = new byte[newLength]; count = 0; } } byte[] result = new byte[total]; if (buffers != null) { for (byte[] buffer : buffers) { System.arraycopy(buffer, 0, result, result.length - total, buffer.length); total -= buffer.length; } } System.arraycopy(bytes, 0, result, result.length - total, total); return result; } @NotNull public static Future<Void> asyncDelete(@NotNull File file) { return asyncDelete(Collections.singleton(file)); } @NotNull public static Future<Void> asyncDelete(@NotNull Collection<File> files) { List<File> tempFiles = new ArrayList<File>(); for (File file : files) { final File tempFile = renameToTempFileOrDelete(file); if (tempFile != null) { tempFiles.add(tempFile); } } if (!tempFiles.isEmpty()) { return startDeletionThread(tempFiles.toArray(new File[tempFiles.size()])); } return new FixedFuture<Void>(null); } private static Future<Void> startDeletionThread(@NotNull final File... tempFiles) { final RunnableFuture<Void> deleteFilesTask = new FutureTask<Void>(new Runnable() { @Override public void run() { final Thread currentThread = Thread.currentThread(); final int priority = currentThread.getPriority(); currentThread.setPriority(Thread.MIN_PRIORITY); try { for (File tempFile : tempFiles) { delete(tempFile); } } finally { currentThread.setPriority(priority); } } }, null); try { // attempt to execute on pooled thread final Class<?> aClass = Class.forName("com.intellij.openapi.application.ApplicationManager"); final Method getApplicationMethod = aClass.getMethod("getApplication"); final Object application = getApplicationMethod.invoke(null); final Method executeOnPooledThreadMethod = application.getClass().getMethod("executeOnPooledThread", Runnable.class); executeOnPooledThreadMethod.invoke(application, deleteFilesTask); } catch (Exception ignored) { new Thread(deleteFilesTask, "File deletion thread").start(); } return deleteFilesTask; } @Nullable private static File renameToTempFileOrDelete(@NotNull File file) { String tempDir = getTempDirectory(); boolean isSameDrive = true; if (SystemInfo.isWindows) { String tempDirDrive = tempDir.substring(0, 2); String fileDrive = file.getAbsolutePath().substring(0, 2); isSameDrive = tempDirDrive.equalsIgnoreCase(fileDrive); } if (isSameDrive) { // the optimization is reasonable only if destination dir is located on the same drive final String originalFileName = file.getName(); File tempFile = getTempFile(originalFileName, tempDir); if (file.renameTo(tempFile)) { return tempFile; } } delete(file); return null; } private static File getTempFile(@NotNull String originalFileName, @NotNull String parent) { int randomSuffix = (int)(System.currentTimeMillis() % 1000); for (int i = randomSuffix; ; i++) { String name = "___" + originalFileName + i + ASYNC_DELETE_EXTENSION; File tempFile = new File(parent, name); if (!tempFile.exists()) return tempFile; } } public static boolean delete(@NotNull File file) { if (NIOReflect.IS_AVAILABLE) { return deleteRecursivelyNIO(file); } return deleteRecursively(file); } private static boolean deleteRecursively(@NotNull File file) { FileAttributes attributes = FileSystemUtil.getAttributes(file); if (attributes == null) return true; if (attributes.isDirectory() && !attributes.isSymLink()) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { if (!deleteRecursively(child)) return false; } } } return deleteFile(file); } public static boolean createParentDirs(@NotNull File file) { return FileUtilRt.createParentDirs(file); } public static boolean createDirectory(@NotNull File path) { return FileUtilRt.createDirectory(path); } public static boolean createIfDoesntExist(@NotNull File file) { return FileUtilRt.createIfNotExists(file); } public static boolean ensureCanCreateFile(@NotNull File file) { return FileUtilRt.ensureCanCreateFile(file); } public static void copy(@NotNull File fromFile, @NotNull File toFile) throws IOException { performCopy(fromFile, toFile, true); } public static void copyContent(@NotNull File fromFile, @NotNull File toFile) throws IOException { performCopy(fromFile, toFile, false); } @SuppressWarnings("Duplicates") private static void performCopy(@NotNull File fromFile, @NotNull File toFile, final boolean syncTimestamp) throws IOException { if (filesEqual(fromFile, toFile)) return; final FileOutputStream fos; try { fos = openOutputStream(toFile); } catch (IOException e) { if (SystemInfo.isWindows && e.getMessage() != null && e.getMessage().contains("denied") && WinUACTemporaryFix.nativeCopy(fromFile, toFile, syncTimestamp)) { return; } throw e; } try { final FileInputStream fis = new FileInputStream(fromFile); try { copy(fis, fos); } finally { fis.close(); } } finally { fos.close(); } if (syncTimestamp) { final long timeStamp = fromFile.lastModified(); if (timeStamp < 0) { LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'"); } else if (!toFile.setLastModified(timeStamp)) { LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'"); } } if (SystemInfo.isUnix && fromFile.canExecute()) { FileSystemUtil.clonePermissionsToExecute(fromFile.getPath(), toFile.getPath()); } } private static FileOutputStream openOutputStream(@NotNull final File file) throws IOException { try { return new FileOutputStream(file); } catch (FileNotFoundException e) { final File parentFile = file.getParentFile(); if (parentFile == null) { throw new IOException("Parent file is null for " + file.getPath(), e); } createParentDirs(file); return new FileOutputStream(file); } } public static void copy(@NotNull InputStream inputStream, @NotNull OutputStream outputStream) throws IOException { FileUtilRt.copy(inputStream, outputStream); } public static void copy(@NotNull InputStream inputStream, int maxSize, @NotNull OutputStream outputStream) throws IOException { final byte[] buffer = getThreadLocalBuffer(); int toRead = maxSize; while (toRead > 0) { int read = inputStream.read(buffer, 0, Math.min(buffer.length, toRead)); if (read < 0) break; toRead -= read; outputStream.write(buffer, 0, read); } } public static void copyFileOrDir(@NotNull File from, @NotNull File to) throws IOException { copyFileOrDir(from, to, from.isDirectory()); } public static void copyFileOrDir(@NotNull File from, @NotNull File to, boolean isDir) throws IOException { if (isDir) { copyDir(from, to); } else { copy(from, to); } } public static void copyDir(@NotNull File fromDir, @NotNull File toDir) throws IOException { copyDir(fromDir, toDir, true); } /** * Copies content of {@code fromDir} to {@code toDir}. * It's equivalent to "cp -r fromDir/* toDir" unix command. * * @param fromDir source directory * @param toDir destination directory * @throws IOException in case of any IO troubles */ public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException { File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY); for (File child : children) { copyFileOrDir(child, new File(toDir, child.getName())); } } public static void copyDir(@NotNull File fromDir, @NotNull File toDir, boolean copySystemFiles) throws IOException { copyDir(fromDir, toDir, copySystemFiles ? null : new FileFilter() { @Override public boolean accept(@NotNull File file) { return !StringUtil.startsWithChar(file.getName(), '.'); } }); } public static void copyDir(@NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter) throws IOException { ensureExists(toDir); if (isAncestor(fromDir, toDir, true)) { LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself."); return; } File[] files = fromDir.listFiles(); if (files == null) throw new IOException(CommonBundle.message("exception.directory.is.invalid", fromDir.getPath())); if (!fromDir.canRead()) throw new IOException(CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath())); for (File file : files) { if (filter != null && !filter.accept(file)) { continue; } if (file.isDirectory()) { copyDir(file, new File(toDir, file.getName()), filter); } else { copy(file, new File(toDir, file.getName())); } } } public static void ensureExists(@NotNull File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException(CommonBundle.message("exception.directory.can.not.create", dir.getPath())); } } @NotNull public static String getNameWithoutExtension(@NotNull File file) { return getNameWithoutExtension(file.getName()); } @NotNull public static String getNameWithoutExtension(@NotNull String name) { return FileUtilRt.getNameWithoutExtension(name); } public static String createSequentFileName(@NotNull File aParentFolder, @NotNull String aFilePrefix, @NotNull String aExtension) { return findSequentNonexistentFile(aParentFolder, aFilePrefix, aExtension).getName(); } public static File findSequentNonexistentFile(@NotNull File parentFolder, @NotNull String filePrefix, @NotNull String extension) { int postfix = 0; String ext = extension.isEmpty() ? "" : '.' + extension; File candidate = new File(parentFolder, filePrefix + ext); while (candidate.exists()) { postfix++; candidate = new File(parentFolder, filePrefix + Integer.toString(postfix) + ext); } return candidate; } @NotNull public static String toSystemDependentName(@NotNull String aFileName) { return FileUtilRt.toSystemDependentName(aFileName); } @NotNull public static String toSystemIndependentName(@NotNull String aFileName) { return FileUtilRt.toSystemIndependentName(aFileName); } /** @deprecated to be removed in IDEA 17 */ @SuppressWarnings({"unused", "StringToUpperCaseOrToLowerCaseWithoutLocale"}) public static String nameToCompare(@NotNull String name) { return (SystemInfo.isFileSystemCaseSensitive ? name : name.toLowerCase()).replace('\\', '/'); } /** * Converts given path to canonical representation by eliminating '.'s, traversing '..'s, and omitting duplicate separators. * Please note that this method is symlink-unfriendly (i.e. result of "/path/to/link/../next" most probably will differ from * what {@link File#getCanonicalPath()} will return) - so use with care.<br> * <br> * If the path may contain symlinks, use {@link FileUtil#toCanonicalPath(String, boolean)} instead. */ @Contract("null -> null") public static String toCanonicalPath(@Nullable String path) { return toCanonicalPath(path, File.separatorChar, true); } /** * When relative ../ parts do not escape outside of symlinks, the links are not expanded.<br> * That is, in the best-case scenario the original non-expanded path is preserved.<br> * <br> * Otherwise, returns a fully resolved path using {@link File#getCanonicalPath()}.<br> * <br> * Consider the following case: * <pre> * root/ * dir1/ * link_to_dir1 * dir2/ * </pre> * 'root/dir1/link_to_dir1/../dir2' should be resolved to 'root/dir2' */ @Contract("null, _ -> null") public static String toCanonicalPath(@Nullable String path, boolean resolveSymlinksIfNecessary) { return toCanonicalPath(path, File.separatorChar, true, resolveSymlinksIfNecessary); } @Contract("null, _ -> null") public static String toCanonicalPath(@Nullable String path, char separatorChar) { return toCanonicalPath(path, separatorChar, true); } @Contract("null -> null") public static String toCanonicalUriPath(@Nullable String path) { return toCanonicalPath(path, '/', false); } @Contract("null, _, _ -> null") private static String toCanonicalPath(@Nullable String path, char separatorChar, boolean removeLastSlash) { return toCanonicalPath(path, separatorChar, removeLastSlash, false); } @Contract("null, _, _, _ -> null") private static String toCanonicalPath(@Nullable String path, final char separatorChar, final boolean removeLastSlash, final boolean resolveSymlinks) { if (path == null || path.isEmpty()) { return path; } if (StringUtil.startsWithChar(path, '.')) { if (path.length() == 1) { return ""; } char c = path.charAt(1); if (c == '/' || c == separatorChar) { path = path.substring(2); } } path = path.replace(separatorChar, '/'); // trying to speedup the common case when there are no "//" or "/." int index = -1; do { index = path.indexOf('/', index+1); char next = index == path.length() - 1 ? 0 : path.charAt(index + 1); if (next == '.' || next == '/') { break; } } while (index != -1); if (index == -1) { if (removeLastSlash) { int start = processRoot(path, NullAppendable.INSTANCE); int slashIndex = path.lastIndexOf('/'); return slashIndex != -1 && slashIndex > start ? StringUtil.trimEnd(path, '/') : path; } return path; } final String finalPath = path; NotNullProducer<String> realCanonicalPath = resolveSymlinks ? new NotNullProducer<String>() { @NotNull @Override public String produce() { try { return new File(finalPath).getCanonicalPath().replace(separatorChar, '/'); } catch (IOException ignore) { // fall back to the default behavior return toCanonicalPath(finalPath, separatorChar, removeLastSlash, false); } } } : null; StringBuilder result = new StringBuilder(path.length()); int start = processRoot(path, result); int dots = 0; boolean separator = true; for (int i = start; i < path.length(); ++i) { char c = path.charAt(i); if (c == '/') { if (!separator) { if (!processDots(result, dots, start, resolveSymlinks)) { return realCanonicalPath.produce(); } dots = 0; } separator = true; } else if (c == '.') { if (separator || dots > 0) { ++dots; } else { result.append('.'); } separator = false; } else { if (dots > 0) { StringUtil.repeatSymbol(result, '.', dots); dots = 0; } result.append(c); separator = false; } } if (dots > 0) { if (!processDots(result, dots, start, resolveSymlinks)) { return realCanonicalPath.produce(); } } int lastChar = result.length() - 1; if (removeLastSlash && lastChar >= 0 && result.charAt(lastChar) == '/' && lastChar > start) { result.deleteCharAt(lastChar); } return result.toString(); } private static int processRoot(@NotNull String path, @NotNull Appendable result) { try { if (SystemInfo.isWindows && path.length() > 1 && path.charAt(0) == '/' && path.charAt(1) == '/') { result.append("//"); int hostStart = 2; while (hostStart < path.length() && path.charAt(hostStart) == '/') hostStart++; if (hostStart == path.length()) return hostStart; int hostEnd = path.indexOf('/', hostStart); if (hostEnd < 0) hostEnd = path.length(); result.append(path, hostStart, hostEnd); result.append('/'); int shareStart = hostEnd; while (shareStart < path.length() && path.charAt(shareStart) == '/') shareStart++; if (shareStart == path.length()) return shareStart; int shareEnd = path.indexOf('/', shareStart); if (shareEnd < 0) shareEnd = path.length(); result.append(path, shareStart, shareEnd); result.append('/'); return shareEnd; } if (!path.isEmpty() && path.charAt(0) == '/') { result.append('/'); return 1; } if (path.length() > 2 && path.charAt(1) == ':' && path.charAt(2) == '/') { result.append(path, 0, 3); return 3; } } catch (IOException e) { throw new RuntimeException(e); } return 0; } @Contract("_, _, _, false -> true") private static boolean processDots(@NotNull StringBuilder result, int dots, int start, boolean resolveSymlinks) { if (dots == 2) { int pos = -1; if (!StringUtil.endsWith(result, "/../") && !StringUtil.equals(result, "../")) { pos = StringUtil.lastIndexOf(result, '/', start, result.length() - 1); if (pos >= 0) { ++pos; // separator found, trim to next char } else if (start > 0) { pos = start; // path is absolute, trim to root ('/..' -> '/') } else if (result.length() > 0) { pos = 0; // path is relative, trim to default ('a/..' -> '') } } if (pos >= 0) { if (resolveSymlinks && FileSystemUtil.isSymLink(new File(result.toString()))) { return false; } result.delete(pos, result.length()); } else { result.append("../"); // impossible to traverse, keep as-is } } else if (dots != 1) { StringUtil.repeatSymbol(result, '.', dots); result.append('/'); } return true; } /** * converts back slashes to forward slashes * removes double slashes inside the path, e.g. "x/y//z" => "x/y/z" */ @NotNull public static String normalize(@NotNull String path) { int start = 0; boolean separator = false; if (SystemInfo.isWindows) { if (path.startsWith("//")) { start = 2; separator = true; } else if (path.startsWith("\\\\")) { return normalizeTail(0, path, false); } } for (int i = start; i < path.length(); ++i) { final char c = path.charAt(i); if (c == '/') { if (separator) { return normalizeTail(i, path, true); } separator = true; } else if (c == '\\') { return normalizeTail(i, path, separator); } else { separator = false; } } return path; } @NotNull private static String normalizeTail(int prefixEnd, @NotNull String path, boolean separator) { final StringBuilder result = new StringBuilder(path.length()); result.append(path, 0, prefixEnd); int start = prefixEnd; if (start==0 && SystemInfo.isWindows && (path.startsWith("//") || path.startsWith("\\\\"))) { start = 2; result.append("//"); separator = true; } for (int i = start; i < path.length(); ++i) { final char c = path.charAt(i); if (c == '/' || c == '\\') { if (!separator) result.append('/'); separator = true; } else { result.append(c); separator = false; } } return result.toString(); } @NotNull public static String unquote(@NotNull String urlString) { urlString = urlString.replace('/', File.separatorChar); return URLUtil.unescapePercentSequences(urlString); } public static boolean isFilePathAcceptable(@NotNull File root, @Nullable FileFilter fileFilter) { if (fileFilter == null) return true; File file = root; do { if (!fileFilter.accept(file)) return false; file = file.getParentFile(); } while (file != null); return true; } public static boolean rename(@NotNull File source, @NotNull String newName) throws IOException { File target = new File(source.getParent(), newName); if (!SystemInfo.isFileSystemCaseSensitive && newName.equalsIgnoreCase(source.getName())) { File intermediate = createTempFile(source.getParentFile(), source.getName(), ".tmp", false, false); return source.renameTo(intermediate) && intermediate.renameTo(target); } else { return source.renameTo(target); } } public static void rename(@NotNull File source, @NotNull File target) throws IOException { if (source.renameTo(target)) return; if (!source.exists()) return; copy(source, target); delete(source); } public static boolean filesEqual(@Nullable File file1, @Nullable File file2) { // on MacOS java.io.File.equals() is incorrectly case-sensitive return pathsEqual(file1 == null ? null : file1.getPath(), file2 == null ? null : file2.getPath()); } public static boolean pathsEqual(@Nullable String path1, @Nullable String path2) { if (path1 == path2) return true; if (path1 == null || path2 == null) return false; path1 = toCanonicalPath(path1); path2 = toCanonicalPath(path2); return PATH_HASHING_STRATEGY.equals(path1, path2); } /** * optimized version of pathsEqual - it only compares pure names, without file separators */ public static boolean namesEqual(@Nullable String name1, @Nullable String name2) { if (name1 == name2) return true; if (name1 == null || name2 == null) return false; return PATH_HASHING_STRATEGY.equals(name1, name2); } public static int compareFiles(@Nullable File file1, @Nullable File file2) { return comparePaths(file1 == null ? null : file1.getPath(), file2 == null ? null : file2.getPath()); } public static int comparePaths(@Nullable String path1, @Nullable String path2) { path1 = path1 == null ? null : toSystemIndependentName(path1); path2 = path2 == null ? null : toSystemIndependentName(path2); return StringUtil.compare(path1, path2, !SystemInfo.isFileSystemCaseSensitive); } public static int fileHashCode(@Nullable File file) { return pathHashCode(file == null ? null : file.getPath()); } public static int pathHashCode(@Nullable String path) { return StringUtil.isEmpty(path) ? 0 : PATH_HASHING_STRATEGY.computeHashCode(toCanonicalPath(path)); } /** * @deprecated this method returns extension converted to lower case, this may not be correct for case-sensitive FS. * Use {@link FileUtilRt#getExtension(String)} instead to get the unchanged extension. * If you need to check whether a file has a specified extension use {@link FileUtilRt#extensionEquals(String, String)} */ @SuppressWarnings("StringToUpperCaseOrToLowerCaseWithoutLocale") @NotNull public static String getExtension(@NotNull String fileName) { return FileUtilRt.getExtension(fileName).toLowerCase(); } @NotNull public static String resolveShortWindowsName(@NotNull String path) throws IOException { return SystemInfo.isWindows && containsWindowsShortName(path) ? new File(path).getCanonicalPath() : path; } public static boolean containsWindowsShortName(@NotNull String path) { if (StringUtil.containsChar(path, '~')) { path = toSystemIndependentName(path); int start = 0; while (start < path.length()) { int end = path.indexOf('/', start); if (end < 0) end = path.length(); // "How Windows Generates 8.3 File Names from Long File Names", https://support.microsoft.com/en-us/kb/142982 int dot = path.lastIndexOf('.', end); if (dot < start) dot = end; if (dot - start > 2 && dot - start <= 8 && end - dot - 1 <= 3 && path.charAt(dot - 2) == '~' && Character.isDigit(path.charAt(dot - 1))) { return true; } start = end + 1; } } return false; } public static void collectMatchedFiles(@NotNull File root, @NotNull Pattern pattern, @NotNull List<File> outFiles) { collectMatchedFiles(root, root, pattern, outFiles); } private static void collectMatchedFiles(@NotNull File absoluteRoot, @NotNull File root, @NotNull Pattern pattern, @NotNull List<File> files) { final File[] dirs = root.listFiles(); if (dirs == null) return; for (File dir : dirs) { if (dir.isFile()) { final String relativePath = getRelativePath(absoluteRoot, dir); if (relativePath != null) { final String path = toSystemIndependentName(relativePath); if (pattern.matcher(path).matches()) { files.add(dir); } } } else { collectMatchedFiles(absoluteRoot, dir, pattern, files); } } } @RegExp @NotNull public static String convertAntToRegexp(@NotNull String antPattern) { return convertAntToRegexp(antPattern, true); } /** * @param antPattern ant-style path pattern * @return java regexp pattern. * Note that no matter whether forward or backward slashes were used in the antPattern * the returned regexp pattern will use forward slashes ('/') as file separators. * Paths containing windows-style backslashes must be converted before matching against the resulting regexp * @see FileUtil#toSystemIndependentName */ @RegExp @NotNull public static String convertAntToRegexp(@NotNull String antPattern, boolean ignoreStartingSlash) { final StringBuilder builder = new StringBuilder(); int asteriskCount = 0; boolean recursive = true; final int start = ignoreStartingSlash && (StringUtil.startsWithChar(antPattern, '/') || StringUtil.startsWithChar(antPattern, '\\')) ? 1 : 0; for (int idx = start; idx < antPattern.length(); idx++) { final char ch = antPattern.charAt(idx); if (ch == '*') { asteriskCount++; continue; } final boolean foundRecursivePattern = recursive && asteriskCount == 2 && (ch == '/' || ch == '\\'); final boolean asterisksFound = asteriskCount > 0; asteriskCount = 0; recursive = ch == '/' || ch == '\\'; if (foundRecursivePattern) { builder.append("(?:[^/]+/)*?"); continue; } if (asterisksFound) { builder.append("[^/]*?"); } if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '^' || ch == '$' || ch == '.' || ch == '{' || ch == '}' || ch == '+' || ch == '|') { // quote regexp-specific symbols builder.append('\\').append(ch); continue; } if (ch == '?') { builder.append("[^/]{1}"); continue; } if (ch == '\\') { builder.append('/'); continue; } builder.append(ch); } // handle ant shorthand: my_package/test/ is interpreted as if it were my_package/test/** final boolean isTrailingSlash = builder.length() > 0 && builder.charAt(builder.length() - 1) == '/'; if (asteriskCount == 0 && isTrailingSlash || recursive && asteriskCount == 2) { if (isTrailingSlash) { builder.setLength(builder.length() - 1); } if (builder.length() == 0) { builder.append(".*"); } else { builder.append("(?:$|/.+)"); } } else if (asteriskCount > 0) { builder.append("[^/]*?"); } return builder.toString(); } public static boolean moveDirWithContent(@NotNull File fromDir, @NotNull File toDir) { if (!toDir.exists()) return fromDir.renameTo(toDir); File[] files = fromDir.listFiles(); if (files == null) return false; boolean success = true; for (File fromFile : files) { File toFile = new File(toDir, fromFile.getName()); success = success && fromFile.renameTo(toFile); } //noinspection ResultOfMethodCallIgnored fromDir.delete(); return success; } @NotNull public static String sanitizeFileName(@NotNull String name) { return sanitizeFileName(name, true); } /** @deprecated use {@link #sanitizeFileName(String, boolean)} (to be removed in IDEA 17) */ @SuppressWarnings("unused") public static String sanitizeName(@NotNull String name) { return sanitizeFileName(name, false); } @NotNull public static String sanitizeFileName(@NotNull String name, boolean strict) { StringBuilder result = null; int last = 0; int length = name.length(); for (int i = 0; i < length; i++) { char c = name.charAt(i); boolean appendReplacement = true; if (c > 0 && c < 255) { if (strict ? Character.isLetterOrDigit(c) || c == '_' : Character.isJavaIdentifierPart(c) || c == ' ' || c == '@' || c == '-') { continue; } } else { appendReplacement = false; } if (result == null) { result = new StringBuilder(); } if (last < i) { result.append(name, last, i); } if (appendReplacement) { result.append('_'); } last = i + 1; } if (result == null) { return name; } if (last < length) { result.append(name, last, length); } return result.toString(); } public static boolean canExecute(@NotNull File file) { return file.canExecute(); } public static boolean canWrite(@NotNull String path) { FileAttributes attributes = FileSystemUtil.getAttributes(path); return attributes != null && attributes.isWritable(); } public static void setReadOnlyAttribute(@NotNull String path, boolean readOnlyFlag) { boolean writableFlag = !readOnlyFlag; if (!new File(path).setWritable(writableFlag, false) && canWrite(path) != writableFlag) { LOG.warn("Can't set writable attribute of '" + path + "' to '" + readOnlyFlag + "'"); } } public static void appendToFile(@NotNull File file, @NotNull String text) throws IOException { writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), true); } public static void writeToFile(@NotNull File file, @NotNull byte[] text) throws IOException { writeToFile(file, text, false); } public static void writeToFile(@NotNull File file, @NotNull String text) throws IOException { writeToFile(file, text, false); } public static void writeToFile(@NotNull File file, @NotNull String text, boolean append) throws IOException { writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), append); } public static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len) throws IOException { writeToFile(file, text, off, len, false); } public static void writeToFile(@NotNull File file, @NotNull byte[] text, boolean append) throws IOException { writeToFile(file, text, 0, text.length, append); } private static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len, boolean append) throws IOException { createParentDirs(file); OutputStream stream = new FileOutputStream(file, append); try { stream.write(text, off, len); } finally { stream.close(); } } public static boolean processFilesRecursively(@NotNull File root, @NotNull Processor<File> processor) { return processFilesRecursively(root, processor, null); } public static boolean processFilesRecursively(@NotNull File root, @NotNull Processor<File> processor, @Nullable final Processor<File> directoryFilter) { final LinkedList<File> queue = new LinkedList<File>(); queue.add(root); while (!queue.isEmpty()) { final File file = queue.removeFirst(); if (!processor.process(file)) return false; if (directoryFilter != null && (!file.isDirectory() || !directoryFilter.process(file))) continue; final File[] children = file.listFiles(); if (children != null) { ContainerUtil.addAll(queue, children); } } return true; } @Nullable public static File findFirstThatExist(@NotNull String... paths) { for (String path : paths) { if (!StringUtil.isEmptyOrSpaces(path)) { File file = new File(toSystemDependentName(path)); if (file.exists()) return file; } } return null; } @NotNull public static List<File> findFilesByMask(@NotNull Pattern pattern, @NotNull File dir) { final ArrayList<File> found = new ArrayList<File>(); final File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { found.addAll(findFilesByMask(pattern, file)); } else if (pattern.matcher(file.getName()).matches()) { found.add(file); } } } return found; } @NotNull public static List<File> findFilesOrDirsByMask(@NotNull Pattern pattern, @NotNull File dir) { final ArrayList<File> found = new ArrayList<File>(); final File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (pattern.matcher(file.getName()).matches()) { found.add(file); } if (file.isDirectory()) { found.addAll(findFilesOrDirsByMask(pattern, file)); } } } return found; } /** * Returns empty string for empty path. * First checks whether provided path is a path of a file with sought-for name. * Unless found, checks if provided file was a directory. In this case checks existence * of child files with given names in order "as provided". Finally checks filename among * brother-files of provided. Returns null if nothing found. * * @return path of the first of found files or empty string or null. */ @Nullable public static String findFileInProvidedPath(String providedPath, String... fileNames) { if (StringUtil.isEmpty(providedPath)) { return ""; } File providedFile = new File(providedPath); if (providedFile.exists() && ArrayUtil.indexOf(fileNames, providedFile.getName()) >= 0) { return toSystemDependentName(providedFile.getPath()); } if (providedFile.isDirectory()) { //user chose folder with file for (String fileName : fileNames) { File file = new File(providedFile, fileName); if (fileName.equals(file.getName()) && file.exists()) { return toSystemDependentName(file.getPath()); } } } providedFile = providedFile.getParentFile(); //users chose wrong file in same directory if (providedFile != null && providedFile.exists()) { for (String fileName : fileNames) { File file = new File(providedFile, fileName); if (fileName.equals(file.getName()) && file.exists()) { return toSystemDependentName(file.getPath()); } } } return null; } public static boolean isAbsolutePlatformIndependent(@NotNull String path) { return isUnixAbsolutePath(path) || isWindowsAbsolutePath(path); } public static boolean isUnixAbsolutePath(@NotNull String path) { return path.startsWith("/"); } public static boolean isWindowsAbsolutePath(@NotNull String pathString) { return pathString.length() >= 2 && Character.isLetter(pathString.charAt(0)) && pathString.charAt(1) == ':'; } @Contract("null -> null; !null -> !null") public static String getLocationRelativeToUserHome(@Nullable String path) { return getLocationRelativeToUserHome(path, true); } @Contract("null,_ -> null; !null,_ -> !null") public static String getLocationRelativeToUserHome(@Nullable String path, boolean unixOnly) { if (path == null) return null; if (SystemInfo.isUnix || !unixOnly) { File projectDir = new File(path); File userHomeDir = new File(SystemProperties.getUserHome()); if (isAncestor(userHomeDir, projectDir, true)) { return '~' + File.separator + getRelativePath(userHomeDir, projectDir); } } return path; } @NotNull public static String expandUserHome(@NotNull String path) { if (path.startsWith("~/") || path.startsWith("~\\")) { path = SystemProperties.getUserHome() + path.substring(1); } return path; } @NotNull public static File[] notNullize(@Nullable File[] files) { return notNullize(files, ArrayUtil.EMPTY_FILE_ARRAY); } @NotNull public static File[] notNullize(@Nullable File[] files, @NotNull File[] defaultFiles) { return files == null ? defaultFiles : files; } public static boolean isHashBangLine(CharSequence firstCharsIfText, String marker) { if (firstCharsIfText == null) { return false; } final int lineBreak = StringUtil.indexOf(firstCharsIfText, '\n'); if (lineBreak < 0) { return false; } String firstLine = firstCharsIfText.subSequence(0, lineBreak).toString(); return firstLine.startsWith("#!") && firstLine.contains(marker); } @NotNull public static File createTempDirectory(@NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempDirectory(prefix, suffix); } @NotNull public static File createTempDirectory(@NotNull String prefix, @Nullable String suffix, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempDirectory(prefix, suffix, deleteOnExit); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempDirectory(dir, prefix, suffix); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull String prefix, @Nullable String suffix, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempDirectory(dir, prefix, suffix, deleteOnExit); } @NotNull public static File createTempFile(@NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempFile(prefix, suffix); } @NotNull public static File createTempFile(@NotNull String prefix, @Nullable String suffix, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempFile(prefix, suffix, deleteOnExit); } @NotNull public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempFile(dir, prefix, suffix); } @NotNull public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix, boolean create) throws IOException { return FileUtilRt.createTempFile(dir, prefix, suffix, create); } @NotNull public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix, boolean create, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempFile(dir, prefix, suffix, create, deleteOnExit); } @NotNull public static String getTempDirectory() { return FileUtilRt.getTempDirectory(); } @TestOnly public static void resetCanonicalTempPathCache(final String tempPath) { FileUtilRt.resetCanonicalTempPathCache(tempPath); } @NotNull public static File generateRandomTemporaryPath() throws IOException { return FileUtilRt.generateRandomTemporaryPath(); } public static void setExecutableAttribute(@NotNull String path, boolean executableFlag) throws IOException { FileUtilRt.setExecutableAttribute(path, executableFlag); } public static void setLastModified(@NotNull File file, long timeStamp) throws IOException { if (!file.setLastModified(timeStamp)) { LOG.warn(file.getPath()); } } @NotNull public static String loadFile(@NotNull File file) throws IOException { return FileUtilRt.loadFile(file); } @NotNull public static String loadFile(@NotNull File file, boolean convertLineSeparators) throws IOException { return FileUtilRt.loadFile(file, convertLineSeparators); } @NotNull public static String loadFile(@NotNull File file, @Nullable String encoding) throws IOException { return FileUtilRt.loadFile(file, encoding); } @NotNull public static String loadFile(@NotNull File file, @NotNull Charset encoding) throws IOException { return String.valueOf(FileUtilRt.loadFileText(file, encoding)); } @NotNull public static String loadFile(@NotNull File file, @Nullable String encoding, boolean convertLineSeparators) throws IOException { return FileUtilRt.loadFile(file, encoding, convertLineSeparators); } @NotNull public static char[] loadFileText(@NotNull File file) throws IOException { return FileUtilRt.loadFileText(file); } @NotNull public static char[] loadFileText(@NotNull File file, @Nullable String encoding) throws IOException { return FileUtilRt.loadFileText(file, encoding); } @NotNull public static char[] loadText(@NotNull Reader reader, int length) throws IOException { return FileUtilRt.loadText(reader, length); } @NotNull public static List<String> loadLines(@NotNull File file) throws IOException { return FileUtilRt.loadLines(file); } @NotNull public static List<String> loadLines(@NotNull File file, @Nullable String encoding) throws IOException { return FileUtilRt.loadLines(file, encoding); } @NotNull public static List<String> loadLines(@NotNull String path) throws IOException { return FileUtilRt.loadLines(path); } @NotNull public static List<String> loadLines(@NotNull String path, @Nullable String encoding) throws IOException { return FileUtilRt.loadLines(path, encoding); } @NotNull public static List<String> loadLines(@NotNull BufferedReader reader) throws IOException { return FileUtilRt.loadLines(reader); } @NotNull public static byte[] loadBytes(@NotNull InputStream stream) throws IOException { return FileUtilRt.loadBytes(stream); } @NotNull public static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException { return FileUtilRt.loadBytes(stream, length); } @NotNull public static List<String> splitPath(@NotNull String path) { ArrayList<String> list = new ArrayList<String>(); int index = 0; int nextSeparator; while ((nextSeparator = path.indexOf(File.separatorChar, index)) != -1) { list.add(path.substring(index, nextSeparator)); index = nextSeparator + 1; } list.add(path.substring(index, path.length())); return list; } public static boolean isJarOrZip(@NotNull File file) { if (file.isDirectory()) { return false; } final String name = file.getName(); return StringUtil.endsWithIgnoreCase(name, ".jar") || StringUtil.endsWithIgnoreCase(name, ".zip"); } public static boolean visitFiles(@NotNull File root, @NotNull Processor<File> processor) { if (!processor.process(root)) { return false; } File[] children = root.listFiles(); if (children != null) { for (File child : children) { if (!visitFiles(child, processor)) { return false; } } } return true; } /** * Like {@link Properties#load(Reader)}, but preserves the order of key/value pairs. */ @NotNull public static Map<String, String> loadProperties(@NotNull Reader reader) throws IOException { final Map<String, String> map = ContainerUtil.newLinkedHashMap(); new Properties() { @Override public synchronized Object put(Object key, Object value) { map.put(String.valueOf(key), String.valueOf(value)); //noinspection UseOfPropertiesAsHashtable return super.put(key, value); } }.load(reader); return map; } public static boolean isRootPath(@NotNull File file) { return isRootPath(file.getPath()); } public static boolean isRootPath(@NotNull String path) { return path.equals("/") || path.matches("[a-zA-Z]:[/\\\\]"); } public static boolean deleteWithRenaming(File file) { File tempFileNameForDeletion = findSequentNonexistentFile(file.getParentFile(), file.getName(), ""); boolean success = file.renameTo(tempFileNameForDeletion); return delete(success ? tempFileNameForDeletion:file); } public static boolean isFileSystemCaseSensitive(@NotNull String path) throws FileNotFoundException { FileAttributes attributes = FileSystemUtil.getAttributes(path); if (attributes == null) { throw new FileNotFoundException(path); } FileAttributes upper = FileSystemUtil.getAttributes(path.toUpperCase(Locale.ENGLISH)); FileAttributes lower = FileSystemUtil.getAttributes(path.toLowerCase(Locale.ENGLISH)); return !(attributes.equals(upper) && attributes.equals(lower)); } }
platform/util/src/com/intellij/openapi/util/io/FileUtil.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.util.io; import com.intellij.CommonBundle; import com.intellij.Patches; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.*; import com.intellij.util.concurrency.FixedFuture; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.io.URLUtil; import com.intellij.util.text.FilePathHashingStrategy; import com.intellij.util.text.StringFactory; import gnu.trove.TObjectHashingStrategy; import org.intellij.lang.annotations.RegExp; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.*; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.RunnableFuture; import java.util.regex.Pattern; @SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"}) public class FileUtil extends FileUtilRt { static { if (!Patches.USE_REFLECTION_TO_ACCESS_JDK7) throw new RuntimeException("Please migrate FileUtilRt to JDK8"); } public static final String ASYNC_DELETE_EXTENSION = ".__del__"; public static final int REGEX_PATTERN_FLAGS = SystemInfo.isFileSystemCaseSensitive ? 0 : Pattern.CASE_INSENSITIVE; public static final TObjectHashingStrategy<String> PATH_HASHING_STRATEGY = FilePathHashingStrategy.create(); public static final TObjectHashingStrategy<File> FILE_HASHING_STRATEGY = SystemInfo.isFileSystemCaseSensitive ? ContainerUtil.<File>canonicalStrategy() : new TObjectHashingStrategy<File>() { @Override public int computeHashCode(File object) { return fileHashCode(object); } @Override public boolean equals(File o1, File o2) { return filesEqual(o1, o2); } }; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil"); @NotNull public static String join(@NotNull final String... parts) { return StringUtil.join(parts, File.separator); } @Nullable public static String getRelativePath(File base, File file) { return FileUtilRt.getRelativePath(base, file); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) { return FileUtilRt.getRelativePath(basePath, filePath, separator); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator, final boolean caseSensitive) { return FileUtilRt.getRelativePath(basePath, filePath, separator, caseSensitive); } public static boolean isAbsolute(@NotNull String path) { return new File(path).isAbsolute(); } /** * Check if the {@code ancestor} is an ancestor of {@code file}. * * @param ancestor supposed ancestor. * @param file supposed descendant. * @param strict if {@code false} then this method returns {@code true} if {@code ancestor} equals to {@code file}. * @return {@code true} if {@code ancestor} is parent of {@code file}; {@code false} otherwise. */ public static boolean isAncestor(@NotNull File ancestor, @NotNull File file, boolean strict) { return isAncestor(ancestor.getPath(), file.getPath(), strict); } public static boolean isAncestor(@NotNull String ancestor, @NotNull String file, boolean strict) { return !ThreeState.NO.equals(isAncestorThreeState(ancestor, file, strict)); } /** * Checks if the {@code ancestor} is an ancestor of the {@code file}, and if it is an immediate parent or not. * * @param ancestor supposed ancestor. * @param file supposed descendant. * @param strict if {@code false}, the file can be ancestor of itself, * i.e. the method returns {@code ThreeState.YES} if {@code ancestor} equals to {@code file}. * * @return {@code ThreeState.YES} if ancestor is an immediate parent of the file, * {@code ThreeState.UNSURE} if ancestor is not immediate parent of the file, * {@code ThreeState.NO} if ancestor is not a parent of the file at all. */ @NotNull public static ThreeState isAncestorThreeState(@NotNull String ancestor, @NotNull String file, boolean strict) { String ancestorPath = toCanonicalPath(ancestor); String filePath = toCanonicalPath(file); return startsWith(filePath, ancestorPath, strict, SystemInfo.isFileSystemCaseSensitive, true); } public static boolean startsWith(@NotNull String path, @NotNull String start) { return !ThreeState.NO.equals(startsWith(path, start, false, SystemInfo.isFileSystemCaseSensitive, false)); } public static boolean startsWith(@NotNull String path, @NotNull String start, boolean caseSensitive) { return !ThreeState.NO.equals(startsWith(path, start, false, caseSensitive, false)); } @NotNull private static ThreeState startsWith(@NotNull String path, @NotNull String prefix, boolean strict, boolean caseSensitive, boolean checkImmediateParent) { final int pathLength = path.length(); final int prefixLength = prefix.length(); if (prefixLength == 0) return pathLength == 0 ? ThreeState.YES : ThreeState.UNSURE; if (prefixLength > pathLength) return ThreeState.NO; if (!path.regionMatches(!caseSensitive, 0, prefix, 0, prefixLength)) return ThreeState.NO; if (pathLength == prefixLength) { return strict ? ThreeState.NO : ThreeState.YES; } char lastPrefixChar = prefix.charAt(prefixLength - 1); int slashOrSeparatorIdx = prefixLength; if (lastPrefixChar == '/' || lastPrefixChar == File.separatorChar) { slashOrSeparatorIdx = prefixLength - 1; } char next1 = path.charAt(slashOrSeparatorIdx); if (next1 == '/' || next1 == File.separatorChar) { if (!checkImmediateParent) return ThreeState.YES; if (slashOrSeparatorIdx == pathLength - 1) return ThreeState.YES; int idxNext = path.indexOf(next1, slashOrSeparatorIdx + 1); idxNext = idxNext == -1 ? path.indexOf(next1 == '/' ? '\\' : '/', slashOrSeparatorIdx + 1) : idxNext; return idxNext == -1 ? ThreeState.YES : ThreeState.UNSURE; } else { return ThreeState.NO; } } /** * @param removeProcessor parent, child */ public static <T> Collection<T> removeAncestors(final Collection<T> files, final Convertor<T, String> convertor, final PairProcessor<T, T> removeProcessor) { if (files.isEmpty()) return files; final TreeMap<String, T> paths = new TreeMap<String, T>(); for (T file : files) { final String path = convertor.convert(file); assert path != null; final String canonicalPath = toCanonicalPath(path); paths.put(canonicalPath, file); } final List<Map.Entry<String, T>> ordered = new ArrayList<Map.Entry<String, T>>(paths.entrySet()); final List<T> result = new ArrayList<T>(ordered.size()); result.add(ordered.get(0).getValue()); for (int i = 1; i < ordered.size(); i++) { final Map.Entry<String, T> entry = ordered.get(i); final String child = entry.getKey(); boolean parentNotFound = true; for (int j = i - 1; j >= 0; j--) { // possible parents final String parent = ordered.get(j).getKey(); if (parent == null) continue; if (startsWith(child, parent) && removeProcessor.process(ordered.get(j).getValue(), entry.getValue())) { parentNotFound = false; break; } } if (parentNotFound) { result.add(entry.getValue()); } } return result; } @Nullable public static File getParentFile(@NotNull File file) { return FileUtilRt.getParentFile(file); } @NotNull public static byte[] loadFileBytes(@NotNull File file) throws IOException { byte[] bytes; final InputStream stream = new FileInputStream(file); try { final long len = file.length(); if (len < 0) { throw new IOException("File length reported negative, probably doesn't exist"); } if (isTooLarge(len)) { throw new FileTooBigException("Attempt to load '" + file + "' in memory buffer, file length is " + len + " bytes."); } bytes = loadBytes(stream, (int)len); } finally { stream.close(); } return bytes; } @NotNull public static byte[] loadFirst(@NotNull InputStream stream, int maxLength) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); copy(stream, maxLength, buffer); buffer.close(); return buffer.toByteArray(); } @NotNull public static String loadTextAndClose(@NotNull InputStream stream) throws IOException { //noinspection IOResourceOpenedButNotSafelyClosed return loadTextAndClose(new InputStreamReader(stream)); } @NotNull public static String loadTextAndClose(@NotNull Reader reader) throws IOException { try { return StringFactory.createShared(adaptiveLoadText(reader)); } finally { reader.close(); } } @NotNull public static char[] adaptiveLoadText(@NotNull Reader reader) throws IOException { char[] chars = new char[4096]; List<char[]> buffers = null; int count = 0; int total = 0; while (true) { int n = reader.read(chars, count, chars.length - count); if (n <= 0) break; count += n; if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + reader); total += n; if (count == chars.length) { if (buffers == null) { buffers = new ArrayList<char[]>(); } buffers.add(chars); int newLength = Math.min(1024 * 1024, chars.length * 2); chars = new char[newLength]; count = 0; } } char[] result = new char[total]; if (buffers != null) { for (char[] buffer : buffers) { System.arraycopy(buffer, 0, result, result.length - total, buffer.length); total -= buffer.length; } } System.arraycopy(chars, 0, result, result.length - total, total); return result; } @NotNull public static byte[] adaptiveLoadBytes(@NotNull InputStream stream) throws IOException { byte[] bytes = getThreadLocalBuffer(); List<byte[]> buffers = null; int count = 0; int total = 0; while (true) { int n = stream.read(bytes, count, bytes.length - count); if (n <= 0) break; count += n; if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + stream); total += n; if (count == bytes.length) { if (buffers == null) { buffers = new ArrayList<byte[]>(); } buffers.add(bytes); int newLength = Math.min(1024 * 1024, bytes.length * 2); bytes = new byte[newLength]; count = 0; } } byte[] result = new byte[total]; if (buffers != null) { for (byte[] buffer : buffers) { System.arraycopy(buffer, 0, result, result.length - total, buffer.length); total -= buffer.length; } } System.arraycopy(bytes, 0, result, result.length - total, total); return result; } @NotNull public static Future<Void> asyncDelete(@NotNull File file) { return asyncDelete(Collections.singleton(file)); } @NotNull public static Future<Void> asyncDelete(@NotNull Collection<File> files) { List<File> tempFiles = new ArrayList<File>(); for (File file : files) { final File tempFile = renameToTempFileOrDelete(file); if (tempFile != null) { tempFiles.add(tempFile); } } if (!tempFiles.isEmpty()) { return startDeletionThread(tempFiles.toArray(new File[tempFiles.size()])); } return new FixedFuture<Void>(null); } private static Future<Void> startDeletionThread(@NotNull final File... tempFiles) { final RunnableFuture<Void> deleteFilesTask = new FutureTask<Void>(new Runnable() { @Override public void run() { final Thread currentThread = Thread.currentThread(); final int priority = currentThread.getPriority(); currentThread.setPriority(Thread.MIN_PRIORITY); try { for (File tempFile : tempFiles) { delete(tempFile); } } finally { currentThread.setPriority(priority); } } }, null); try { // attempt to execute on pooled thread final Class<?> aClass = Class.forName("com.intellij.openapi.application.ApplicationManager"); final Method getApplicationMethod = aClass.getMethod("getApplication"); final Object application = getApplicationMethod.invoke(null); final Method executeOnPooledThreadMethod = application.getClass().getMethod("executeOnPooledThread", Runnable.class); executeOnPooledThreadMethod.invoke(application, deleteFilesTask); } catch (Exception ignored) { new Thread(deleteFilesTask, "File deletion thread").start(); } return deleteFilesTask; } @Nullable private static File renameToTempFileOrDelete(@NotNull File file) { String tempDir = getTempDirectory(); boolean isSameDrive = true; if (SystemInfo.isWindows) { String tempDirDrive = tempDir.substring(0, 2); String fileDrive = file.getAbsolutePath().substring(0, 2); isSameDrive = tempDirDrive.equalsIgnoreCase(fileDrive); } if (isSameDrive) { // the optimization is reasonable only if destination dir is located on the same drive final String originalFileName = file.getName(); File tempFile = getTempFile(originalFileName, tempDir); if (file.renameTo(tempFile)) { return tempFile; } } delete(file); return null; } private static File getTempFile(@NotNull String originalFileName, @NotNull String parent) { int randomSuffix = (int)(System.currentTimeMillis() % 1000); for (int i = randomSuffix; ; i++) { String name = "___" + originalFileName + i + ASYNC_DELETE_EXTENSION; File tempFile = new File(parent, name); if (!tempFile.exists()) return tempFile; } } public static boolean delete(@NotNull File file) { if (NIOReflect.IS_AVAILABLE) { return deleteRecursivelyNIO(file); } return deleteRecursively(file); } private static boolean deleteRecursively(@NotNull File file) { FileAttributes attributes = FileSystemUtil.getAttributes(file); if (attributes == null) return true; if (attributes.isDirectory() && !attributes.isSymLink()) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { if (!deleteRecursively(child)) return false; } } } return deleteFile(file); } public static boolean createParentDirs(@NotNull File file) { return FileUtilRt.createParentDirs(file); } public static boolean createDirectory(@NotNull File path) { return FileUtilRt.createDirectory(path); } public static boolean createIfDoesntExist(@NotNull File file) { return FileUtilRt.createIfNotExists(file); } public static boolean ensureCanCreateFile(@NotNull File file) { return FileUtilRt.ensureCanCreateFile(file); } public static void copy(@NotNull File fromFile, @NotNull File toFile) throws IOException { performCopy(fromFile, toFile, true); } public static void copyContent(@NotNull File fromFile, @NotNull File toFile) throws IOException { performCopy(fromFile, toFile, false); } @SuppressWarnings("Duplicates") private static void performCopy(@NotNull File fromFile, @NotNull File toFile, final boolean syncTimestamp) throws IOException { final FileOutputStream fos; try { fos = openOutputStream(toFile); } catch (IOException e) { if (SystemInfo.isWindows && e.getMessage() != null && e.getMessage().contains("denied") && WinUACTemporaryFix.nativeCopy(fromFile, toFile, syncTimestamp)) { return; } throw e; } try { final FileInputStream fis = new FileInputStream(fromFile); try { copy(fis, fos); } finally { fis.close(); } } finally { fos.close(); } if (syncTimestamp) { final long timeStamp = fromFile.lastModified(); if (timeStamp < 0) { LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'"); } else if (!toFile.setLastModified(timeStamp)) { LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'"); } } if (SystemInfo.isUnix && fromFile.canExecute()) { FileSystemUtil.clonePermissionsToExecute(fromFile.getPath(), toFile.getPath()); } } private static FileOutputStream openOutputStream(@NotNull final File file) throws IOException { try { return new FileOutputStream(file); } catch (FileNotFoundException e) { final File parentFile = file.getParentFile(); if (parentFile == null) { throw new IOException("Parent file is null for " + file.getPath(), e); } createParentDirs(file); return new FileOutputStream(file); } } public static void copy(@NotNull InputStream inputStream, @NotNull OutputStream outputStream) throws IOException { FileUtilRt.copy(inputStream, outputStream); } public static void copy(@NotNull InputStream inputStream, int maxSize, @NotNull OutputStream outputStream) throws IOException { final byte[] buffer = getThreadLocalBuffer(); int toRead = maxSize; while (toRead > 0) { int read = inputStream.read(buffer, 0, Math.min(buffer.length, toRead)); if (read < 0) break; toRead -= read; outputStream.write(buffer, 0, read); } } public static void copyFileOrDir(@NotNull File from, @NotNull File to) throws IOException { copyFileOrDir(from, to, from.isDirectory()); } public static void copyFileOrDir(@NotNull File from, @NotNull File to, boolean isDir) throws IOException { if (isDir) { copyDir(from, to); } else { copy(from, to); } } public static void copyDir(@NotNull File fromDir, @NotNull File toDir) throws IOException { copyDir(fromDir, toDir, true); } /** * Copies content of {@code fromDir} to {@code toDir}. * It's equivalent to "cp -r fromDir/* toDir" unix command. * * @param fromDir source directory * @param toDir destination directory * @throws IOException in case of any IO troubles */ public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException { File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY); for (File child : children) { copyFileOrDir(child, new File(toDir, child.getName())); } } public static void copyDir(@NotNull File fromDir, @NotNull File toDir, boolean copySystemFiles) throws IOException { copyDir(fromDir, toDir, copySystemFiles ? null : new FileFilter() { @Override public boolean accept(@NotNull File file) { return !StringUtil.startsWithChar(file.getName(), '.'); } }); } public static void copyDir(@NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter) throws IOException { ensureExists(toDir); if (isAncestor(fromDir, toDir, true)) { LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself."); return; } File[] files = fromDir.listFiles(); if (files == null) throw new IOException(CommonBundle.message("exception.directory.is.invalid", fromDir.getPath())); if (!fromDir.canRead()) throw new IOException(CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath())); for (File file : files) { if (filter != null && !filter.accept(file)) { continue; } if (file.isDirectory()) { copyDir(file, new File(toDir, file.getName()), filter); } else { copy(file, new File(toDir, file.getName())); } } } public static void ensureExists(@NotNull File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException(CommonBundle.message("exception.directory.can.not.create", dir.getPath())); } } @NotNull public static String getNameWithoutExtension(@NotNull File file) { return getNameWithoutExtension(file.getName()); } @NotNull public static String getNameWithoutExtension(@NotNull String name) { return FileUtilRt.getNameWithoutExtension(name); } public static String createSequentFileName(@NotNull File aParentFolder, @NotNull String aFilePrefix, @NotNull String aExtension) { return findSequentNonexistentFile(aParentFolder, aFilePrefix, aExtension).getName(); } public static File findSequentNonexistentFile(@NotNull File parentFolder, @NotNull String filePrefix, @NotNull String extension) { int postfix = 0; String ext = extension.isEmpty() ? "" : '.' + extension; File candidate = new File(parentFolder, filePrefix + ext); while (candidate.exists()) { postfix++; candidate = new File(parentFolder, filePrefix + Integer.toString(postfix) + ext); } return candidate; } @NotNull public static String toSystemDependentName(@NotNull String aFileName) { return FileUtilRt.toSystemDependentName(aFileName); } @NotNull public static String toSystemIndependentName(@NotNull String aFileName) { return FileUtilRt.toSystemIndependentName(aFileName); } /** @deprecated to be removed in IDEA 17 */ @SuppressWarnings({"unused", "StringToUpperCaseOrToLowerCaseWithoutLocale"}) public static String nameToCompare(@NotNull String name) { return (SystemInfo.isFileSystemCaseSensitive ? name : name.toLowerCase()).replace('\\', '/'); } /** * Converts given path to canonical representation by eliminating '.'s, traversing '..'s, and omitting duplicate separators. * Please note that this method is symlink-unfriendly (i.e. result of "/path/to/link/../next" most probably will differ from * what {@link File#getCanonicalPath()} will return) - so use with care.<br> * <br> * If the path may contain symlinks, use {@link FileUtil#toCanonicalPath(String, boolean)} instead. */ @Contract("null -> null") public static String toCanonicalPath(@Nullable String path) { return toCanonicalPath(path, File.separatorChar, true); } /** * When relative ../ parts do not escape outside of symlinks, the links are not expanded.<br> * That is, in the best-case scenario the original non-expanded path is preserved.<br> * <br> * Otherwise, returns a fully resolved path using {@link File#getCanonicalPath()}.<br> * <br> * Consider the following case: * <pre> * root/ * dir1/ * link_to_dir1 * dir2/ * </pre> * 'root/dir1/link_to_dir1/../dir2' should be resolved to 'root/dir2' */ @Contract("null, _ -> null") public static String toCanonicalPath(@Nullable String path, boolean resolveSymlinksIfNecessary) { return toCanonicalPath(path, File.separatorChar, true, resolveSymlinksIfNecessary); } @Contract("null, _ -> null") public static String toCanonicalPath(@Nullable String path, char separatorChar) { return toCanonicalPath(path, separatorChar, true); } @Contract("null -> null") public static String toCanonicalUriPath(@Nullable String path) { return toCanonicalPath(path, '/', false); } @Contract("null, _, _ -> null") private static String toCanonicalPath(@Nullable String path, char separatorChar, boolean removeLastSlash) { return toCanonicalPath(path, separatorChar, removeLastSlash, false); } @Contract("null, _, _, _ -> null") private static String toCanonicalPath(@Nullable String path, final char separatorChar, final boolean removeLastSlash, final boolean resolveSymlinks) { if (path == null || path.isEmpty()) { return path; } if (StringUtil.startsWithChar(path, '.')) { if (path.length() == 1) { return ""; } char c = path.charAt(1); if (c == '/' || c == separatorChar) { path = path.substring(2); } } path = path.replace(separatorChar, '/'); // trying to speedup the common case when there are no "//" or "/." int index = -1; do { index = path.indexOf('/', index+1); char next = index == path.length() - 1 ? 0 : path.charAt(index + 1); if (next == '.' || next == '/') { break; } } while (index != -1); if (index == -1) { if (removeLastSlash) { int start = processRoot(path, NullAppendable.INSTANCE); int slashIndex = path.lastIndexOf('/'); return slashIndex != -1 && slashIndex > start ? StringUtil.trimEnd(path, '/') : path; } return path; } final String finalPath = path; NotNullProducer<String> realCanonicalPath = resolveSymlinks ? new NotNullProducer<String>() { @NotNull @Override public String produce() { try { return new File(finalPath).getCanonicalPath().replace(separatorChar, '/'); } catch (IOException ignore) { // fall back to the default behavior return toCanonicalPath(finalPath, separatorChar, removeLastSlash, false); } } } : null; StringBuilder result = new StringBuilder(path.length()); int start = processRoot(path, result); int dots = 0; boolean separator = true; for (int i = start; i < path.length(); ++i) { char c = path.charAt(i); if (c == '/') { if (!separator) { if (!processDots(result, dots, start, resolveSymlinks)) { return realCanonicalPath.produce(); } dots = 0; } separator = true; } else if (c == '.') { if (separator || dots > 0) { ++dots; } else { result.append('.'); } separator = false; } else { if (dots > 0) { StringUtil.repeatSymbol(result, '.', dots); dots = 0; } result.append(c); separator = false; } } if (dots > 0) { if (!processDots(result, dots, start, resolveSymlinks)) { return realCanonicalPath.produce(); } } int lastChar = result.length() - 1; if (removeLastSlash && lastChar >= 0 && result.charAt(lastChar) == '/' && lastChar > start) { result.deleteCharAt(lastChar); } return result.toString(); } private static int processRoot(@NotNull String path, @NotNull Appendable result) { try { if (SystemInfo.isWindows && path.length() > 1 && path.charAt(0) == '/' && path.charAt(1) == '/') { result.append("//"); int hostStart = 2; while (hostStart < path.length() && path.charAt(hostStart) == '/') hostStart++; if (hostStart == path.length()) return hostStart; int hostEnd = path.indexOf('/', hostStart); if (hostEnd < 0) hostEnd = path.length(); result.append(path, hostStart, hostEnd); result.append('/'); int shareStart = hostEnd; while (shareStart < path.length() && path.charAt(shareStart) == '/') shareStart++; if (shareStart == path.length()) return shareStart; int shareEnd = path.indexOf('/', shareStart); if (shareEnd < 0) shareEnd = path.length(); result.append(path, shareStart, shareEnd); result.append('/'); return shareEnd; } if (!path.isEmpty() && path.charAt(0) == '/') { result.append('/'); return 1; } if (path.length() > 2 && path.charAt(1) == ':' && path.charAt(2) == '/') { result.append(path, 0, 3); return 3; } } catch (IOException e) { throw new RuntimeException(e); } return 0; } @Contract("_, _, _, false -> true") private static boolean processDots(@NotNull StringBuilder result, int dots, int start, boolean resolveSymlinks) { if (dots == 2) { int pos = -1; if (!StringUtil.endsWith(result, "/../") && !StringUtil.equals(result, "../")) { pos = StringUtil.lastIndexOf(result, '/', start, result.length() - 1); if (pos >= 0) { ++pos; // separator found, trim to next char } else if (start > 0) { pos = start; // path is absolute, trim to root ('/..' -> '/') } else if (result.length() > 0) { pos = 0; // path is relative, trim to default ('a/..' -> '') } } if (pos >= 0) { if (resolveSymlinks && FileSystemUtil.isSymLink(new File(result.toString()))) { return false; } result.delete(pos, result.length()); } else { result.append("../"); // impossible to traverse, keep as-is } } else if (dots != 1) { StringUtil.repeatSymbol(result, '.', dots); result.append('/'); } return true; } /** * converts back slashes to forward slashes * removes double slashes inside the path, e.g. "x/y//z" => "x/y/z" */ @NotNull public static String normalize(@NotNull String path) { int start = 0; boolean separator = false; if (SystemInfo.isWindows) { if (path.startsWith("//")) { start = 2; separator = true; } else if (path.startsWith("\\\\")) { return normalizeTail(0, path, false); } } for (int i = start; i < path.length(); ++i) { final char c = path.charAt(i); if (c == '/') { if (separator) { return normalizeTail(i, path, true); } separator = true; } else if (c == '\\') { return normalizeTail(i, path, separator); } else { separator = false; } } return path; } @NotNull private static String normalizeTail(int prefixEnd, @NotNull String path, boolean separator) { final StringBuilder result = new StringBuilder(path.length()); result.append(path, 0, prefixEnd); int start = prefixEnd; if (start==0 && SystemInfo.isWindows && (path.startsWith("//") || path.startsWith("\\\\"))) { start = 2; result.append("//"); separator = true; } for (int i = start; i < path.length(); ++i) { final char c = path.charAt(i); if (c == '/' || c == '\\') { if (!separator) result.append('/'); separator = true; } else { result.append(c); separator = false; } } return result.toString(); } @NotNull public static String unquote(@NotNull String urlString) { urlString = urlString.replace('/', File.separatorChar); return URLUtil.unescapePercentSequences(urlString); } public static boolean isFilePathAcceptable(@NotNull File root, @Nullable FileFilter fileFilter) { if (fileFilter == null) return true; File file = root; do { if (!fileFilter.accept(file)) return false; file = file.getParentFile(); } while (file != null); return true; } public static boolean rename(@NotNull File source, @NotNull String newName) throws IOException { File target = new File(source.getParent(), newName); if (!SystemInfo.isFileSystemCaseSensitive && newName.equalsIgnoreCase(source.getName())) { File intermediate = createTempFile(source.getParentFile(), source.getName(), ".tmp", false, false); return source.renameTo(intermediate) && intermediate.renameTo(target); } else { return source.renameTo(target); } } public static void rename(@NotNull File source, @NotNull File target) throws IOException { if (source.renameTo(target)) return; if (!source.exists()) return; copy(source, target); delete(source); } public static boolean filesEqual(@Nullable File file1, @Nullable File file2) { // on MacOS java.io.File.equals() is incorrectly case-sensitive return pathsEqual(file1 == null ? null : file1.getPath(), file2 == null ? null : file2.getPath()); } public static boolean pathsEqual(@Nullable String path1, @Nullable String path2) { if (path1 == path2) return true; if (path1 == null || path2 == null) return false; path1 = toCanonicalPath(path1); path2 = toCanonicalPath(path2); return PATH_HASHING_STRATEGY.equals(path1, path2); } /** * optimized version of pathsEqual - it only compares pure names, without file separators */ public static boolean namesEqual(@Nullable String name1, @Nullable String name2) { if (name1 == name2) return true; if (name1 == null || name2 == null) return false; return PATH_HASHING_STRATEGY.equals(name1, name2); } public static int compareFiles(@Nullable File file1, @Nullable File file2) { return comparePaths(file1 == null ? null : file1.getPath(), file2 == null ? null : file2.getPath()); } public static int comparePaths(@Nullable String path1, @Nullable String path2) { path1 = path1 == null ? null : toSystemIndependentName(path1); path2 = path2 == null ? null : toSystemIndependentName(path2); return StringUtil.compare(path1, path2, !SystemInfo.isFileSystemCaseSensitive); } public static int fileHashCode(@Nullable File file) { return pathHashCode(file == null ? null : file.getPath()); } public static int pathHashCode(@Nullable String path) { return StringUtil.isEmpty(path) ? 0 : PATH_HASHING_STRATEGY.computeHashCode(toCanonicalPath(path)); } /** * @deprecated this method returns extension converted to lower case, this may not be correct for case-sensitive FS. * Use {@link FileUtilRt#getExtension(String)} instead to get the unchanged extension. * If you need to check whether a file has a specified extension use {@link FileUtilRt#extensionEquals(String, String)} */ @SuppressWarnings("StringToUpperCaseOrToLowerCaseWithoutLocale") @NotNull public static String getExtension(@NotNull String fileName) { return FileUtilRt.getExtension(fileName).toLowerCase(); } @NotNull public static String resolveShortWindowsName(@NotNull String path) throws IOException { return SystemInfo.isWindows && containsWindowsShortName(path) ? new File(path).getCanonicalPath() : path; } public static boolean containsWindowsShortName(@NotNull String path) { if (StringUtil.containsChar(path, '~')) { path = toSystemIndependentName(path); int start = 0; while (start < path.length()) { int end = path.indexOf('/', start); if (end < 0) end = path.length(); // "How Windows Generates 8.3 File Names from Long File Names", https://support.microsoft.com/en-us/kb/142982 int dot = path.lastIndexOf('.', end); if (dot < start) dot = end; if (dot - start > 2 && dot - start <= 8 && end - dot - 1 <= 3 && path.charAt(dot - 2) == '~' && Character.isDigit(path.charAt(dot - 1))) { return true; } start = end + 1; } } return false; } public static void collectMatchedFiles(@NotNull File root, @NotNull Pattern pattern, @NotNull List<File> outFiles) { collectMatchedFiles(root, root, pattern, outFiles); } private static void collectMatchedFiles(@NotNull File absoluteRoot, @NotNull File root, @NotNull Pattern pattern, @NotNull List<File> files) { final File[] dirs = root.listFiles(); if (dirs == null) return; for (File dir : dirs) { if (dir.isFile()) { final String relativePath = getRelativePath(absoluteRoot, dir); if (relativePath != null) { final String path = toSystemIndependentName(relativePath); if (pattern.matcher(path).matches()) { files.add(dir); } } } else { collectMatchedFiles(absoluteRoot, dir, pattern, files); } } } @RegExp @NotNull public static String convertAntToRegexp(@NotNull String antPattern) { return convertAntToRegexp(antPattern, true); } /** * @param antPattern ant-style path pattern * @return java regexp pattern. * Note that no matter whether forward or backward slashes were used in the antPattern * the returned regexp pattern will use forward slashes ('/') as file separators. * Paths containing windows-style backslashes must be converted before matching against the resulting regexp * @see FileUtil#toSystemIndependentName */ @RegExp @NotNull public static String convertAntToRegexp(@NotNull String antPattern, boolean ignoreStartingSlash) { final StringBuilder builder = new StringBuilder(); int asteriskCount = 0; boolean recursive = true; final int start = ignoreStartingSlash && (StringUtil.startsWithChar(antPattern, '/') || StringUtil.startsWithChar(antPattern, '\\')) ? 1 : 0; for (int idx = start; idx < antPattern.length(); idx++) { final char ch = antPattern.charAt(idx); if (ch == '*') { asteriskCount++; continue; } final boolean foundRecursivePattern = recursive && asteriskCount == 2 && (ch == '/' || ch == '\\'); final boolean asterisksFound = asteriskCount > 0; asteriskCount = 0; recursive = ch == '/' || ch == '\\'; if (foundRecursivePattern) { builder.append("(?:[^/]+/)*?"); continue; } if (asterisksFound) { builder.append("[^/]*?"); } if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '^' || ch == '$' || ch == '.' || ch == '{' || ch == '}' || ch == '+' || ch == '|') { // quote regexp-specific symbols builder.append('\\').append(ch); continue; } if (ch == '?') { builder.append("[^/]{1}"); continue; } if (ch == '\\') { builder.append('/'); continue; } builder.append(ch); } // handle ant shorthand: my_package/test/ is interpreted as if it were my_package/test/** final boolean isTrailingSlash = builder.length() > 0 && builder.charAt(builder.length() - 1) == '/'; if (asteriskCount == 0 && isTrailingSlash || recursive && asteriskCount == 2) { if (isTrailingSlash) { builder.setLength(builder.length() - 1); } if (builder.length() == 0) { builder.append(".*"); } else { builder.append("(?:$|/.+)"); } } else if (asteriskCount > 0) { builder.append("[^/]*?"); } return builder.toString(); } public static boolean moveDirWithContent(@NotNull File fromDir, @NotNull File toDir) { if (!toDir.exists()) return fromDir.renameTo(toDir); File[] files = fromDir.listFiles(); if (files == null) return false; boolean success = true; for (File fromFile : files) { File toFile = new File(toDir, fromFile.getName()); success = success && fromFile.renameTo(toFile); } //noinspection ResultOfMethodCallIgnored fromDir.delete(); return success; } @NotNull public static String sanitizeFileName(@NotNull String name) { return sanitizeFileName(name, true); } /** @deprecated use {@link #sanitizeFileName(String, boolean)} (to be removed in IDEA 17) */ @SuppressWarnings("unused") public static String sanitizeName(@NotNull String name) { return sanitizeFileName(name, false); } @NotNull public static String sanitizeFileName(@NotNull String name, boolean strict) { StringBuilder result = null; int last = 0; int length = name.length(); for (int i = 0; i < length; i++) { char c = name.charAt(i); boolean appendReplacement = true; if (c > 0 && c < 255) { if (strict ? Character.isLetterOrDigit(c) || c == '_' : Character.isJavaIdentifierPart(c) || c == ' ' || c == '@' || c == '-') { continue; } } else { appendReplacement = false; } if (result == null) { result = new StringBuilder(); } if (last < i) { result.append(name, last, i); } if (appendReplacement) { result.append('_'); } last = i + 1; } if (result == null) { return name; } if (last < length) { result.append(name, last, length); } return result.toString(); } public static boolean canExecute(@NotNull File file) { return file.canExecute(); } public static boolean canWrite(@NotNull String path) { FileAttributes attributes = FileSystemUtil.getAttributes(path); return attributes != null && attributes.isWritable(); } public static void setReadOnlyAttribute(@NotNull String path, boolean readOnlyFlag) { boolean writableFlag = !readOnlyFlag; if (!new File(path).setWritable(writableFlag, false) && canWrite(path) != writableFlag) { LOG.warn("Can't set writable attribute of '" + path + "' to '" + readOnlyFlag + "'"); } } public static void appendToFile(@NotNull File file, @NotNull String text) throws IOException { writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), true); } public static void writeToFile(@NotNull File file, @NotNull byte[] text) throws IOException { writeToFile(file, text, false); } public static void writeToFile(@NotNull File file, @NotNull String text) throws IOException { writeToFile(file, text, false); } public static void writeToFile(@NotNull File file, @NotNull String text, boolean append) throws IOException { writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), append); } public static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len) throws IOException { writeToFile(file, text, off, len, false); } public static void writeToFile(@NotNull File file, @NotNull byte[] text, boolean append) throws IOException { writeToFile(file, text, 0, text.length, append); } private static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len, boolean append) throws IOException { createParentDirs(file); OutputStream stream = new FileOutputStream(file, append); try { stream.write(text, off, len); } finally { stream.close(); } } public static boolean processFilesRecursively(@NotNull File root, @NotNull Processor<File> processor) { return processFilesRecursively(root, processor, null); } public static boolean processFilesRecursively(@NotNull File root, @NotNull Processor<File> processor, @Nullable final Processor<File> directoryFilter) { final LinkedList<File> queue = new LinkedList<File>(); queue.add(root); while (!queue.isEmpty()) { final File file = queue.removeFirst(); if (!processor.process(file)) return false; if (directoryFilter != null && (!file.isDirectory() || !directoryFilter.process(file))) continue; final File[] children = file.listFiles(); if (children != null) { ContainerUtil.addAll(queue, children); } } return true; } @Nullable public static File findFirstThatExist(@NotNull String... paths) { for (String path : paths) { if (!StringUtil.isEmptyOrSpaces(path)) { File file = new File(toSystemDependentName(path)); if (file.exists()) return file; } } return null; } @NotNull public static List<File> findFilesByMask(@NotNull Pattern pattern, @NotNull File dir) { final ArrayList<File> found = new ArrayList<File>(); final File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { found.addAll(findFilesByMask(pattern, file)); } else if (pattern.matcher(file.getName()).matches()) { found.add(file); } } } return found; } @NotNull public static List<File> findFilesOrDirsByMask(@NotNull Pattern pattern, @NotNull File dir) { final ArrayList<File> found = new ArrayList<File>(); final File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (pattern.matcher(file.getName()).matches()) { found.add(file); } if (file.isDirectory()) { found.addAll(findFilesOrDirsByMask(pattern, file)); } } } return found; } /** * Returns empty string for empty path. * First checks whether provided path is a path of a file with sought-for name. * Unless found, checks if provided file was a directory. In this case checks existence * of child files with given names in order "as provided". Finally checks filename among * brother-files of provided. Returns null if nothing found. * * @return path of the first of found files or empty string or null. */ @Nullable public static String findFileInProvidedPath(String providedPath, String... fileNames) { if (StringUtil.isEmpty(providedPath)) { return ""; } File providedFile = new File(providedPath); if (providedFile.exists() && ArrayUtil.indexOf(fileNames, providedFile.getName()) >= 0) { return toSystemDependentName(providedFile.getPath()); } if (providedFile.isDirectory()) { //user chose folder with file for (String fileName : fileNames) { File file = new File(providedFile, fileName); if (fileName.equals(file.getName()) && file.exists()) { return toSystemDependentName(file.getPath()); } } } providedFile = providedFile.getParentFile(); //users chose wrong file in same directory if (providedFile != null && providedFile.exists()) { for (String fileName : fileNames) { File file = new File(providedFile, fileName); if (fileName.equals(file.getName()) && file.exists()) { return toSystemDependentName(file.getPath()); } } } return null; } public static boolean isAbsolutePlatformIndependent(@NotNull String path) { return isUnixAbsolutePath(path) || isWindowsAbsolutePath(path); } public static boolean isUnixAbsolutePath(@NotNull String path) { return path.startsWith("/"); } public static boolean isWindowsAbsolutePath(@NotNull String pathString) { return pathString.length() >= 2 && Character.isLetter(pathString.charAt(0)) && pathString.charAt(1) == ':'; } @Contract("null -> null; !null -> !null") public static String getLocationRelativeToUserHome(@Nullable String path) { return getLocationRelativeToUserHome(path, true); } @Contract("null,_ -> null; !null,_ -> !null") public static String getLocationRelativeToUserHome(@Nullable String path, boolean unixOnly) { if (path == null) return null; if (SystemInfo.isUnix || !unixOnly) { File projectDir = new File(path); File userHomeDir = new File(SystemProperties.getUserHome()); if (isAncestor(userHomeDir, projectDir, true)) { return '~' + File.separator + getRelativePath(userHomeDir, projectDir); } } return path; } @NotNull public static String expandUserHome(@NotNull String path) { if (path.startsWith("~/") || path.startsWith("~\\")) { path = SystemProperties.getUserHome() + path.substring(1); } return path; } @NotNull public static File[] notNullize(@Nullable File[] files) { return notNullize(files, ArrayUtil.EMPTY_FILE_ARRAY); } @NotNull public static File[] notNullize(@Nullable File[] files, @NotNull File[] defaultFiles) { return files == null ? defaultFiles : files; } public static boolean isHashBangLine(CharSequence firstCharsIfText, String marker) { if (firstCharsIfText == null) { return false; } final int lineBreak = StringUtil.indexOf(firstCharsIfText, '\n'); if (lineBreak < 0) { return false; } String firstLine = firstCharsIfText.subSequence(0, lineBreak).toString(); return firstLine.startsWith("#!") && firstLine.contains(marker); } @NotNull public static File createTempDirectory(@NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempDirectory(prefix, suffix); } @NotNull public static File createTempDirectory(@NotNull String prefix, @Nullable String suffix, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempDirectory(prefix, suffix, deleteOnExit); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempDirectory(dir, prefix, suffix); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull String prefix, @Nullable String suffix, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempDirectory(dir, prefix, suffix, deleteOnExit); } @NotNull public static File createTempFile(@NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempFile(prefix, suffix); } @NotNull public static File createTempFile(@NotNull String prefix, @Nullable String suffix, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempFile(prefix, suffix, deleteOnExit); } @NotNull public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix) throws IOException { return FileUtilRt.createTempFile(dir, prefix, suffix); } @NotNull public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix, boolean create) throws IOException { return FileUtilRt.createTempFile(dir, prefix, suffix, create); } @NotNull public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix, boolean create, boolean deleteOnExit) throws IOException { return FileUtilRt.createTempFile(dir, prefix, suffix, create, deleteOnExit); } @NotNull public static String getTempDirectory() { return FileUtilRt.getTempDirectory(); } @TestOnly public static void resetCanonicalTempPathCache(final String tempPath) { FileUtilRt.resetCanonicalTempPathCache(tempPath); } @NotNull public static File generateRandomTemporaryPath() throws IOException { return FileUtilRt.generateRandomTemporaryPath(); } public static void setExecutableAttribute(@NotNull String path, boolean executableFlag) throws IOException { FileUtilRt.setExecutableAttribute(path, executableFlag); } public static void setLastModified(@NotNull File file, long timeStamp) throws IOException { if (!file.setLastModified(timeStamp)) { LOG.warn(file.getPath()); } } @NotNull public static String loadFile(@NotNull File file) throws IOException { return FileUtilRt.loadFile(file); } @NotNull public static String loadFile(@NotNull File file, boolean convertLineSeparators) throws IOException { return FileUtilRt.loadFile(file, convertLineSeparators); } @NotNull public static String loadFile(@NotNull File file, @Nullable String encoding) throws IOException { return FileUtilRt.loadFile(file, encoding); } @NotNull public static String loadFile(@NotNull File file, @NotNull Charset encoding) throws IOException { return String.valueOf(FileUtilRt.loadFileText(file, encoding)); } @NotNull public static String loadFile(@NotNull File file, @Nullable String encoding, boolean convertLineSeparators) throws IOException { return FileUtilRt.loadFile(file, encoding, convertLineSeparators); } @NotNull public static char[] loadFileText(@NotNull File file) throws IOException { return FileUtilRt.loadFileText(file); } @NotNull public static char[] loadFileText(@NotNull File file, @Nullable String encoding) throws IOException { return FileUtilRt.loadFileText(file, encoding); } @NotNull public static char[] loadText(@NotNull Reader reader, int length) throws IOException { return FileUtilRt.loadText(reader, length); } @NotNull public static List<String> loadLines(@NotNull File file) throws IOException { return FileUtilRt.loadLines(file); } @NotNull public static List<String> loadLines(@NotNull File file, @Nullable String encoding) throws IOException { return FileUtilRt.loadLines(file, encoding); } @NotNull public static List<String> loadLines(@NotNull String path) throws IOException { return FileUtilRt.loadLines(path); } @NotNull public static List<String> loadLines(@NotNull String path, @Nullable String encoding) throws IOException { return FileUtilRt.loadLines(path, encoding); } @NotNull public static List<String> loadLines(@NotNull BufferedReader reader) throws IOException { return FileUtilRt.loadLines(reader); } @NotNull public static byte[] loadBytes(@NotNull InputStream stream) throws IOException { return FileUtilRt.loadBytes(stream); } @NotNull public static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException { return FileUtilRt.loadBytes(stream, length); } @NotNull public static List<String> splitPath(@NotNull String path) { ArrayList<String> list = new ArrayList<String>(); int index = 0; int nextSeparator; while ((nextSeparator = path.indexOf(File.separatorChar, index)) != -1) { list.add(path.substring(index, nextSeparator)); index = nextSeparator + 1; } list.add(path.substring(index, path.length())); return list; } public static boolean isJarOrZip(@NotNull File file) { if (file.isDirectory()) { return false; } final String name = file.getName(); return StringUtil.endsWithIgnoreCase(name, ".jar") || StringUtil.endsWithIgnoreCase(name, ".zip"); } public static boolean visitFiles(@NotNull File root, @NotNull Processor<File> processor) { if (!processor.process(root)) { return false; } File[] children = root.listFiles(); if (children != null) { for (File child : children) { if (!visitFiles(child, processor)) { return false; } } } return true; } /** * Like {@link Properties#load(Reader)}, but preserves the order of key/value pairs. */ @NotNull public static Map<String, String> loadProperties(@NotNull Reader reader) throws IOException { final Map<String, String> map = ContainerUtil.newLinkedHashMap(); new Properties() { @Override public synchronized Object put(Object key, Object value) { map.put(String.valueOf(key), String.valueOf(value)); //noinspection UseOfPropertiesAsHashtable return super.put(key, value); } }.load(reader); return map; } public static boolean isRootPath(@NotNull File file) { return isRootPath(file.getPath()); } public static boolean isRootPath(@NotNull String path) { return path.equals("/") || path.matches("[a-zA-Z]:[/\\\\]"); } public static boolean deleteWithRenaming(File file) { File tempFileNameForDeletion = findSequentNonexistentFile(file.getParentFile(), file.getName(), ""); boolean success = file.renameTo(tempFileNameForDeletion); return delete(success ? tempFileNameForDeletion:file); } public static boolean isFileSystemCaseSensitive(@NotNull String path) throws FileNotFoundException { FileAttributes attributes = FileSystemUtil.getAttributes(path); if (attributes == null) { throw new FileNotFoundException(path); } FileAttributes upper = FileSystemUtil.getAttributes(path.toUpperCase(Locale.ENGLISH)); FileAttributes lower = FileSystemUtil.getAttributes(path.toLowerCase(Locale.ENGLISH)); return !(attributes.equals(upper) && attributes.equals(lower)); } }
Fix of bug in FileUtil - do not empty the file if one tries to copy it into itself.
platform/util/src/com/intellij/openapi/util/io/FileUtil.java
Fix of bug in FileUtil - do not empty the file if one tries to copy it into itself.
<ide><path>latform/util/src/com/intellij/openapi/util/io/FileUtil.java <ide> <ide> @SuppressWarnings("Duplicates") <ide> private static void performCopy(@NotNull File fromFile, @NotNull File toFile, final boolean syncTimestamp) throws IOException { <add> if (filesEqual(fromFile, toFile)) return; <ide> final FileOutputStream fos; <ide> try { <ide> fos = openOutputStream(toFile);
Java
apache-2.0
5047a860b8cc5a6c7a80d489e8cfbb3125a6e658
0
ricardotealdi/http-client
package br.com.tealdi.httpclient.wrapper; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import br.com.tealdi.httpclient.Header; import br.com.tealdi.httpclient.Request; import br.com.tealdi.httpclient.Response; import br.com.tealdi.httpclient.builder.IResponseBuilder; public class HttpConnectorWrapper implements IHttpConnectorWrapper { private final IResponseBuilder builder; public HttpConnectorWrapper(IResponseBuilder builder) { this.builder = builder; } @Override public Response connectTo(Request request, String httpVerb) throws MalformedURLException, IOException { URL url = new URL(request.getUri()); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestMethod(httpVerb); setRequestHeader(urlConnection, request.getHeader()); setRequestBody(urlConnection, request.getBody()); urlConnection.connect(); return readResponse(urlConnection); } private Response readResponse(HttpURLConnection connection) throws IOException { int statusCode = connection.getResponseCode(); Header header = getHeader(connection); String body = getBody(connection); connection.disconnect(); return builder.buildWith(statusCode, body, header); } private Header getHeader(HttpURLConnection urlConnection) { Iterator<String> iterator = urlConnection.getHeaderFields().keySet().iterator(); Header header = new Header(); while(iterator.hasNext()) { String headerKey = iterator.next(); String headerValue = urlConnection.getHeaderField(headerKey); header.add(headerKey, headerValue); } return header; } private String getBody(HttpURLConnection urlConnection) throws IOException { StringBuilder builderForBody = new StringBuilder(); InputStream output; try { output = urlConnection.getInputStream(); } catch(IOException exception) { output = urlConnection.getErrorStream(); } Scanner scanner = new Scanner(output); while(scanner.hasNextLine()) { builderForBody.append(scanner.nextLine()); builderForBody.append("\r"); } output.close(); scanner.close(); return builderForBody.toString(); } private void setRequestBody(HttpURLConnection urlConnection, String body) throws IOException { PrintWriter bodyStream = new PrintWriter(urlConnection.getOutputStream()); bodyStream.print(body); bodyStream.close(); } private void setRequestHeader(HttpURLConnection connection, Header header) { Iterator<String> headerIterator = header.getHeaders().keySet().iterator(); while(headerIterator.hasNext()) { String headerKey = headerIterator.next(); String headerValue = header.get(headerKey); connection.setRequestProperty(headerKey, headerValue); } } }
src/main/java/br/com/tealdi/httpclient/wrapper/HttpConnectorWrapper.java
package br.com.tealdi.httpclient.wrapper; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import br.com.tealdi.httpclient.Header; import br.com.tealdi.httpclient.Request; import br.com.tealdi.httpclient.Response; import br.com.tealdi.httpclient.builder.IResponseBuilder; public class HttpConnectorWrapper implements IHttpConnectorWrapper { private final IResponseBuilder builder; public HttpConnectorWrapper(IResponseBuilder builder) { this.builder = builder; } @Override public Response connectTo(Request request, String httpVerb) throws MalformedURLException, IOException { URL url = new URL(request.getUri()); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestMethod(httpVerb); setRequestHeader(urlConnection, request.getHeader()); setRequestBody(urlConnection, request.getBody()); urlConnection.connect(); return readResponse(urlConnection); /*System.setProperty("http.keepAlive", "FALSE"); HttpURLConnection connection = (HttpURLConnection) new URL(request.getUri()).openConnection(); connection.setRequestMethod(httpVerb); connection.setDoInput(true); connection.setDoOutput(true); setRequestHeader(connection, request.getHeader()); Response response; try { setRequestBody(request.getBody(), connection.getOutputStream()); response = readResponse(connection); } catch(UnknownHostException exception) { response = builder .buildWith( HttpURLConnection.HTTP_BAD_GATEWAY, getErrorBody(connection), new Header()); } catch(IOException exception) { response = builder .buildWith( connection.getResponseCode(), getErrorBody(connection), new Header()); } connection.disconnect(); return response;*/ } private Response readResponse(HttpURLConnection connection) throws IOException { int statusCode = connection.getResponseCode(); Header header = getHeader(connection); String body = getBody(connection); connection.disconnect(); return builder.buildWith(statusCode, body, header); } private Header getHeader(HttpURLConnection urlConnection) { Iterator<String> iterator = urlConnection.getHeaderFields().keySet().iterator(); Header header = new Header(); while(iterator.hasNext()) { String headerKey = iterator.next(); String headerValue = urlConnection.getHeaderField(headerKey); header.add(headerKey, headerValue); } return header; } private String getBody(HttpURLConnection urlConnection) throws IOException { StringBuilder builderForBody = new StringBuilder(); InputStream output; try { output = urlConnection.getInputStream(); } catch(IOException exception) { output = urlConnection.getErrorStream(); } Scanner scanner = new Scanner(output); while(scanner.hasNextLine()) { builderForBody.append(scanner.nextLine()); builderForBody.append("\r"); } output.close(); scanner.close(); return builderForBody.toString(); } private void setRequestBody(HttpURLConnection urlConnection, String body) throws IOException { PrintWriter bodyStream = new PrintWriter(urlConnection.getOutputStream()); bodyStream.print(body); bodyStream.close(); } private void setRequestHeader(HttpURLConnection connection, Header header) { Iterator<String> headerIterator = header.getHeaders().keySet().iterator(); while(headerIterator.hasNext()) { String headerKey = headerIterator.next(); String headerValue = header.get(headerKey); connection.setRequestProperty(headerKey, headerValue); } } }
removed some commented code
src/main/java/br/com/tealdi/httpclient/wrapper/HttpConnectorWrapper.java
removed some commented code
<ide><path>rc/main/java/br/com/tealdi/httpclient/wrapper/HttpConnectorWrapper.java <ide> urlConnection.connect(); <ide> <ide> return readResponse(urlConnection); <del> <del> /*System.setProperty("http.keepAlive", "FALSE"); <del> HttpURLConnection connection = <del> (HttpURLConnection) new URL(request.getUri()).openConnection(); <del> connection.setRequestMethod(httpVerb); <del> connection.setDoInput(true); <del> connection.setDoOutput(true); <del> <del> setRequestHeader(connection, request.getHeader()); <del> Response response; <del> <del> try { <del> setRequestBody(request.getBody(), connection.getOutputStream()); <del> <del> response = readResponse(connection); <del> } catch(UnknownHostException exception) { <del> response = <del> builder <del> .buildWith( <del> HttpURLConnection.HTTP_BAD_GATEWAY, <del> getErrorBody(connection), <del> new Header()); <del> } catch(IOException exception) { <del> response = <del> builder <del> .buildWith( <del> connection.getResponseCode(), <del> getErrorBody(connection), <del> new Header()); <del> } <del> <del> connection.disconnect(); <del> <del> return response;*/ <ide> } <ide> <ide> private Response readResponse(HttpURLConnection connection) throws IOException {
Java
apache-2.0
9326c93ff14f3b8df02006021e82aa1517039146
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
package br.net.mirante.singular.form.mform.options; import br.net.mirante.singular.form.mform.MILista; import br.net.mirante.singular.form.mform.MInstancia; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.UUID; /** * Mapeia cada MInstancia fornecida pelo OptionsProvider * para uma par de descricao e chave (label e key) * É reponsável também por devolver a MIinstancia correspondente a cada * chave */ public class MOptionsConfig { private static final Logger LOGGER = LoggerFactory.getLogger(MOptionsConfig.class); private BiMap<String, MInstancia> optionsKeyInstanceMap; private BiMap<String, String> optionsKeylabelMap; private MILista<? extends MInstancia> options; private MSelectionableInstance instancia; public MOptionsConfig(MSelectionableInstance instancia) { this.instancia = instancia; } protected MOptionsProvider getOptionsProvider() { if (instancia instanceof MILista) { return ((MILista) instancia).getTipoElementos().getProviderOpcoes(); } return instancia.getMTipo().getProviderOpcoes(); } private BiMap<String, MInstancia> getOptions() { init(); return optionsKeyInstanceMap; } private void init() { if (optionsKeyInstanceMap == null) { reloadOptionsFromProvider(); } } /** * Reexecuta o listAvailableOptions do provider do tipo. */ private void reloadOptionsFromProvider() { MOptionsProvider provider = getOptionsProvider(); if (provider != null) { MILista<? extends MInstancia> newOptions = provider.listAvailableOptions(instancia); LOGGER.warn("Opções recarregadas para "+toString()); if (newOptions != null && !newOptions.equals(options)) { options = newOptions; optionsKeyInstanceMap = HashBiMap.create(options.size()); optionsKeylabelMap = HashBiMap.create(options.size()); for (MInstancia mInstancia : options) { String key = UUID.randomUUID().toString(); optionsKeyInstanceMap.put(key, mInstancia); optionsKeylabelMap.put(key, mInstancia.getSelectLabel()); } } } else { optionsKeyInstanceMap = HashBiMap.create(); optionsKeylabelMap = HashBiMap.create(options.size()); options = new MILista<>(); } } private MILista<? extends MInstancia> getOptionsList() { if (options == null) { return new MILista<>(); } return options; } public String getLabelFromOption(MInstancia selectedValue) { if (selectedValue == null) { return null; } String key = getOptions().inverse().get(selectedValue); return optionsKeylabelMap.get(key); } public String getLabelFromKey(String key) { if (key == null) { return null; } return optionsKeylabelMap.get(key); } public String getKeyFromOptions(MInstancia option) { if (option == null) { return null; } return getOptions().inverse().get(option); } public MInstancia getValueFromKey(String key) { if (key == null) { return null; } return getOptions().get(key); } /** * @return Um mapa de chave e valor representando as Minstancias disponibilizadas pelo provider do tipo * da instancia. */ public Map<String, String> listSelectOptions() { reloadOptionsFromProvider(); return optionsKeylabelMap; } }
form/core/src/main/java/br/net/mirante/singular/form/mform/options/MOptionsConfig.java
package br.net.mirante.singular.form.mform.options; import br.net.mirante.singular.form.mform.MILista; import br.net.mirante.singular.form.mform.MInstancia; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.UUID; import java.util.function.Supplier; /** * Mapeia cada MInstancia fornecida pelo OptionsProvider * para uma par de descricao e chave (label e key) * É reponsável também por devolver a MIinstancia correspondente a cada * chave */ public class MOptionsConfig { private static final Logger LOGGER = LoggerFactory.getLogger(MOptionsConfig.class); private BiMap<String, MInstancia> optionsKeyInstanceMap; private BiMap<String, String> optionsKeylabelMap; private MILista<? extends MInstancia> options; private MSelectionableInstance instancia; private Supplier<MOptionsProvider> providerSupplier; public MOptionsConfig(MSelectionableInstance instancia) { this.instancia = instancia; } protected MOptionsProvider getOptionsProvider() { return providerSupplier.get(); } private BiMap<String, MInstancia> getOptions() { init(); return optionsKeyInstanceMap; } private void init() { if (optionsKeyInstanceMap == null) { reloadOptionsFromProvider(); } } /** * Reexecuta o listAvailableOptions do provider do tipo. */ private void reloadOptionsFromProvider() { MOptionsProvider provider = getOptionsProvider(); if (provider != null) { MILista<? extends MInstancia> newOptions = provider.listAvailableOptions(instancia); LOGGER.warn("Opções recarregadas para "+toString()); if (newOptions != null && !newOptions.equals(options)) { options = newOptions; optionsKeyInstanceMap = HashBiMap.create(options.size()); optionsKeylabelMap = HashBiMap.create(options.size()); for (MInstancia mInstancia : options) { String key = UUID.randomUUID().toString(); optionsKeyInstanceMap.put(key, mInstancia); optionsKeylabelMap.put(key, mInstancia.getSelectLabel()); } } } else { optionsKeyInstanceMap = HashBiMap.create(); optionsKeylabelMap = HashBiMap.create(options.size()); options = new MILista<>(); } } private MILista<? extends MInstancia> getOptionsList() { if (options == null) { return new MILista<>(); } return options; } public String getLabelFromOption(MInstancia selectedValue) { if (selectedValue == null) { return null; } String key = getOptions().inverse().get(selectedValue); return optionsKeylabelMap.get(key); } public String getLabelFromKey(String key) { if (key == null) { return null; } return optionsKeylabelMap.get(key); } public String getKeyFromOptions(MInstancia option) { if (option == null) { return null; } return getOptions().inverse().get(option); } public MInstancia getValueFromKey(String key) { if (key == null) { return null; } return getOptions().get(key); } /** * @return Um mapa de chave e valor representando as Minstancias disponibilizadas pelo provider do tipo * da instancia. */ public Map<String, String> listSelectOptions() { reloadOptionsFromProvider(); return optionsKeylabelMap; } }
corrigindo commit errado refernetes aos bugs do select
form/core/src/main/java/br/net/mirante/singular/form/mform/options/MOptionsConfig.java
corrigindo commit errado refernetes aos bugs do select
<ide><path>orm/core/src/main/java/br/net/mirante/singular/form/mform/options/MOptionsConfig.java <ide> <ide> import java.util.Map; <ide> import java.util.UUID; <del>import java.util.function.Supplier; <ide> <ide> /** <ide> * Mapeia cada MInstancia fornecida pelo OptionsProvider <ide> private BiMap<String, String> optionsKeylabelMap; <ide> private MILista<? extends MInstancia> options; <ide> private MSelectionableInstance instancia; <del> private Supplier<MOptionsProvider> providerSupplier; <ide> <ide> public MOptionsConfig(MSelectionableInstance instancia) { <ide> this.instancia = instancia; <ide> } <ide> <ide> protected MOptionsProvider getOptionsProvider() { <del> return providerSupplier.get(); <add> if (instancia instanceof MILista) { <add> return ((MILista) instancia).getTipoElementos().getProviderOpcoes(); <add> } <add> return instancia.getMTipo().getProviderOpcoes(); <ide> } <ide> <ide> private BiMap<String, MInstancia> getOptions() {
JavaScript
apache-2.0
3587542a9bf2a4985f36a83fddd0dc98a4eb6bcc
0
neighbourhoodie/voice-of-interconnect,neighbourhoodie/voice-of-interconnect,neighbourhoodie/voice-of-interconnect
/* global localStorage */ module.exports = appNav const $nav = document.querySelector('#app-nav') const $showAbout = document.querySelector('.view__about') const $showApp = document.querySelector('.view__app') const $aboutDisplay = document.querySelector('.about') const $closeAbout = document.querySelector('.close__about') function appNav () { $showAbout.addEventListener('click', showAbout) $showApp.addEventListener('click', showApp) $closeAbout.addEventListener('click', showApp) if (localStorage.getItem('seenWelcome')) { return showApp() } } function showAbout (event) { event.preventDefault() $aboutDisplay.classList.add('active') $nav.classList.remove('active') localStorage.setItem('seenWelcome', '1') } function showApp (event) { if (event) { event.preventDefault() } $showApp.classList.add('active') $aboutDisplay.classList.remove('active') $nav.classList.remove('active') localStorage.setItem('seenWelcome', '1') }
app/lib/app-nav.js
// For mobile navigation module.exports = appNav const $nav = document.querySelector('#app-nav') const $showAbout = document.querySelector('.view__about') const $showApp = document.querySelector('.view__app') const $aboutDisplay = document.querySelector('.about') const $closeAbout = document.querySelector('.close__about') function appNav () { $showAbout.addEventListener('click', function (event) { event.preventDefault() $aboutDisplay.classList.add('active') $nav.classList.remove('active') }) $showApp.addEventListener('click', function (event) { event.preventDefault() $showApp.classList.add('active') $aboutDisplay.classList.remove('active') $nav.classList.remove('active') }) $closeAbout.addEventListener('click', function (event) { event.preventDefault() $aboutDisplay.classList.remove('active') $nav.classList.remove('active') }) }
fix: remember that welcome splash screen has been seen cc @kidfribble
app/lib/app-nav.js
fix: remember that welcome splash screen has been seen
<ide><path>pp/lib/app-nav.js <del>// For mobile navigation <add>/* global localStorage */ <ide> module.exports = appNav <ide> <ide> const $nav = document.querySelector('#app-nav') <ide> const $closeAbout = document.querySelector('.close__about') <ide> <ide> function appNav () { <del> $showAbout.addEventListener('click', function (event) { <add> $showAbout.addEventListener('click', showAbout) <add> $showApp.addEventListener('click', showApp) <add> $closeAbout.addEventListener('click', showApp) <add> <add> if (localStorage.getItem('seenWelcome')) { <add> return showApp() <add> } <add>} <add> <add>function showAbout (event) { <add> event.preventDefault() <add> <add> $aboutDisplay.classList.add('active') <add> $nav.classList.remove('active') <add> <add> localStorage.setItem('seenWelcome', '1') <add>} <add> <add>function showApp (event) { <add> if (event) { <ide> event.preventDefault() <add> } <ide> <del> $aboutDisplay.classList.add('active') <del> $nav.classList.remove('active') <del> }) <add> $showApp.classList.add('active') <add> $aboutDisplay.classList.remove('active') <add> $nav.classList.remove('active') <ide> <del> $showApp.addEventListener('click', function (event) { <del> event.preventDefault() <del> <del> $showApp.classList.add('active') <del> $aboutDisplay.classList.remove('active') <del> $nav.classList.remove('active') <del> }) <del> <del> $closeAbout.addEventListener('click', function (event) { <del> event.preventDefault() <del> <del> $aboutDisplay.classList.remove('active') <del> $nav.classList.remove('active') <del> }) <add> localStorage.setItem('seenWelcome', '1') <ide> }
Java
apache-2.0
60a352cda7157d7552e537bc99527f6d87ce05e5
0
phlizik/FreeFlow,zhaochuanTeam/FreeFlow,rantianhua/FreeFlow,tsdl2013/FreeFlow,qingsong-xu/FreeFlow,hgl888/FreeFlow,elevenetc/FreeFlow,xiaoyanit/FreeFlow,predator11/FreeFlow-2-,pkexcellent/FreeFlow,hanhailong/FreeFlow,dhamofficial/FreeFlow,simple88/FreeFlow,Cryhelyxx/FreeFlow,hesling/FreeFlow,Comcast/FreeFlow,letanloc/FreeFlow
/******************************************************************************* * Copyright 2013 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.comcast.freeflow.examples.artbook; import com.comcast.freeflow.core.AbsLayoutContainer; import com.comcast.freeflow.core.AbsLayoutContainer.OnItemClickListener; import com.comcast.freeflow.core.Container; import com.comcast.freeflow.core.FreeFlowItem; import com.comcast.freeflow.core.Container.OnScrollListener; import com.comcast.freeflow.layouts.FreeFlowLayout; import com.comcast.freeflow.layouts.VGridLayout; import com.comcast.freeflow.layouts.VLayout; import com.comcast.freeflow.layouts.VGridLayout.LayoutParams; import com.comcast.freeflow.examples.artbook.data.DribbbleDataAdapter; import com.comcast.freeflow.examples.artbook.layouts.ArtbookLayout; import com.comcast.freeflow.examples.artbook.models.DribbbleFeed; import com.comcast.freeflow.examples.artbook.models.DribbbleFetch; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Point; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; public class ArtbookActivity extends Activity implements OnClickListener{ public static final String TAG = "ArtbookActivity"; private Container container; private VGridLayout grid; private ArtbookLayout custom; private DribbbleFetch fetch; private int itemsPerPage = 25; private int pageIndex = 1; DribbbleDataAdapter adapter; FreeFlowLayout[] layouts; int currLayoutIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_artbook); container = (Container) findViewById(R.id.container); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); findViewById(R.id.load_more).setOnClickListener(this); //Our new layout custom = new ArtbookLayout(); //Grid Layout grid = new VGridLayout(); VGridLayout.LayoutParams params = new VGridLayout.LayoutParams(size.x/2, size.x/2); grid.setLayoutParams(params); //Vertical Layout VLayout vert = new VLayout(); VLayout.LayoutParams params2 = new VLayout.LayoutParams(size.x); vert.setLayoutParams(params2); layouts = new FreeFlowLayout[]{custom, grid, vert}; adapter = new DribbbleDataAdapter(this); container.setLayout(layouts[currLayoutIndex]); container.setAdapter(adapter); fetch = new DribbbleFetch(); fetch.load(this,itemsPerPage , pageIndex); } public void onDataLoaded(DribbbleFeed feed) { Log.d(TAG, "photo: " + feed.getShots().get(0).getImage_teaser_url()); adapter.update(feed); container.dataInvalidated(); container.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AbsLayoutContainer parent, FreeFlowItem proxy) { } }); container.addScrollListener( new OnScrollListener() { @Override public void onScroll(Container container) { Log.d(TAG, "scroll percent "+ container.getScrollPercentY() ); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.artbook, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()){ case (R.id.action_change_layout): currLayoutIndex++; if(currLayoutIndex == layouts.length){ currLayoutIndex = 0; } container.setLayout(layouts[currLayoutIndex]); break; case (R.id.action_about): Intent about = new Intent(this, AboutActivity.class); startActivity(about); break; } return true; } @Override public void onClick(View v) { Log.d(TAG, "Loading data"); pageIndex++; fetch.load(this, itemsPerPage, pageIndex); } }
examples/Artbook/src/com/comcast/freeflow/examples/artbook/ArtbookActivity.java
/******************************************************************************* * Copyright 2013 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.comcast.freeflow.examples.artbook; import com.comcast.freeflow.core.AbsLayoutContainer; import com.comcast.freeflow.core.AbsLayoutContainer.OnItemClickListener; import com.comcast.freeflow.core.Container; import com.comcast.freeflow.core.FreeFlowItem; import com.comcast.freeflow.core.Container.OnScrollListener; import com.comcast.freeflow.layouts.VGridLayout; import com.comcast.freeflow.layouts.VGridLayout.LayoutParams; import com.comcast.freeflow.examples.artbook.data.DribbbleDataAdapter; import com.comcast.freeflow.examples.artbook.layouts.ArtbookLayout; import com.comcast.freeflow.examples.artbook.models.DribbbleFeed; import com.comcast.freeflow.examples.artbook.models.DribbbleFetch; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Point; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; public class ArtbookActivity extends Activity implements OnClickListener{ public static final String TAG = "ArtbookActivity"; private Container container; private VGridLayout grid; private ArtbookLayout custom; private DribbbleFetch fetch; private int itemsPerPage = 5; private int pageIndex = 1; DribbbleDataAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_artbook); container = (Container) findViewById(R.id.container); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); findViewById(R.id.load_more).setOnClickListener(this); grid = new VGridLayout(); VGridLayout.LayoutParams params = new VGridLayout.LayoutParams(size.x/2, size.x/2); grid.setLayoutParams(params); adapter = new DribbbleDataAdapter(this); custom = new ArtbookLayout(); container.setLayout(custom); container.setAdapter(adapter); fetch = new DribbbleFetch(); fetch.load(this,itemsPerPage , pageIndex); } public void onDataLoaded(DribbbleFeed feed) { Log.d(TAG, "photo: " + feed.getShots().get(0).getImage_teaser_url()); adapter.update(feed); container.dataInvalidated(); container.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AbsLayoutContainer parent, FreeFlowItem proxy) { } }); container.addScrollListener( new OnScrollListener() { @Override public void onScroll(Container container) { Log.d(TAG, "scroll percent "+ container.getScrollPercentY() ); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.artbook, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()){ case (R.id.action_change_layout): if(container.getLayout() == grid){ container.setLayout(custom); } else{ container.setLayout(grid); } break; case (R.id.action_about): Intent about = new Intent(this, AboutActivity.class); startActivity(about); break; } return true; } @Override public void onClick(View v) { Log.d(TAG, "Loading data"); pageIndex++; fetch.load(this, itemsPerPage, pageIndex); } }
Added another layout to the Artbook project
examples/Artbook/src/com/comcast/freeflow/examples/artbook/ArtbookActivity.java
Added another layout to the Artbook project
<ide><path>xamples/Artbook/src/com/comcast/freeflow/examples/artbook/ArtbookActivity.java <ide> import com.comcast.freeflow.core.Container; <ide> import com.comcast.freeflow.core.FreeFlowItem; <ide> import com.comcast.freeflow.core.Container.OnScrollListener; <add>import com.comcast.freeflow.layouts.FreeFlowLayout; <ide> import com.comcast.freeflow.layouts.VGridLayout; <add>import com.comcast.freeflow.layouts.VLayout; <ide> import com.comcast.freeflow.layouts.VGridLayout.LayoutParams; <ide> import com.comcast.freeflow.examples.artbook.data.DribbbleDataAdapter; <ide> import com.comcast.freeflow.examples.artbook.layouts.ArtbookLayout; <ide> private ArtbookLayout custom; <ide> <ide> private DribbbleFetch fetch; <del> private int itemsPerPage = 5; <add> private int itemsPerPage = 25; <ide> private int pageIndex = 1; <ide> <ide> DribbbleDataAdapter adapter; <add> <add> FreeFlowLayout[] layouts; <add> int currLayoutIndex = 0; <ide> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> display.getSize(size); <ide> <ide> findViewById(R.id.load_more).setOnClickListener(this); <del> <add> //Our new layout <add> custom = new ArtbookLayout(); <add> <add> //Grid Layout <ide> grid = new VGridLayout(); <ide> VGridLayout.LayoutParams params = new VGridLayout.LayoutParams(size.x/2, size.x/2); <ide> grid.setLayoutParams(params); <ide> <add> //Vertical Layout <add> VLayout vert = new VLayout(); <add> VLayout.LayoutParams params2 = new VLayout.LayoutParams(size.x); <add> vert.setLayoutParams(params2); <add> <add> <add> layouts = new FreeFlowLayout[]{custom, grid, vert}; <add> <ide> adapter = new DribbbleDataAdapter(this); <del> custom = new ArtbookLayout(); <del> container.setLayout(custom); <add> <add> <add> container.setLayout(layouts[currLayoutIndex]); <ide> container.setAdapter(adapter); <ide> <ide> <ide> super.onOptionsItemSelected(item); <ide> switch(item.getItemId()){ <ide> case (R.id.action_change_layout): <del> if(container.getLayout() == grid){ <del> container.setLayout(custom); <add> currLayoutIndex++; <add> if(currLayoutIndex == layouts.length){ <add> currLayoutIndex = 0; <ide> } <del> else{ <del> container.setLayout(grid); <del> } <add> container.setLayout(layouts[currLayoutIndex]); <add> <ide> break; <ide> case (R.id.action_about): Intent about = new Intent(this, AboutActivity.class); <ide> startActivity(about);
JavaScript
mit
293049b6be6ba46d9de9ee34bca3f16f60661839
0
cpelletier88/cubot,cpelletier88/cubot,cpelletier88/cubot
var querystring = require('querystring'); var https = require('https'); module.exports = function(robot) { function getEncodedToken(env) { if(env === 'eval' || env === 'evaluation') { return 'MGZjY2RiYzczNTgxY2EwZjliZjhjMzc5ZTZhOTY4MTM6MzcxOWExMjRiY2ZjMDNjNTM0ZDRmNWMwNWI1YTE5NmI='; } else if(env === 'rc') { return (new Buffer(process.env.CS_RC_CLIENT_ID + ':' + process.env.CS_RC_CLIENT_SECRET).toString('base64')); } else { return (new Buffer(process.env.CS_CLIENT_ID + ':' + process.env.CS_CLIENT_SECRET).toString('base64')); } } function getHostName(env) { var hostname; switch(env) { case 'eval': hostname = 'capi-eval.signnow.com'; break; case 'evaluation': hostname = 'capi-eval.signnow.com'; break; case 'dev': hostname = 'api-dev.signnow.com'; break; case 'development': hostname = 'api-dev.signnow.com'; break; case 'rc': hostname = 'api-rc.signnow.com'; break; default: hostname = 'capi-eval.signnow.com'; break; } return hostname; } robot.respond(/get me a basic token for (.*)/i, function(res) { var env = res.match[1].trim(); res.reply(getEncodedToken(env)); }); robot.respond(/create user (.*) on (.*)/i, function(res) { var userResponse; var user = res.match[1].trim().split(','); var email = user[0].trim(); var password = user[1].trim(); var env = res.match[2].trim(); if (email == undefined || password == undefined) { res.reply('You did provide and email and or password'); } else if(env == undefined) { res.reply('You did provide an environment'); } else { if (env == 'prod' || env == 'production') { res.reply('Not creating users on prod right now'); } else { var data = JSON.stringify({ email: email, password: password }); var options = { hostname: getHostName(env), path: '/user', method: 'POST', headers: { "Authorization": "Basic " + getEncodedToken(env), "User-Agent": "My Cubot app" } }; if (env === 'eval') { options.path = '/api/user'; } var req = https.request(options, function(httpResponse) { httpResponse.on('data', function(d) { res.reply(d.toString('utf8')); }); }); console.log(req); req.write(data); req.end(); req.on('error', function(e) { res.reply(e); }); } } }); };
scripts/cudasign.js
var querystring = require('querystring'); var https = require('https'); module.exports = function(robot) { function getEncodedToken(env) { if(env === 'eval' || env === 'evaluation') { return 'MGZjY2RiYzczNTgxY2EwZjliZjhjMzc5ZTZhOTY4MTM6MzcxOWExMjRiY2ZjMDNjNTM0ZDRmNWMwNWI1YTE5NmI='; } else if(env === 'rc') { return (new Buffer(process.env.CS_RC_CLIENT_ID + ':' + process.env.CS_RC_CLIENT_SECRET).toString('base64')); } else { return (new Buffer(process.env.CS_CLIENT_ID + ':' + process.env.CS_CLIENT_SECRET).toString('base64')); } } function getHostName(env) { var hostname; switch(env) { case 'eval': hostname = 'capi-eval.signnow.com'; break; case 'evaluation': hostname = 'capi-eval.signnow.com'; break; case 'dev': hostname = 'api-dev.signnow.com'; break; case 'development': hostname = 'api-dev.signnow.com'; break; case 'development': hostname = 'api-rc.signnow.com'; break; default: hostname = 'capi-eval.signnow.com'; break; } return hostname; } robot.respond(/get me a basic token for (.*)/i, function(res) { var env = res.match[1].trim(); res.reply(getEncodedToken(env)); }); robot.respond(/create user (.*) on (.*)/i, function(res) { var userResponse; var user = res.match[1].trim().split(','); var email = user[0].trim(); var password = user[1].trim(); var env = res.match[2].trim(); if (email == undefined || password == undefined) { res.reply('You did provide and email and or password'); } else if(env == undefined) { res.reply('You did provide an environment'); } else { if (env == 'prod' || env == 'production') { res.reply('Not creating users on prod right now'); } else { var data = JSON.stringify({ email: email, password: password }); var options = { hostname: getHostName(env), path: '/user', method: 'POST', headers: { "Authorization": "Basic " + getEncodedToken(env), "User-Agent": "My Cubot app" } }; if (env === 'eval') { options.path = '/api/user'; } var req = https.request(options, function(httpResponse) { httpResponse.on('data', function(d) { res.reply(d.toString('utf8')); }); }); console.log(req); req.write(data); req.end(); req.on('error', function(e) { res.reply(e); }); } } }); };
Forgot the environment when env is rc
scripts/cudasign.js
Forgot the environment when env is rc
<ide><path>cripts/cudasign.js <ide> case 'development': <ide> hostname = 'api-dev.signnow.com'; <ide> break; <del> case 'development': <add> case 'rc': <ide> hostname = 'api-rc.signnow.com'; <ide> break; <ide> default:
Java
apache-2.0
5897c5c185e1ca4ce430f29310bef7059cdb5396
0
electricalwind/greycat,electricalwind/greycat,Neoskai/greycat,electricalwind/greycat,Neoskai/greycat,electricalwind/greycat,Neoskai/greycat,Neoskai/greycat,electricalwind/greycat,datathings/greycat,datathings/greycat,Neoskai/greycat,datathings/greycat,datathings/greycat,datathings/greycat,datathings/greycat,electricalwind/greycat,Neoskai/greycat
package org.mwg.core.task; import org.mwg.Callback; import org.mwg.DeferCounter; import org.mwg.Node; import org.mwg.core.utility.CoreDeferCounter; import org.mwg.plugin.Job; import org.mwg.task.TaskAction; import org.mwg.task.TaskContext; class ActionJump implements TaskAction { private final String _time; ActionJump(String time) { _time = time; } @Override public void eval(TaskContext context) { String templatedTime = context.template(_time); long time = Long.parseLong(templatedTime); Object previousResult = context.result(); Node[] jumpedNodes = TaskHelper.flatNodes(previousResult,false); final DeferCounter defer = new CoreDeferCounter(jumpedNodes.length); Node[] result = new Node[jumpedNodes.length]; for(int i=0;i<jumpedNodes.length;i++) { final int ii = i; jumpedNodes[i].jump(time, new Callback<Node>() { @Override public void on(Node jumped) { result[ii] = jumped; defer.count(); } }); } defer.then(new Job() { @Override public void run() { context.cleanObj(previousResult); context.setUnsafeResult(result); } }); } @Override public String toString() { return "jump(" + _time + ")"; } }
core/src/main/java/org/mwg/core/task/ActionJump.java
package org.mwg.core.task; import org.mwg.Callback; import org.mwg.DeferCounter; import org.mwg.Node; import org.mwg.core.utility.CoreDeferCounter; import org.mwg.plugin.Job; import org.mwg.task.TaskAction; import org.mwg.task.TaskContext; public class ActionJump implements TaskAction { private final String _time; public ActionJump(String time) { _time = time; } @Override public void eval(TaskContext context) { String templatedTime = context.template(_time); long time = Long.parseLong(templatedTime); Object previousResult = context.result(); Node[] jumpedNodes = TaskHelper.flatNodes(previousResult,false); final DeferCounter defer = new CoreDeferCounter(jumpedNodes.length); Node[] result = new Node[jumpedNodes.length]; for(int i=0;i<jumpedNodes.length;i++) { final int ii = i; jumpedNodes[i].jump(time, new Callback<Node>() { @Override public void on(Node jumped) { result[ii] = jumped; defer.count(); } }); } defer.then(new Job() { @Override public void run() { context.cleanObj(previousResult); context.setUnsafeResult(result); } }); } @Override public String toString() { return "jump(" + _time + ")"; } }
fix action jump visibility
core/src/main/java/org/mwg/core/task/ActionJump.java
fix action jump visibility
<ide><path>ore/src/main/java/org/mwg/core/task/ActionJump.java <ide> import org.mwg.task.TaskAction; <ide> import org.mwg.task.TaskContext; <ide> <del> <del>public class ActionJump implements TaskAction { <add>class ActionJump implements TaskAction { <ide> private final String _time; <ide> <del> public ActionJump(String time) { <add> ActionJump(String time) { <ide> _time = time; <ide> } <ide>
Java
mit
5942e8cb7cc121712c8593c05a28f94a1b171f5e
0
ctlab/sgmwcs-solver,ctlab/sgmwcs-solver,ctlab/gmwcs-solver
package ru.ifmo.ctddev.gmwcs; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.jgrapht.UndirectedGraph; import ru.ifmo.ctddev.gmwcs.graph.*; import ru.ifmo.ctddev.gmwcs.solver.ComponentSolver; import ru.ifmo.ctddev.gmwcs.solver.RLTSolver; import ru.ifmo.ctddev.gmwcs.solver.SolverException; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.List; import static java.util.Arrays.asList; public class Main { public static OptionSet parseArgs(String args[]) throws IOException { OptionParser optionParser = new OptionParser(); optionParser.allowsUnrecognizedOptions(); optionParser.acceptsAll(asList("h", "help"), "Print a short help message"); OptionSet optionSet = optionParser.parse(args); optionParser.acceptsAll(asList("n", "nodes"), "Node list file").withRequiredArg().required(); optionParser.acceptsAll(asList("e", "edges"), "Edge list file").withRequiredArg().required(); optionParser.acceptsAll(asList("m", "threads"), "Number of threads").withRequiredArg() .ofType(Integer.class).defaultsTo(1); optionParser.acceptsAll(asList("t", "timelimit"), "Timelimit in seconds (<= 0 - unlimited)") .withRequiredArg().ofType(Long.class).defaultsTo(0L); optionParser.acceptsAll(asList("s", "synonyms"), "Synonym list file").withRequiredArg(); optionParser.acceptsAll(asList("r", "root"), "Solve with selected root node").withRequiredArg(); optionParser.acceptsAll(asList("a", "all"), "Write to out files at each found solution"); optionParser.acceptsAll(asList("B", "bruteforce"), "Bruteforce n the most weighted nodes") .withRequiredArg().ofType(Integer.class).defaultsTo(0); optionParser.acceptsAll(asList("b", "break"), "Breaking symmetries"); optionParser.accepts("tune", "Time allocated for each cplex tuning test").withRequiredArg().ofType(Double.class); optionParser.accepts("probe", "Time allocated for cplex probing").withRequiredArg().ofType(Double.class); if (optionSet.has("h")) { optionParser.printHelpOn(System.out); System.exit(0); } try { optionSet = optionParser.parse(args); } catch (Exception e) { System.err.println(e.getMessage()); System.err.println(); optionParser.printHelpOn(System.err); System.exit(1); } return optionSet; } public static void main(String[] args) { OptionSet optionSet = null; try { optionSet = parseArgs(args); } catch (IOException e) { // We can't say anything. Error occurred while printing to stderr. System.exit(2); } long timelimit = (Long) optionSet.valueOf("timelimit"); TimeLimit tl = new TimeLimit(timelimit <= 0 ? Double.POSITIVE_INFINITY : timelimit); int threadsNum = (Integer) optionSet.valueOf("threads"); File nodeFile = new File((String) optionSet.valueOf("nodes")); File edgeFile = new File((String) optionSet.valueOf("edges")); RLTSolver rltSolver = new RLTSolver(optionSet.has("b")); ComponentSolver solver = new ComponentSolver(rltSolver); solver.setBFNum((Integer) optionSet.valueOf("B")); solver.setTimeLimit(tl); rltSolver.setThreadsNum(threadsNum); SimpleIO graphIO = new SimpleIO(nodeFile, new File(nodeFile.toString() + ".out"), edgeFile, new File(edgeFile.toString() + ".out")); LDSU<Unit> synonyms = new LDSU<>(); if (optionSet.has("a")) { rltSolver.setCallback(new WritingCallback(graphIO)); } if (optionSet.has("tune")) { rltSolver.setTuningTime((Double) optionSet.valueOf("tune")); } if (optionSet.has("probe")) { rltSolver.setProbingTime((Double) optionSet.valueOf("probe")); } try { UndirectedGraph<Node, Edge> graph = graphIO.read(); if (optionSet.has("s")) { synonyms = graphIO.getSynonyms(new File((String) optionSet.valueOf("s"))); } else { for (Node node : graph.vertexSet()) { synonyms.add(node); } for (Edge edge : graph.edgeSet()) { synonyms.add(edge); } } if (optionSet.has("r")) { String rootName = (String) optionSet.valueOf("r"); Node root = graphIO.getNode(rootName); if (root == null) { System.err.println("There is no such node, which was chosen as root"); System.exit(1); } solver.setRoot(root); } List<Unit> units = solver.solve(graph, synonyms); graphIO.write(units); } catch (ParseException e) { System.err.println("Couldn't parse input files: " + e.getMessage() + " " + e.getErrorOffset()); } catch (SolverException e) { System.err.println("Error occured while solving:" + e.getMessage()); } catch (IOException e) { System.err.println("Error occurred while reading/writing input/output files"); } } private static class WritingCallback extends RLTSolver.SolutionCallback { private GraphIO graphIO; public WritingCallback(GraphIO graphIO) { this.graphIO = graphIO; } @Override public void main(List<Unit> solution) { try { graphIO.write(solution); } catch (IOException e) { System.err.println("Solution couldn't be written to disk. Input output error occured."); } } } }
src/main/java/ru/ifmo/ctddev/gmwcs/Main.java
package ru.ifmo.ctddev.gmwcs; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.jgrapht.UndirectedGraph; import ru.ifmo.ctddev.gmwcs.graph.*; import ru.ifmo.ctddev.gmwcs.solver.ComponentSolver; import ru.ifmo.ctddev.gmwcs.solver.RLTSolver; import ru.ifmo.ctddev.gmwcs.solver.SolverException; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.List; import static java.util.Arrays.asList; public class Main { public static OptionSet parseArgs(String args[]) throws IOException { OptionParser optionParser = new OptionParser(); optionParser.allowsUnrecognizedOptions(); optionParser.acceptsAll(asList("h", "help"), "Print a short help message"); OptionSet optionSet = optionParser.parse(args); optionParser.acceptsAll(asList("n", "nodes"), "Node list file").withRequiredArg().required(); optionParser.acceptsAll(asList("e", "edges"), "Edge list file").withRequiredArg().required(); optionParser.acceptsAll(asList("m", "threads"), "Number of threads").withRequiredArg() .ofType(Integer.class).defaultsTo(1); optionParser.acceptsAll(asList("t", "timelimit"), "Timelimit in seconds (<= 0 - unlimited)") .withRequiredArg().ofType(Long.class).defaultsTo(0L); optionParser.acceptsAll(asList("s", "synonyms"), "Synonym list file").withRequiredArg(); optionParser.acceptsAll(asList("r", "root"), "Solve with selected root node").withRequiredArg(); optionParser.acceptsAll(asList("a", "all"), "Write to out files at each found solution"); optionParser.acceptsAll(asList("B", "bruteforce"), "Bruteforce n the most weighted nodes") .withRequiredArg().ofType(Integer.class).defaultsTo(0); optionParser.acceptsAll(asList("b", "break"), "Breaking symmetries"); optionParser.accepts("tune", "Time allocated for each cplex tuning test").withRequiredArg().ofType(Double.class); optionParser.accepts("probe", "Time allocated for cplex probing").withRequiredArg().ofType(Double.class); if (optionSet.has("h")) { optionParser.printHelpOn(System.out); System.exit(0); } try { optionSet = optionParser.parse(args); } catch (Exception e) { System.err.println(e.getMessage()); System.err.println(); optionParser.printHelpOn(System.err); System.exit(1); } return optionSet; } public static void main(String[] args) { OptionSet optionSet = null; try { optionSet = parseArgs(args); } catch (IOException e) { // We can't say anything. Error occurred while printing to stderr. System.exit(2); } long timelimit = (Long) optionSet.valueOf("timelimit"); TimeLimit tl = new TimeLimit(timelimit <= 0 ? Double.POSITIVE_INFINITY : timelimit); int threadsNum = (Integer) optionSet.valueOf("threads"); File nodeFile = new File((String) optionSet.valueOf("nodes")); File edgeFile = new File((String) optionSet.valueOf("edges")); RLTSolver rltSolver = new RLTSolver(optionSet.has("b")); ComponentSolver solver = new ComponentSolver(rltSolver); solver.setBFNum((Integer) optionSet.valueOf("B")); solver.setTimeLimit(tl); rltSolver.setThreadsNum(threadsNum); SimpleIO graphIO = new SimpleIO(nodeFile, new File(nodeFile.toString() + ".out"), edgeFile, new File(edgeFile.toString() + ".out")); LDSU<Unit> synonyms = new LDSU<>(); if (optionSet.has("a")) { rltSolver.setCallback(new WritingCallback(graphIO)); } if (optionSet.has("tune")) { rltSolver.setTuningTime((Double) optionSet.valueOf("tune")); } if (optionSet.has("probe")) { rltSolver.setTuningTime((Double) optionSet.valueOf("probe")); } try { UndirectedGraph<Node, Edge> graph = graphIO.read(); if (optionSet.has("s")) { synonyms = graphIO.getSynonyms(new File((String) optionSet.valueOf("s"))); } else { for (Node node : graph.vertexSet()) { synonyms.add(node); } for (Edge edge : graph.edgeSet()) { synonyms.add(edge); } } if (optionSet.has("r")) { String rootName = (String) optionSet.valueOf("r"); Node root = graphIO.getNode(rootName); if (root == null) { System.err.println("There is no such node, which was chosen as root"); System.exit(1); } solver.setRoot(root); } List<Unit> units = solver.solve(graph, synonyms); graphIO.write(units); } catch (ParseException e) { System.err.println("Couldn't parse input files: " + e.getMessage() + " " + e.getErrorOffset()); } catch (SolverException e) { System.err.println("Error occured while solving:" + e.getMessage()); } catch (IOException e) { System.err.println("Error occurred while reading/writing input/output files"); } } private static class WritingCallback extends RLTSolver.SolutionCallback { private GraphIO graphIO; public WritingCallback(GraphIO graphIO) { this.graphIO = graphIO; } @Override public void main(List<Unit> solution) { try { graphIO.write(solution); } catch (IOException e) { System.err.println("Solution couldn't be written to disk. Input output error occured."); } } } }
Bug fixed
src/main/java/ru/ifmo/ctddev/gmwcs/Main.java
Bug fixed
<ide><path>rc/main/java/ru/ifmo/ctddev/gmwcs/Main.java <ide> rltSolver.setTuningTime((Double) optionSet.valueOf("tune")); <ide> } <ide> if (optionSet.has("probe")) { <del> rltSolver.setTuningTime((Double) optionSet.valueOf("probe")); <add> rltSolver.setProbingTime((Double) optionSet.valueOf("probe")); <ide> } <ide> try { <ide> UndirectedGraph<Node, Edge> graph = graphIO.read();
Java
mit
c6191303b29c6db9c3bd07823ed5e0fd977a9779
0
ssyyddnneeyy/ChokingHazard-Iteration2
package Models; import Helpers.Json; import java.util.*; import Helpers.JsonObject; public class JavaPlayer extends Player implements Serializable<JavaPlayer>{ private int famePoints; private int actionPoints; private int developersOffBoard; //private int developersOnBoard; private int numOneRiceTile; private int numOneVillageTile; private int numTwoTile; private int numActionTokens; private ArrayList<PalaceCard> palaceCards; private Developer[] developersOnBoard; private int selectedDeveloperIndex; private Developer[] developerArray; public int currentlySelectedDeveloper; private boolean hasPlacedLandTile; private boolean hasUsedActionToken; public JavaPlayer(String name, String color){ super(name, color); this.famePoints = 0; this.actionPoints = 6; this.developersOffBoard = 12; this.numOneRiceTile = 3; this.numOneVillageTile = 2; this.numTwoTile = 5; this.numActionTokens = 3; this.palaceCards = new ArrayList<PalaceCard>(); this.hasPlacedLandTile = false; this.developersOnBoard = new Developer[12]; this.selectedDeveloperIndex = 0; this.hasUsedActionToken = false; } public int getFamePoints() { return famePoints; } public int getActionPoints() { return actionPoints; } public int getDevelopersOffBoard() { return developersOffBoard; } public int getNumOneRiceTile() { return numOneRiceTile; } public int getNumOneVillageTile() { return numOneVillageTile; } public int getNumTwoTile() { return numTwoTile; } public int getNumActionTokens() { return numActionTokens; } public ArrayList<PalaceCard> getPalaceCards(){ return palaceCards; } public int getAvailableActionPoints(boolean isLandTile) { if (hasPlacedLandTile || isLandTile) { return actionPoints; } return actionPoints - 1; } public void changeFamePoints(int modifier){ famePoints += modifier; } public Developer[] getDevelopersOnBoard() { return developersOnBoard; } //Returns the selected developer if there is a valid option (Developers on the board) public Developer getSelectedDeveloper() { return developersOnBoard[selectedDeveloperIndex]; } //Tabs through the collection of developers on the board. If the index is greater than the //number of developers, the first developer in the list becomes selected public void tabThroughDevelopers() { int count = 0; while (count < developersOnBoard.length) { selectedDeveloperIndex++; if(selectedDeveloperIndex >= developersOnBoard.length) { selectedDeveloperIndex = 0; } if (developersOnBoard[selectedDeveloperIndex] != null) { break; } count++; } } public boolean decrementNActionPoints(int n, boolean isLandTile) { if (getAvailableActionPoints(isLandTile) >= n) { actionPoints -= n; return true; } return false; } public void removeDeveloperFromArray() { developerArray[currentlySelectedDeveloper] = null; } public void addPalaceCard(PalaceCard card){ this.palaceCards.add(card); } //Methods needed from Player controller to validate action selections----------------------------------- public boolean canUsePalace() { //checks if the player has the AP return getAvailableActionPoints(false) > 0; } public boolean canUseRice() { //checks if the player has enough plus has the AP return numOneRiceTile > 0 && getAvailableActionPoints(true) > 0; } public boolean canUseThree() { //checks if the player has the AP return getAvailableActionPoints(false) > 0; } public boolean canUseTwo() { //checks if the player has enough plus has the AP return numTwoTile > 0 && getAvailableActionPoints(true) > 0; } public boolean canUseActionToken() { //checks if the player has not used an action token yet return !hasUsedActionToken; } public boolean canUseIrrigation() { //checks if the player has the AP return getAvailableActionPoints(false) > 0; } public boolean canUseVillage() { //checks if the player has enough plus has the AP return numOneVillageTile > 0 && getAvailableActionPoints(true) > 0; } public boolean canEndTurn() { //checks if the player has placed a land tile return hasPlacedLandTile; } //--------------------------------------------------------------------------------------------------------- @Override public String serialize() { return Json.jsonObject(Json.jsonMembers( Json.jsonPair("name", Json.jsonValue(name + "")), Json.jsonPair("color", Json.jsonValue(color + "")), Json.jsonPair("famePoints", Json.jsonValue(famePoints + "")), Json.jsonPair("actionPoints", Json.jsonValue(actionPoints + "")), Json.jsonPair("numOneRiceTile", Json.jsonValue(numOneRiceTile + "")), Json.jsonPair("numOneVillageTile", Json.jsonValue(numOneVillageTile + "")), Json.jsonPair("numTwoTile", Json.jsonValue(numTwoTile + "")), Json.jsonPair("numActionTokens", Json.jsonValue(numActionTokens + "")), Json.jsonPair("developersOffBoard", Json.jsonValue(developersOffBoard + "")), Json.jsonPair("palaceCards", Json.serializeArray(palaceCards)), Json.jsonPair("developersOnBoard", Json.serializeArray(developersOnBoard)), Json.jsonPair("developerArray", Json.serializeArray(developerArray)), Json.jsonPair("selectedDeveloperIndex", Json.jsonValue(selectedDeveloperIndex + "")), Json.jsonPair("currentlySelectedDeveloper", Json.jsonValue(currentlySelectedDeveloper + "")), Json.jsonPair("hasPlacedLandTile", Json.jsonValue(hasPlacedLandTile + "")), Json.jsonPair("hasUsedActionToken", Json.jsonValue(hasUsedActionToken + "")) )); } @Override public JavaPlayer loadObject(JsonObject json) { this.name = json.getString("name"); this.color = json.getString("color"); this.famePoints = Integer.parseInt(json.getString("famePoints")); this.actionPoints = Integer.parseInt(json.getString("actionPoints")); this.numOneRiceTile = Integer.parseInt(json.getString("numOneRiceTile")); this.numOneVillageTile = Integer.parseInt(json.getString("numOneVillageTile")); this.numTwoTile = Integer.parseInt(json.getString("numTwoTile")); this.numActionTokens = Integer.parseInt(json.getString("numActionTokens")); this.developersOffBoard = Integer.parseInt(json.getString("developersOffBoard")); this.selectedDeveloperIndex = Integer.parseInt(json.getString("selectedDeveloperIndex")); this.currentlySelectedDeveloper = Integer.parseInt(json.getString("currentlySelectedDeveloper")); this.hasPlacedLandTile = Boolean.parseBoolean(json.getString("hasPlacedLandTile")); this.hasUsedActionToken = Boolean.parseBoolean(json.getString("hasUsedActionToken")); this.palaceCards = new ArrayList<PalaceCard>(); for(JsonObject obj : json.getJsonObjectArray("palaceCards")) this.palaceCards.add((new PalaceCard(-1)).loadObject(obj)); this.developersOnBoard = new Developer[json.getJsonObjectArray("developersOnBoard").length]; for(int x = 0; x < this.developersOnBoard.length; ++x) this.developersOnBoard[x] = (new Developer(this)).loadObject(json.getJsonObjectArray("developersOnBoard")[x]); this.developerArray = new Developer[json.getJsonObjectArray("developerArray").length]; for(int x = 0; x < this.developerArray.length; ++x) this.developerArray[x] = (new Developer(this)).loadObject(json.getJsonObjectArray("developerArray")[x]); return this; } }
src/Models/JavaPlayer.java
package Models; import Helpers.Json; import java.util.*; import Helpers.JsonObject; public class JavaPlayer extends Player implements Serializable<JavaPlayer>{ private int famePoints; private int actionPoints; private int developersOffBoard; //private int developersOnBoard; private int numOneRiceTile; private int numOneVillageTile; private int numTwoTile; private int numActionTokens; private ArrayList<PalaceCard> palaceCards; private Developer[] developersOnBoard; private int selectedDeveloperIndex; private Developer[] developerArray; public int currentlySelectedDeveloper; private boolean hasPlacedLandTile; private boolean hasUsedActionToken; public JavaPlayer(String name, String color){ super(name, color); this.famePoints = 0; this.actionPoints = 6; this.developersOffBoard = 12; this.numOneRiceTile = 3; this.numOneVillageTile = 2; this.numTwoTile = 5; this.numActionTokens = 3; this.palaceCards = new ArrayList<PalaceCard>(); this.hasPlacedLandTile = false; this.developersOnBoard = new Developer[12]; this.selectedDeveloperIndex = 0; this.hasUsedActionToken = false; } public int getFamePoints() { return famePoints; } public int getActionPoints() { return actionPoints; } public int getDevelopersOffBoard() { return developersOffBoard; } public int getNumOneRiceTile() { return numOneRiceTile; } public int getNumOneVillageTile() { return numOneVillageTile; } public int getNumTwoTile() { return numTwoTile; } public int getNumActionTokens() { return numActionTokens; } public ArrayList<PalaceCard> getPalaceCards(){ return palaceCards; } public int getAvailableActionPoints(boolean isLandTile) { if (hasPlacedLandTile || isLandTile) { return actionPoints; } return actionPoints - 1; } public void changeFamePoints(int modifier){ famePoints += modifier; } public Developer[] getDevelopersOnBoard() { return developersOnBoard; } //Returns the selected developer if there is a valid option (Developers on the board) public Developer getSelectedDeveloper() { return developersOnBoard[selectedDeveloperIndex]; } //Tabs through the collection of developers on the board. If the index is greater than the //number of developers, the first developer in the list becomes selected public void tabThroughDevelopers() { int count = 0; while (count < developersOnBoard.length) { selectedDeveloperIndex++; if(selectedDeveloperIndex >= developersOnBoard.length) { selectedDeveloperIndex = 0; } if (developersOnBoard[selectedDeveloperIndex] != null) { break; } count++; } } public boolean decrementNActionPoints(int n, boolean isLandTile) { if (getAvailableActionPoints(isLandTile) >= n) { actionPoints -= n; return true; } return false; } public void removeDeveloperFromArray() { developerArray[currentlySelectedDeveloper] = null; } public void addPalaceCard(PalaceCard card){ this.palaceCards.add(card); } //Methods needed from Player controller to validate action selections----------------------------------- public boolean canUsePalace() { //checks if the player has the AP return getAvailableActionPoints(false) > 0; } public boolean canUseRice() { //checks if the player has enough plus has the AP return numOneRiceTile > 0 && getAvailableActionPoints(true) > 0; } public boolean canUseThree() { //checks if the player has the AP return getAvailableActionPoints(false) > 0; } public boolean canUseTwo() { //checks if the player has enough plus has the AP return numTwoTile > 0 && getAvailableActionPoints(true) > 0; } public boolean canUseActionToken() { //checks if the player has not used an action token yet return !hasUsedActionToken; } public boolean canUseIrrigation() { //checks if the player has the AP return getAvailableActionPoints(false) > 0; } public boolean canUseVillage() { //checks if the player has enough plus has the AP return numOneVillageTile > 0 && getAvailableActionPoints(true) > 0; } public boolean canEndTurn() { //checks if the player has placed a land tile return hasPlacedLandTile; } //--------------------------------------------------------------------------------------------------------- @Override public String serialize() { return Json.jsonObject(Json.jsonMembers( Json.jsonPair("name", Json.jsonValue(name + "")), Json.jsonPair("color", Json.jsonValue(color + "")), Json.jsonPair("famePoints", Json.jsonValue(famePoints + "")), Json.jsonPair("actionPoints", Json.jsonValue(actionPoints + "")), Json.jsonPair("numOneRiceTile", Json.jsonValue(numOneRiceTile + "")), Json.jsonPair("numOneVillageTile", Json.jsonValue(numOneVillageTile + "")), Json.jsonPair("numTwoTile", Json.jsonValue(numTwoTile + "")), Json.jsonPair("numActionTokens", Json.jsonValue(numActionTokens + "")), Json.jsonPair("developersOffBoard", Json.jsonValue(developersOffBoard + "")), Json.jsonPair("palaceCards", Json.serializeArray(palaceCards)), Json.jsonPair("developersOnBoard", Json.serializeArray(developersOnBoard)), Json.jsonPair("developerArray", Json.serializeArray(developerArray)), Json.jsonPair("selectedDeveloperIndex", Json.jsonValue(selectedDeveloperIndex + "")), Json.jsonPair("currentlySelectedDeveloper", Json.jsonValue(currentlySelectedDeveloper + "")), Json.jsonPair("placedLandTile", Json.jsonValue(hasPlacedLandTile + "")) )); } @Override public JavaPlayer loadObject(JsonObject json) { // TODO Auto-generated method stub return this; } }
JavaPlayer save
src/Models/JavaPlayer.java
JavaPlayer save
<ide><path>rc/Models/JavaPlayer.java <ide> Json.jsonPair("developerArray", Json.serializeArray(developerArray)), <ide> Json.jsonPair("selectedDeveloperIndex", Json.jsonValue(selectedDeveloperIndex + "")), <ide> Json.jsonPair("currentlySelectedDeveloper", Json.jsonValue(currentlySelectedDeveloper + "")), <del> Json.jsonPair("placedLandTile", Json.jsonValue(hasPlacedLandTile + "")) <add> Json.jsonPair("hasPlacedLandTile", Json.jsonValue(hasPlacedLandTile + "")), <add> Json.jsonPair("hasUsedActionToken", Json.jsonValue(hasUsedActionToken + "")) <ide> )); <ide> } <ide> <ide> @Override <ide> public JavaPlayer loadObject(JsonObject json) { <del> <del> // TODO Auto-generated method stub <add> this.name = json.getString("name"); <add> this.color = json.getString("color"); <add> this.famePoints = Integer.parseInt(json.getString("famePoints")); <add> this.actionPoints = Integer.parseInt(json.getString("actionPoints")); <add> this.numOneRiceTile = Integer.parseInt(json.getString("numOneRiceTile")); <add> this.numOneVillageTile = Integer.parseInt(json.getString("numOneVillageTile")); <add> this.numTwoTile = Integer.parseInt(json.getString("numTwoTile")); <add> this.numActionTokens = Integer.parseInt(json.getString("numActionTokens")); <add> this.developersOffBoard = Integer.parseInt(json.getString("developersOffBoard")); <add> this.selectedDeveloperIndex = Integer.parseInt(json.getString("selectedDeveloperIndex")); <add> this.currentlySelectedDeveloper = Integer.parseInt(json.getString("currentlySelectedDeveloper")); <add> this.hasPlacedLandTile = Boolean.parseBoolean(json.getString("hasPlacedLandTile")); <add> this.hasUsedActionToken = Boolean.parseBoolean(json.getString("hasUsedActionToken")); <add> <add> this.palaceCards = new ArrayList<PalaceCard>(); <add> for(JsonObject obj : json.getJsonObjectArray("palaceCards")) <add> this.palaceCards.add((new PalaceCard(-1)).loadObject(obj)); <add> <add> this.developersOnBoard = new Developer[json.getJsonObjectArray("developersOnBoard").length]; <add> for(int x = 0; x < this.developersOnBoard.length; ++x) <add> this.developersOnBoard[x] = (new Developer(this)).loadObject(json.getJsonObjectArray("developersOnBoard")[x]); <add> <add> this.developerArray = new Developer[json.getJsonObjectArray("developerArray").length]; <add> for(int x = 0; x < this.developerArray.length; ++x) <add> this.developerArray[x] = (new Developer(this)).loadObject(json.getJsonObjectArray("developerArray")[x]); <add> <ide> return this; <ide> } <ide> }
Java
apache-2.0
86821d53df72492a3d10cd15f817672602045bd9
0
puppetlabs/trapperkeeper-webserver-jetty9,puppetlabs/trapperkeeper-webserver-jetty9
package com.puppetlabs.trapperkeeper.services.webserver.jetty9.utils; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.security.CertificateUtils; import org.eclipse.jetty.util.ssl.SslContextFactory; import java.io.File; import java.security.cert.CRL; import java.util.Collection; import java.util.function.Consumer; public class InternalSslContextFactory extends SslContextFactory { private static int maxTries = 5; private static int sleepInMillisecondsBetweenTries = 1000; private static final Logger LOG = Log.getLogger(InternalSslContextFactory.class); private static Consumer<SslContextFactory> consumer = sslContextFactory -> {}; private Collection<? extends CRL> _crls; @Override protected Collection<? extends CRL> loadCRL(String crlPath) throws Exception { Collection<? extends CRL> crls; synchronized (this) { if (_crls == null) { crls = super.loadCRL(crlPath); } else { crls = _crls; } } return crls; } public void reload() throws Exception { synchronized (this) { Exception reloadEx = null; int tries = maxTries; String crlPath = getCrlPath(); if (crlPath != null) { File crlPathAsFile = new File(crlPath); long crlLastModified = crlPathAsFile.lastModified(); // Try to parse CRLs from the crlPath until it is successful // or a hard-coded number of failed attempts have been made. do { reloadEx = null; try { _crls = CertificateUtils.loadCRL(crlPath); } catch (Exception e) { reloadEx = e; // If the CRL file has been updated since the last reload // attempt, reset the retry counter. if (crlPathAsFile != null && crlLastModified != crlPathAsFile.lastModified()) { crlLastModified = crlPathAsFile.lastModified(); tries = maxTries; } else { tries--; } if (tries == 0) { LOG.warn("Failed ssl context reload after " + maxTries + " tries. CRL file is: " + crlPath, reloadEx); } else { Thread.sleep(sleepInMillisecondsBetweenTries); } } } while (reloadEx != null && tries > 0); } if (reloadEx == null) { reload(consumer); } } } }
java/com/puppetlabs/trapperkeeper/services/webserver/jetty9/utils/InternalSslContextFactory.java
package com.puppetlabs.trapperkeeper.services.webserver.jetty9.utils; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.security.CertificateUtils; import org.eclipse.jetty.util.ssl.SslContextFactory; import java.io.File; import java.security.cert.CRL; import java.util.Collection; import java.util.function.Consumer; public class InternalSslContextFactory extends SslContextFactory { private static int maxTries = 5; private static int sleepInMillisecondsBetweenTries = 1000; private static final Logger LOG = Log.getLogger(InternalSslContextFactory.class); private static Consumer<SslContextFactory> consumer = sslContextFactory -> {}; private Collection<? extends CRL> _crls; @Override protected Collection<? extends CRL> loadCRL(String crlPath) throws Exception { Collection<? extends CRL> crls; synchronized (this) { if (_crls == null) { crls = super.loadCRL(crlPath); } else { crls = _crls; } } return crls; } public void reload() throws Exception { synchronized (this) { Exception reloadEx; int tries = maxTries; String crlPath = getCrlPath(); File crlPathAsFile = null; long crlLastModified = 0; if (crlPath != null) { crlPathAsFile = new File(crlPath); crlLastModified = crlPathAsFile.lastModified(); } // Try to parse CRLs from the crlPath until it is successful // or a hard-coded number of failed attempts have been made. do { reloadEx = null; try { _crls = CertificateUtils.loadCRL(crlPath); } catch (Exception e) { reloadEx = e; // If the CRL file has been updated since the last reload // attempt, reset the retry counter. if (crlPathAsFile != null && crlLastModified != crlPathAsFile.lastModified()) { crlLastModified = crlPathAsFile.lastModified(); tries = maxTries; } else { tries--; } if (tries == 0) { LOG.warn("Failed ssl context reload after " + maxTries + " tries. CRL file is: " + crlPath, reloadEx); } else { Thread.sleep(sleepInMillisecondsBetweenTries); } } } while (reloadEx != null && tries > 0); if (reloadEx == null) { reload(consumer); } } } }
(TK-149) Avoid reloading crl if crlPath is null If the crlPath is null on the SSLContext, don't try to reload the crl file from disk.
java/com/puppetlabs/trapperkeeper/services/webserver/jetty9/utils/InternalSslContextFactory.java
(TK-149) Avoid reloading crl if crlPath is null
<ide><path>ava/com/puppetlabs/trapperkeeper/services/webserver/jetty9/utils/InternalSslContextFactory.java <ide> <ide> public void reload() throws Exception { <ide> synchronized (this) { <del> Exception reloadEx; <add> Exception reloadEx = null; <ide> int tries = maxTries; <ide> String crlPath = getCrlPath(); <del> File crlPathAsFile = null; <del> long crlLastModified = 0; <ide> <ide> if (crlPath != null) { <del> crlPathAsFile = new File(crlPath); <del> crlLastModified = crlPathAsFile.lastModified(); <add> File crlPathAsFile = new File(crlPath); <add> long crlLastModified = crlPathAsFile.lastModified(); <add> <add> // Try to parse CRLs from the crlPath until it is successful <add> // or a hard-coded number of failed attempts have been made. <add> do { <add> reloadEx = null; <add> try { <add> _crls = CertificateUtils.loadCRL(crlPath); <add> } catch (Exception e) { <add> reloadEx = e; <add> <add> // If the CRL file has been updated since the last reload <add> // attempt, reset the retry counter. <add> if (crlPathAsFile != null && <add> crlLastModified != crlPathAsFile.lastModified()) { <add> crlLastModified = crlPathAsFile.lastModified(); <add> tries = maxTries; <add> } else { <add> tries--; <add> } <add> <add> if (tries == 0) { <add> LOG.warn("Failed ssl context reload after " + <add> maxTries + " tries. CRL file is: " + <add> crlPath, reloadEx); <add> } else { <add> Thread.sleep(sleepInMillisecondsBetweenTries); <add> } <add> } <add> } while (reloadEx != null && tries > 0); <ide> } <del> <del> // Try to parse CRLs from the crlPath until it is successful <del> // or a hard-coded number of failed attempts have been made. <del> do { <del> reloadEx = null; <del> try { <del> _crls = CertificateUtils.loadCRL(crlPath); <del> } catch (Exception e) { <del> reloadEx = e; <del> <del> // If the CRL file has been updated since the last reload <del> // attempt, reset the retry counter. <del> if (crlPathAsFile != null && <del> crlLastModified != crlPathAsFile.lastModified()) { <del> crlLastModified = crlPathAsFile.lastModified(); <del> tries = maxTries; <del> } else { <del> tries--; <del> } <del> <del> if (tries == 0) { <del> LOG.warn("Failed ssl context reload after " + <del> maxTries + " tries. CRL file is: " + <del> crlPath, reloadEx); <del> } else { <del> Thread.sleep(sleepInMillisecondsBetweenTries); <del> } <del> } <del> } while (reloadEx != null && tries > 0); <ide> <ide> if (reloadEx == null) { <ide> reload(consumer);
Java
mit
5d6389249aa9189a2acba1814db0d772786da641
0
lucko/LuckPerms
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.luckperms.common.api.implementation; import com.google.common.collect.ImmutableListMultimap; import me.lucko.luckperms.common.api.ApiUtils; import me.lucko.luckperms.common.model.Group; import me.lucko.luckperms.common.model.manager.group.GroupManager; import me.lucko.luckperms.common.node.matcher.ConstraintNodeMatcher; import me.lucko.luckperms.common.node.matcher.StandardNodeMatchers; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.storage.misc.NodeEntry; import me.lucko.luckperms.common.util.ImmutableCollectors; import net.luckperms.api.event.cause.CreationCause; import net.luckperms.api.event.cause.DeletionCause; import net.luckperms.api.node.HeldNode; import net.luckperms.api.node.Node; import net.luckperms.api.node.matcher.NodeMatcher; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; public class ApiGroupManager extends ApiAbstractManager<Group, net.luckperms.api.model.group.Group, GroupManager<?>> implements net.luckperms.api.model.group.GroupManager { public ApiGroupManager(LuckPermsPlugin plugin, GroupManager<?> handle) { super(plugin, handle); } @Override protected net.luckperms.api.model.group.Group proxy(me.lucko.luckperms.common.model.Group internal) { return internal == null ? null : internal.getApiProxy(); } @Override public @NonNull CompletableFuture<net.luckperms.api.model.group.Group> createAndLoadGroup(@NonNull String name) { name = ApiUtils.checkName(Objects.requireNonNull(name, "name")); return this.plugin.getStorage().createAndLoadGroup(name, CreationCause.API) .thenApply(this::proxy); } @Override public @NonNull CompletableFuture<Optional<net.luckperms.api.model.group.Group>> loadGroup(@NonNull String name) { name = ApiUtils.checkName(Objects.requireNonNull(name, "name")); return this.plugin.getStorage().loadGroup(name).thenApply(opt -> opt.map(this::proxy)); } @Override public @NonNull CompletableFuture<Void> saveGroup(net.luckperms.api.model.group.@NonNull Group group) { Objects.requireNonNull(group, "group"); return this.plugin.getStorage().saveGroup(ApiGroup.cast(group)); } @Override public @NonNull CompletableFuture<Void> deleteGroup(net.luckperms.api.model.group.@NonNull Group group) { Objects.requireNonNull(group, "group"); if (group.getName().equalsIgnoreCase(GroupManager.DEFAULT_GROUP_NAME)) { throw new IllegalArgumentException("Cannot delete the default group."); } return this.plugin.getStorage().deleteGroup(ApiGroup.cast(group), DeletionCause.API); } @Override public @NonNull CompletableFuture<Void> modifyGroup(@NonNull String name, @NonNull Consumer<? super net.luckperms.api.model.group.Group> action) { Objects.requireNonNull(name, "name"); Objects.requireNonNull(action, "action"); return this.plugin.getStorage().createAndLoadGroup(name, CreationCause.API) .thenApplyAsync(group -> { action.accept(group.getApiProxy()); return group; }, this.plugin.getBootstrap().getScheduler().async()) .thenCompose(group -> this.plugin.getStorage().saveGroup(group)); } @Override public @NonNull CompletableFuture<Void> loadAllGroups() { return this.plugin.getStorage().loadAllGroups(); } @SuppressWarnings({"unchecked", "rawtypes"}) @Override @Deprecated public @NonNull CompletableFuture<List<HeldNode<String>>> getWithPermission(@NonNull String permission) { Objects.requireNonNull(permission, "permission"); return (CompletableFuture) this.plugin.getStorage().getGroupsWithPermission(StandardNodeMatchers.key(permission)); } @SuppressWarnings("unchecked") @Override public @NonNull <T extends Node> CompletableFuture<Map<String, Collection<T>>> searchAll(@NonNull NodeMatcher<? extends T> matcher) { Objects.requireNonNull(matcher, "matcher"); ConstraintNodeMatcher<? extends T> constraint = (ConstraintNodeMatcher<? extends T>) matcher; return this.plugin.getStorage().getGroupsWithPermission(constraint).thenApply(list -> { ImmutableListMultimap.Builder<String, T> builder = ImmutableListMultimap.builder(); for (NodeEntry<String, ? extends T> row : list) { builder.put(row.getHolder(), row.getNode()); } return builder.build().asMap(); }); } @Override public net.luckperms.api.model.group.Group getGroup(@NonNull String name) { Objects.requireNonNull(name, "name"); return proxy(this.handle.getIfLoaded(name)); } @Override public @NonNull Set<net.luckperms.api.model.group.Group> getLoadedGroups() { return this.handle.getAll().values().stream() .map(this::proxy) .collect(ImmutableCollectors.toSet()); } @Override public boolean isLoaded(@NonNull String name) { Objects.requireNonNull(name, "name"); return this.handle.isLoaded(name); } }
common/src/main/java/me/lucko/luckperms/common/api/implementation/ApiGroupManager.java
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.luckperms.common.api.implementation; import com.google.common.collect.ImmutableListMultimap; import me.lucko.luckperms.common.api.ApiUtils; import me.lucko.luckperms.common.model.Group; import me.lucko.luckperms.common.model.manager.group.GroupManager; import me.lucko.luckperms.common.node.matcher.ConstraintNodeMatcher; import me.lucko.luckperms.common.node.matcher.StandardNodeMatchers; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; import me.lucko.luckperms.common.storage.misc.NodeEntry; import me.lucko.luckperms.common.util.ImmutableCollectors; import net.luckperms.api.event.cause.CreationCause; import net.luckperms.api.event.cause.DeletionCause; import net.luckperms.api.node.HeldNode; import net.luckperms.api.node.Node; import net.luckperms.api.node.matcher.NodeMatcher; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; public class ApiGroupManager extends ApiAbstractManager<Group, net.luckperms.api.model.group.Group, GroupManager<?>> implements net.luckperms.api.model.group.GroupManager { public ApiGroupManager(LuckPermsPlugin plugin, GroupManager<?> handle) { super(plugin, handle); } @Override protected net.luckperms.api.model.group.Group proxy(me.lucko.luckperms.common.model.Group internal) { return internal == null ? null : internal.getApiProxy(); } @Override public @NonNull CompletableFuture<net.luckperms.api.model.group.Group> createAndLoadGroup(@NonNull String name) { name = ApiUtils.checkName(Objects.requireNonNull(name, "name")); return this.plugin.getStorage().createAndLoadGroup(name, CreationCause.API) .thenApply(this::proxy); } @Override public @NonNull CompletableFuture<Optional<net.luckperms.api.model.group.Group>> loadGroup(@NonNull String name) { name = ApiUtils.checkName(Objects.requireNonNull(name, "name")); return this.plugin.getStorage().loadGroup(name).thenApply(opt -> opt.map(this::proxy)); } @Override public @NonNull CompletableFuture<Void> saveGroup(net.luckperms.api.model.group.@NonNull Group group) { Objects.requireNonNull(group, "group"); return this.plugin.getStorage().saveGroup(ApiGroup.cast(group)); } @Override public @NonNull CompletableFuture<Void> deleteGroup(net.luckperms.api.model.group.@NonNull Group group) { Objects.requireNonNull(group, "group"); if (group.getName().equalsIgnoreCase(GroupManager.DEFAULT_GROUP_NAME)) { throw new IllegalArgumentException("Cannot delete the default group."); } return this.plugin.getStorage().deleteGroup(ApiGroup.cast(group), DeletionCause.API); } @Override public @NonNull CompletableFuture<Void> modifyGroup(@NonNull String name, @NonNull Consumer<? super net.luckperms.api.model.group.Group> action) { Objects.requireNonNull(name, "name"); Objects.requireNonNull(action, "action"); return this.plugin.getStorage().createAndLoadGroup(name, CreationCause.API) .thenApplyAsync(group -> { action.accept(group.getApiProxy()); return group; }, this.plugin.getBootstrap().getScheduler().async()) .thenCompose(group -> this.plugin.getStorage().saveGroup(group)); } @Override public @NonNull CompletableFuture<Void> loadAllGroups() { return this.plugin.getStorage().loadAllGroups(); } @SuppressWarnings({"unchecked", "rawtypes"}) @Override @Deprecated public @NonNull CompletableFuture<List<HeldNode<String>>> getWithPermission(@NonNull String permission) { Objects.requireNonNull(permission, "permission"); return (CompletableFuture) this.plugin.getStorage().getUsersWithPermission(StandardNodeMatchers.key(permission)); } @SuppressWarnings("unchecked") @Override public @NonNull <T extends Node> CompletableFuture<Map<String, Collection<T>>> searchAll(@NonNull NodeMatcher<? extends T> matcher) { Objects.requireNonNull(matcher, "matcher"); ConstraintNodeMatcher<? extends T> constraint = (ConstraintNodeMatcher<? extends T>) matcher; return this.plugin.getStorage().getGroupsWithPermission(constraint).thenApply(list -> { ImmutableListMultimap.Builder<String, T> builder = ImmutableListMultimap.builder(); for (NodeEntry<String, ? extends T> row : list) { builder.put(row.getHolder(), row.getNode()); } return builder.build().asMap(); }); } @Override public net.luckperms.api.model.group.Group getGroup(@NonNull String name) { Objects.requireNonNull(name, "name"); return proxy(this.handle.getIfLoaded(name)); } @Override public @NonNull Set<net.luckperms.api.model.group.Group> getLoadedGroups() { return this.handle.getAll().values().stream() .map(this::proxy) .collect(ImmutableCollectors.toSet()); } @Override public boolean isLoaded(@NonNull String name) { Objects.requireNonNull(name, "name"); return this.handle.isLoaded(name); } }
Fix bug with searching for group permissions via the api
common/src/main/java/me/lucko/luckperms/common/api/implementation/ApiGroupManager.java
Fix bug with searching for group permissions via the api
<ide><path>ommon/src/main/java/me/lucko/luckperms/common/api/implementation/ApiGroupManager.java <ide> @Deprecated <ide> public @NonNull CompletableFuture<List<HeldNode<String>>> getWithPermission(@NonNull String permission) { <ide> Objects.requireNonNull(permission, "permission"); <del> return (CompletableFuture) this.plugin.getStorage().getUsersWithPermission(StandardNodeMatchers.key(permission)); <add> return (CompletableFuture) this.plugin.getStorage().getGroupsWithPermission(StandardNodeMatchers.key(permission)); <ide> } <ide> <ide> @SuppressWarnings("unchecked")
JavaScript
mit
c3ced161ef7b2ef1c30a09104ef583421f9f3d00
0
patternfly/patternfly-org
import React from 'react'; import { graphql } from 'gatsby'; import { Alert, PageSection, PageSectionVariants } from '@patternfly/react-core'; import AutoLinkHeader from '@content/AutoLinkHeader'; import { MDXProvider } from '@mdx-js/react'; import { MDXRenderer } from '../components/mdx-renderer'; import SideNav from '../components/_react/Documentation/SideNav'; import Section from '../components/section'; import LiveEdit from '../components/_react/liveEdit'; import Layout from '../components/layout'; import SEO from '../components/seo'; import Tokens from '../components/css-variables'; import PropsTable from '../components/_react/propsTable'; import './template.scss'; import './gettingStarted.scss'; import '../styles/content/spacers.scss'; import '../styles/content/colors.scss'; const components = { code: class LiveEditWrapper extends React.Component { render() { return ( <LiveEdit scope={this.getScope()} className={this.props.className}> {this.props.children} </LiveEdit> ); } }, pre: React.Fragment, p: props => <p {...props} style={{ marginBottom: '16px' }} /> }; for (let i = 1; i <= 6; i++) { components[`h${i}`] = props => { let inner = props.children.length > 0 ? props.children[1] : props.children; return ( <AutoLinkHeader className="ws-linked-heading" is="h2" {...props}> {inner} </AutoLinkHeader> ); }; } const getWarning = state => { switch(state) { case 'early': return "This is an experimental feature in the early stages of testing. It's not intended for production use."; case 'deprecated': return "This experimental feature has been deprecated and will be removed in a future release. We recommend you avoid or move away from using this feature in your projects."; default: return ( <React.Fragment> This experimental feature has been promoted to a <a href={`../../components/${state}`}>production-level component</a> and will be removed in a future release. Use the production-ready version of this feature instead." </React.Fragment> ); } } const MdxPF4Template = ({ data }) => { const { cssPrefix, stage } = data.mdx.frontmatter; const { optIn } = data.mdx.fields; let section = data.mdx.frontmatter.section; if (!section) section = 'component'; const hasProps = data.props && data.props.nodes && data.props.nodes.length > 0; return ( <Layout sideNav={<SideNav />} className="ws-documentation"> <SEO title="React" /> <PageSection variant={PageSectionVariants.light} className="section-border pf-site-background-medium"> <AutoLinkHeader size="md" is="h1" className="pf4-site-framework-title">React</AutoLinkHeader> <AutoLinkHeader size="4xl" is="h2" suffix="-title" className="pf-u-mt-sm pf-u-mb-md"> {data.mdx.frontmatter.title} </AutoLinkHeader> {optIn && ( <Alert variant="info" title="Opt-in feature" className="pf-u-my-md" isInline > {optIn} </Alert> )} {stage && ( <Alert variant={stage === 'early' ? 'info' : 'warning'} title="Experimental feature" className="pf-u-my-md" style={{ marginBottom: 'var(--pf-global--spacer--md)' }} isInline > {getWarning(stage)} </Alert> )} {data.description && ( <Section> <MDXRenderer>{data.description.code.body}</MDXRenderer> </Section> )} <Section> <AutoLinkHeader anchorOnly className="pf-site-toc"> Examples </AutoLinkHeader> {hasProps && ( <AutoLinkHeader anchorOnly className="pf-site-toc"> Props </AutoLinkHeader> )} {cssPrefix && ( <AutoLinkHeader anchorOnly className="pf-site-toc"> CSS variables </AutoLinkHeader> )} </Section> <Section title="Examples" headingLevel="h2"> <Section className="ws-live-demo"> <MDXProvider components={components}> <MDXRenderer>{data.mdx.code.body}</MDXRenderer> </MDXProvider> </Section> </Section> </PageSection> {hasProps && ( <PageSection> <Section title="Props" headingLevel="h2"> {data.props.nodes.map(component => ( <PropsTable name={component.name} description={component.description} props={component.props} /> ))} </Section> </PageSection> )} {cssPrefix && ( <PageSection variant={PageSectionVariants.light} className="pf-site-background-medium"> <Section title="CSS variables" headingLevel="h3"> <Tokens variables={cssPrefix} /> </Section> </PageSection> )} </Layout> ); }; // Test queries in http://localhost:8000/___graphql // See how to filter from: https://www.gatsbyjs.org/docs/graphql-reference/ // We want the markdown from gatsby-mdx // We want component metadata from gatsby-transformer-react-docgen-typescript // for ALL components in that folder export const pageQuery = graphql` query GetComponent($fileAbsolutePath: String!, $propComponents: [String]!, $reactUrl: String!, $pathRegex: String!) { mdx(fileAbsolutePath: { eq: $fileAbsolutePath }) { code { body } frontmatter { title section cssPrefix stage } fields { optIn } } props: allComponentMetadata(filter: { name: { in: $propComponents }, path: { regex: $pathRegex } }) { nodes { path name description props { name description required type { name } tsType { name raw } defaultValue { value } } } } description: mdx(frontmatter: { reactUrl: { eq: $reactUrl } }) { code { body } } allGetStartedNavigationJson { edges { node { text path } } } allDesignGuidelinesNavigationJson { edges { node { text path subNav { text path } } } } } `; export default MdxPF4Template;
packages/patternfly-4/src/templates/mdxPF4Template.js
import React from 'react'; import { graphql } from 'gatsby'; import { Alert, PageSection, PageSectionVariants } from '@patternfly/react-core'; import AutoLinkHeader from '@content/AutoLinkHeader'; import { MDXProvider } from '@mdx-js/react'; import { MDXRenderer } from '../components/mdx-renderer'; import SideNav from '../components/_react/Documentation/SideNav'; import Section from '../components/section'; import LiveEdit from '../components/_react/liveEdit'; import Layout from '../components/layout'; import SEO from '../components/seo'; import Tokens from '../components/css-variables'; import PropsTable from '../components/_react/propsTable'; import './template.scss'; import './gettingStarted.scss'; import '../styles/content/spacers.scss'; import '../styles/content/colors.scss'; const components = { code: class LiveEditWrapper extends React.Component { render() { return ( <LiveEdit scope={this.getScope()} className={this.props.className}> {this.props.children} </LiveEdit> ); } }, pre: React.Fragment }; for (let i = 1; i <= 6; i++) { components[`h${i}`] = props => { let inner = props.children.length > 0 ? props.children[1] : props.children; return ( <AutoLinkHeader className="ws-linked-heading" is="h2" {...props}> {inner} </AutoLinkHeader> ); }; } const getWarning = state => { switch(state) { case 'early': return "This is an experimental feature in the early stages of testing. It's not intended for production use."; case 'deprecated': return "This experimental feature has been deprecated and will be removed in a future release. We recommend you avoid or move away from using this feature in your projects."; default: return ( <React.Fragment> This experimental feature has been promoted to a <a href={`../../components/${state}`}>production-level component</a> and will be removed in a future release. Use the production-ready version of this feature instead." </React.Fragment> ); } } const MdxPF4Template = ({ data }) => { const { cssPrefix, stage } = data.mdx.frontmatter; const { optIn } = data.mdx.fields; let section = data.mdx.frontmatter.section; if (!section) section = 'component'; const hasProps = data.props && data.props.nodes && data.props.nodes.length > 0; return ( <Layout sideNav={<SideNav />} className="ws-documentation"> <SEO title="React" /> <PageSection variant={PageSectionVariants.light} className="section-border pf-site-background-medium"> <AutoLinkHeader size="md" is="h1" className="pf4-site-framework-title">React</AutoLinkHeader> <AutoLinkHeader size="4xl" is="h2" suffix="-title" className="pf-u-mt-sm pf-u-mb-md"> {data.mdx.frontmatter.title} </AutoLinkHeader> {optIn && ( <Alert variant="info" title="Opt-in feature" className="pf-u-my-md" isInline > {optIn} </Alert> )} {stage && ( <Alert variant={stage === 'early' ? 'info' : 'warning'} title="Experimental feature" className="pf-u-my-md" style={{ marginBottom: 'var(--pf-global--spacer--md)' }} isInline > {getWarning(stage)} </Alert> )} {data.description && ( <Section> <MDXRenderer>{data.description.code.body}</MDXRenderer> </Section> )} <Section> <AutoLinkHeader anchorOnly className="pf-site-toc"> Examples </AutoLinkHeader> {hasProps && ( <AutoLinkHeader anchorOnly className="pf-site-toc"> Props </AutoLinkHeader> )} {cssPrefix && ( <AutoLinkHeader anchorOnly className="pf-site-toc"> CSS variables </AutoLinkHeader> )} </Section> <Section title="Examples" headingLevel="h2"> <Section className="ws-live-demo"> <MDXProvider components={components}> <MDXRenderer>{data.mdx.code.body}</MDXRenderer> </MDXProvider> </Section> </Section> </PageSection> {hasProps && ( <PageSection> <Section title="Props" headingLevel="h2"> {data.props.nodes.map(component => ( <PropsTable name={component.name} description={component.description} props={component.props} /> ))} </Section> </PageSection> )} {cssPrefix && ( <PageSection variant={PageSectionVariants.light} className="pf-site-background-medium"> <Section title="CSS variables" headingLevel="h3"> <Tokens variables={cssPrefix} /> </Section> </PageSection> )} </Layout> ); }; // Test queries in http://localhost:8000/___graphql // See how to filter from: https://www.gatsbyjs.org/docs/graphql-reference/ // We want the markdown from gatsby-mdx // We want component metadata from gatsby-transformer-react-docgen-typescript // for ALL components in that folder export const pageQuery = graphql` query GetComponent($fileAbsolutePath: String!, $propComponents: [String]!, $reactUrl: String!, $pathRegex: String!) { mdx(fileAbsolutePath: { eq: $fileAbsolutePath }) { code { body } frontmatter { title section cssPrefix stage } fields { optIn } } props: allComponentMetadata(filter: { name: { in: $propComponents }, path: { regex: $pathRegex } }) { nodes { path name description props { name description required type { name } tsType { name raw } defaultValue { value } } } } description: mdx(frontmatter: { reactUrl: { eq: $reactUrl } }) { code { body } } allGetStartedNavigationJson { edges { node { text path } } } allDesignGuidelinesNavigationJson { edges { node { text path subNav { text path } } } } } `; export default MdxPF4Template;
add paragraph spacing (#1496)
packages/patternfly-4/src/templates/mdxPF4Template.js
add paragraph spacing (#1496)
<ide><path>ackages/patternfly-4/src/templates/mdxPF4Template.js <ide> ); <ide> } <ide> }, <del> pre: React.Fragment <add> pre: React.Fragment, <add> p: props => <p {...props} style={{ marginBottom: '16px' }} /> <ide> }; <ide> for (let i = 1; i <= 6; i++) { <ide> components[`h${i}`] = props => {
JavaScript
mit
78af3c7bd0570bf0a1700ff668241a7c96765d85
0
Kenishi/BroadSpot,Kenishi/BroadSpot
var app = angular.module('hostControlApp', []); app.controller('hostCtrl', function($scope) { $scope.playlistName = "defaultPlaylistName"; $scope.playlist = []; $scope.hostPlaylists = []; $scope.banned = []; $scope.banModalData = {}; $scope.partyCode = "12345"; $scope.powered = true; $scope.testLoadPlaylist = function() { $scope.playlist = [ {ipaddr: "localhost", artist: "Joey", title : "Play that funky music", album:"Nomans Land", id: "songid1"}, {ipaddr: "64.29.124.255", artist : "Bobby Joe", title: "Fire fire fire", album: "Steal this", id: "songig2"} ]; console.log($scope.playlist.length); }; $scope.connect = function() { window.socket = io('//'); window.socket.on('connect_error', function(data) { console.log("Connection error: "); console.log(data); if(data.description === 404) { window.socket = null; } }); window.socket.on('updateBanList', $scope.updateBanList); window.socket.on('updateCode', $scope.updateCode); window.socket.on('updateLists', $scope.updateLists); window.socket.on('updatePlaylist', $scope.updatePlaylist); window.socket.on('updatePowerState', $scope.updatePowerState); window.socket.on('reconnecting', $scope.reconnecting); window.socket.on('reconnect', $scope.reconnected); }; /************************ Admin Modal Button Methods *************************/ $scope.showClearListWarning = function() { $("#clearListModal").modal(); }; $scope.showBanList = function() { $("#banLoading").toggleClass("hidden", false); $("#banListModal").modal(); var data = [{ ipaddr : "244.12.324.12" }, { ipaddr : "85.241.23.0" }, { ipaddr : "128.0.0.1" }]; //window.socket.emit('getBanList'); setTimeout(function() { $scope.updateBanList(data); }, 2000); }; $scope.showCopyList = function() { $("#listLoading").toggleClass("hidden", false); //window.socket.emit('getPlaylists'); var data = [{ name : "Kickass Playlist 1", id : "kickasspl1-1" }, { name : "Lameass Playlist 2", id : "lameaasspl1-1" }, { name : "Playlist 2", id : "playyylist1" }]; setTimeout(function() { $scope.updateLists(data); }, 2000); $("#copyListModal").modal(); }; $scope.showChangeCode = function() { $("#changeCodeModal").modal(); }; // Toggle power is in "Admin Button Triggered actions" /********************************* Admin Button Triggered Actions ************************************/ $scope.copyInPlaylist = function(id, event) { console.log("Copying: " + id); // Toggle button to green and siabled $(event.target).toggleClass("btn-default", false).toggleClass("btn-success"); $(event.target).toggleClass("disabled", true); // Change text $(event.target).text("Adding..."); //window.socket.emit("addPlaylist", {playListId : id}); }; $scope.unBanUser = function(ip) { var data = { ip: ip }; //window.socket.emit('unban', { ip : ip }) console.log("Unban: " + data.ip); }; $scope.clearPlaylist = function() { //window.socket.emit('clearPlayList'); console.log("Playlist cleared"); $("#clearListModal").modal('hide'); }; $scope.togglePower = function() { $scope.powered = !$scope.powered; var data = { powered : $scope.powered }; console.log("Powered State Change: " + data.powered); //window.socket.emit('updatePowerState', data); }; $scope.genNewCode = function() { $("#genCodeBtn").toggleClass("disabled", true); //window.socket.emit('changeCode'); var data = { partyCode : Math.floor(1+Math.random()*1000000).toString() }; setTimeout(function() { $scope.updateCode(data); }, 2000); }; /***************************** Playlist Triggered Actions ******************************/ // Show the modal. Called by the Ban button $scope.banModal = function(track) { $scope.banModalData = { ipaddr : track.ipaddr }; $("#banUserModal").modal('show'); }; // Ban the user. Called when the user clicks "Yes" in modal $scope.doBan = function(ipaddr) { console.log("Banned: " + ipaddr); //window.socket.emit('ban', {ipaddr : ipaddr}); $("#banUserModal").modal('hide'); }; $scope.removeSong = function(track) { //window.socket.emite('removeSong', track); console.log("Removing Song:"); console.log(track); }; /*************************** Socket Triggered Methods ****************************/ $scope.updateBanList = function(data) { $("#banLoading").toggleClass("hidden", true); $scope.$apply(function() { $scope.banned = data; }); }; $scope.updateCode = function(data) { $("#genCodeBtn").toggleClass("disabled", false); $scope.$apply(function() { $scope.partyCode = data.partyCode; }); }; $scope.updateLists = function(data) { $("#listLoading").toggleClass("hidden", true); $scope.$apply(function() { $scope.hostPlaylists = data.playlists; }); }; $scope.updatePlaylist = function(data) { $scope.$apply(function() { $scope.playlist = data.playlist; }); }; $scope.updatePowerState = function(data) { $scope.$apply(function() { $scope.powered = data.powered; }); }; $scope.reconnecting = function(attempt) { $("#reconnectModal").modal('show'); }; $scope.reconnected = function() { $("#reconnectModal").modal('hide'); }; }); function ipMouseOver(event) { this.oldVal = $(event.target).text(); $(event.target).text("Ban"); } function ipMouseOut(event) { $(event.target).text(this.oldVal); } window.onload = function() { angular.element("body").scope().connect(); };
node/public/js/host.js
var app = angular.module('hostControlApp', []); app.controller('hostCtrl', function($scope) { $scope.playlistName = "defaultPlaylistName"; $scope.playlist = []; $scope.hostPlaylists = []; $scope.banned = []; $scope.banModalData = {}; $scope.partyCode = "12345"; $scope.powered = true; $scope.testLoadPlaylist = function() { $scope.playlist = [ {ipaddr: "localhost", artist: "Joey", title : "Play that funky music", album:"Nomans Land", id: "songid1"}, {ipaddr: "64.29.124.255", artist : "Bobby Joe", title: "Fire fire fire", album: "Steal this", id: "songig2"} ]; console.log($scope.playlist.length); }; $scope.connect = function() { window.socket = io('/', $.cookie("sid")); window.socket.on('connect_error', function(data) { console.log("Connection error: " + data); window.location = '/host'; }); window.socket.on('updateBanList', $scope.updateBanList); window.socket.on('updateCode', $scope.updateCode); window.socket.on('updateLists', $scope.updateLists); window.socket.on('updatePlaylist', $scope.updatePlaylist); window.socket.on('updatePowerState', $scope.updatePowerState); window.socket.on('reconnecting', $scope.reconnecting); window.socket.on('reconnect', $scope.reconnected); }; /************************ Admin Modal Button Methods *************************/ $scope.showClearListWarning = function() { $("#clearListModal").modal(); }; $scope.showBanList = function() { $("#banLoading").toggleClass("hidden", false); $("#banListModal").modal(); var data = [{ ipaddr : "244.12.324.12" }, { ipaddr : "85.241.23.0" }, { ipaddr : "128.0.0.1" }]; //window.socket.emit('getBanList'); setTimeout(function() { $scope.updateBanList(data); }, 2000); }; $scope.showCopyList = function() { $("#listLoading").toggleClass("hidden", false); //window.socket.emit('getPlaylists'); var data = [{ name : "Kickass Playlist 1", id : "kickasspl1-1" }, { name : "Lameass Playlist 2", id : "lameaasspl1-1" }, { name : "Playlist 2", id : "playyylist1" }]; setTimeout(function() { $scope.updateLists(data); }, 2000); $("#copyListModal").modal(); }; $scope.showChangeCode = function() { $("#changeCodeModal").modal(); }; // Toggle power is in "Admin Button Triggered actions" /********************************* Admin Button Triggered Actions ************************************/ $scope.copyInPlaylist = function(id, event) { console.log("Copying: " + id); // Toggle button to green and siabled $(event.target).toggleClass("btn-default", false).toggleClass("btn-success"); $(event.target).toggleClass("disabled", true); // Change text $(event.target).text("Adding..."); //window.socket.emit("addPlaylist", {playListId : id}); }; $scope.unBanUser = function(ip) { var data = { ip: ip }; //window.socket.emit('unban', { ip : ip }) console.log("Unban: " + data.ip); }; $scope.clearPlaylist = function() { //window.socket.emit('clearPlayList'); console.log("Playlist cleared"); $("#clearListModal").modal('hide'); }; $scope.togglePower = function() { $scope.powered = !$scope.powered; var data = { powered : $scope.powered }; console.log("Powered State Change: " + data.powered); //window.socket.emit('updatePowerState', data); }; $scope.genNewCode = function() { $("#genCodeBtn").toggleClass("disabled", true); //window.socket.emit('changeCode'); var data = { partyCode : Math.floor(1+Math.random()*1000000).toString() }; setTimeout(function() { $scope.updateCode(data); }, 2000); }; /***************************** Playlist Triggered Actions ******************************/ // Show the modal. Called by the Ban button $scope.banModal = function(track) { $scope.banModalData = { ipaddr : track.ipaddr }; $("#banUserModal").modal('show'); }; // Ban the user. Called when the user clicks "Yes" in modal $scope.doBan = function(ipaddr) { console.log("Banned: " + ipaddr); //window.socket.emit('ban', {ipaddr : ipaddr}); $("#banUserModal").modal('hide'); }; $scope.removeSong = function(track) { //window.socket.emite('removeSong', track); console.log("Removing Song:"); console.log(track); }; /*************************** Socket Triggered Methods ****************************/ $scope.updateBanList = function(data) { $("#banLoading").toggleClass("hidden", true); $scope.$apply(function() { $scope.banned = data; }); }; $scope.updateCode = function(data) { $("#genCodeBtn").toggleClass("disabled", false); $scope.$apply(function() { $scope.partyCode = data.partyCode; }); }; $scope.updateLists = function(data) { $("#listLoading").toggleClass("hidden", true); $scope.$apply(function() { $scope.hostPlaylists = data.playlists; }); }; $scope.updatePlaylist = function(data) { $scope.$apply(function() { $scope.playlist = data.playlist; }); }; $scope.updatePowerState = function(data) { $scope.$apply(function() { $scope.powered = data.powered; }); }; $scope.reconnecting = function(attempt) { $("#reconnectModal").modal('show'); }; $scope.reconnected = function() { $("#reconnectModal").modal('hide'); }; }); function ipMouseOver(event) { this.oldVal = $(event.target).text(); $(event.target).text("Ban"); } function ipMouseOut(event) { $(event.target).text(this.oldVal); } window.onload = function() { angular.element("body").scope().connect(); };
fix bug preventing connecting to server
node/public/js/host.js
fix bug preventing connecting to server
<ide><path>ode/public/js/host.js <ide> }; <ide> <ide> $scope.connect = function() { <del> window.socket = io('/', $.cookie("sid")); <add> window.socket = io('//'); <ide> window.socket.on('connect_error', function(data) { <del> console.log("Connection error: " + data); <del> window.location = '/host'; <add> console.log("Connection error: "); <add> console.log(data); <add> if(data.description === 404) { <add> window.socket = null; <add> } <ide> }); <ide> <ide> window.socket.on('updateBanList', $scope.updateBanList);
Java
apache-2.0
0404e37357b90b583d306074838d69c7074ce307
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.index; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.codecs.FilterCodec; import org.apache.lucene.codecs.PointsFormat; import org.apache.lucene.codecs.PointsReader; import org.apache.lucene.codecs.PointsWriter; import org.apache.lucene.document.BinaryDocValuesField; import org.apache.lucene.document.BinaryPoint; import org.apache.lucene.document.Document; import org.apache.lucene.document.DoubleDocValuesField; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.FloatDocValuesField; import org.apache.lucene.document.IntPoint; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.SortedDocValuesField; import org.apache.lucene.document.SortedNumericDocValuesField; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.search.CollectionStatistics; import org.apache.lucene.search.EarlyTerminatingSortingCollector; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.SortedNumericSortField; import org.apache.lucene.search.SortedSetSortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermStatistics; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.FixedBitSet; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.NumericUtils; import org.apache.lucene.util.TestUtil; import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; public class TestIndexSorting extends LuceneTestCase { static class AssertingNeedsIndexSortCodec extends FilterCodec { boolean needsIndexSort; int numCalls; AssertingNeedsIndexSortCodec() { super(TestUtil.getDefaultCodec().getName(), TestUtil.getDefaultCodec()); } @Override public PointsFormat pointsFormat() { final PointsFormat pf = delegate.pointsFormat(); return new PointsFormat() { @Override public PointsWriter fieldsWriter(SegmentWriteState state) throws IOException { final PointsWriter writer = pf.fieldsWriter(state); return new PointsWriter() { @Override public void merge(MergeState mergeState) throws IOException { // For single segment merge we cannot infer if the segment is already sorted or not. if (mergeState.docMaps.length > 1) { assertEquals(needsIndexSort, mergeState.needsIndexSort); } ++ numCalls; writer.merge(mergeState); } @Override public void writeField(FieldInfo fieldInfo, PointsReader values) throws IOException { writer.writeField(fieldInfo, values); } @Override public void finish() throws IOException { writer.finish(); } @Override public void close() throws IOException { writer.close(); } }; } @Override public PointsReader fieldsReader(SegmentReadState state) throws IOException { return pf.fieldsReader(state); } }; } } private static void assertNeedsIndexSortMerge(SortField sortField, Consumer<Document> defaultValueConsumer, Consumer<Document> randomValueConsumer) throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); AssertingNeedsIndexSortCodec codec = new AssertingNeedsIndexSortCodec(); iwc.setCodec(codec); Sort indexSort = new Sort(sortField, new SortField("id", SortField.Type.INT)); iwc.setIndexSort(indexSort); LogMergePolicy policy = newLogMergePolicy(); // make sure that merge factor is always > 2 if (policy.getMergeFactor() <= 2) { policy.setMergeFactor(3); } iwc.setMergePolicy(policy); // add already sorted documents codec.numCalls = 0; codec.needsIndexSort = false; IndexWriter w = new IndexWriter(dir, iwc); boolean withValues = random().nextBoolean(); for (int i = 100; i < 200; i++) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); doc.add(new IntPoint("point", random().nextInt())); if (withValues) { defaultValueConsumer.accept(doc); } w.addDocument(doc); if (i % 10 == 0) { w.commit(); } } Set<Integer> deletedDocs = new HashSet<> (); int num = random().nextInt(20); for (int i = 0; i < num; i++) { int nextDoc = random().nextInt(100); w.deleteDocuments(new Term("id", Integer.toString(nextDoc))); deletedDocs.add(nextDoc); } w.commit(); w.waitForMerges(); w.forceMerge(1); assertTrue(codec.numCalls > 0); // merge sort is needed codec.numCalls = 0; codec.needsIndexSort = true; for (int i = 10; i >= 0; i--) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); doc.add(new IntPoint("point", random().nextInt())); if (withValues) { defaultValueConsumer.accept(doc); } w.addDocument(doc); w.commit(); } w.commit(); w.waitForMerges(); w.forceMerge(1); assertTrue(codec.numCalls > 0); // segment sort is needed codec.needsIndexSort = true; codec.numCalls = 0; for (int i = 201; i < 300; i++) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); doc.add(new IntPoint("point", random().nextInt())); randomValueConsumer.accept(doc); w.addDocument(doc); if (i % 10 == 0) { w.commit(); } } w.commit(); w.waitForMerges(); w.forceMerge(1); assertTrue(codec.numCalls > 0); w.close(); dir.close(); } public void testNumericAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortField("foo", SortField.Type.INT), (doc) -> doc.add(new NumericDocValuesField("foo", 0)), (doc) -> doc.add(new NumericDocValuesField("foo", random().nextInt()))); } public void testStringAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortField("foo", SortField.Type.STRING), (doc) -> doc.add(new SortedDocValuesField("foo", new BytesRef("default"))), (doc) -> doc.add(new SortedDocValuesField("foo", TestUtil.randomBinaryTerm(random())))); } public void testMultiValuedNumericAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortedNumericSortField("foo", SortField.Type.INT), (doc) -> { doc.add(new SortedNumericDocValuesField("foo", Integer.MIN_VALUE)); int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedNumericDocValuesField("foo", random().nextInt())); } }, (doc) -> { int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedNumericDocValuesField("foo", random().nextInt())); } }); } public void testMultiValuedStringAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortedSetSortField("foo", false), (doc) -> { doc.add(new SortedSetDocValuesField("foo", new BytesRef(""))); int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedSetDocValuesField("foo", TestUtil.randomBinaryTerm(random()))); } }, (doc) -> { int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedSetDocValuesField("foo", TestUtil.randomBinaryTerm(random()))); } }); } public void testBasicString() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.STRING)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("aaa"))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("mmm"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); SortedDocValues values = leaf.getSortedDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals("aaa", values.binaryValue().utf8ToString()); assertEquals(1, values.nextDoc()); assertEquals("mmm", values.binaryValue().utf8ToString()); assertEquals(2, values.nextDoc()); assertEquals("zzz", values.binaryValue().utf8ToString()); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedString() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedSetSortField("foo", false)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("aaa"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("bcg"))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("mmm"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("pppp"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1l, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2l, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3l, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingStringFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.STRING); sortField.setMissingValue(SortField.STRING_FIRST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("mmm"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); SortedDocValues values = leaf.getSortedDocValues("foo"); // docID 0 is missing: assertEquals(1, values.nextDoc()); assertEquals("mmm", values.binaryValue().utf8ToString()); assertEquals(2, values.nextDoc()); assertEquals("zzz", values.binaryValue().utf8ToString()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedStringFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedSetSortField("foo", false); sortField.setMissingValue(SortField.STRING_FIRST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzza"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzzd"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("mmm"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("nnnn"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1l, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2l, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3l, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingStringLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.STRING); sortField.setMissingValue(SortField.STRING_LAST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("mmm"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); SortedDocValues values = leaf.getSortedDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals("mmm", values.binaryValue().utf8ToString()); assertEquals(1, values.nextDoc()); assertEquals("zzz", values.binaryValue().utf8ToString()); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedStringLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedSetSortField("foo", false); sortField.setMissingValue(SortField.STRING_LAST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzzd"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("mmm"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("ppp"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1l, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2l, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3l, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicLong() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", -1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedLong() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 35)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", -1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 22)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingLongFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); // docID 0 has no value assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedLongFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 27)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 24)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingLongLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(18, values.longValue()); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedLongLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 65)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 34)); doc.add(new SortedNumericDocValuesField("foo", 74)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicInt() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.INT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", -1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedInt() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.INT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 34)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", -1)); doc.add(new SortedNumericDocValuesField("foo", 34)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 22)); doc.add(new SortedNumericDocValuesField("foo", 27)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingIntFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedIntFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 187667)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 34)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingIntLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(18, values.longValue()); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedIntLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 6372)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 8)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicDouble() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.DOUBLE)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new DoubleDocValuesField("foo", 18.0)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", -1.0)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", 7.0)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(1, values.nextDoc()); assertEquals(7.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(2, values.nextDoc()); assertEquals(18.0, Double.longBitsToDouble(values.longValue()), 0.0); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedDouble() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.DOUBLE)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.54))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(27.0))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(-1.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(0.0))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.67))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingDoubleFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new DoubleDocValuesField("foo", 18.0)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", 7.0)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(1, values.nextDoc()); assertEquals(7.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(2, values.nextDoc()); assertEquals(18.0, Double.longBitsToDouble(values.longValue()), 0.0); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedDoubleFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(18.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(18.76))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(70.0))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingDoubleLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new DoubleDocValuesField("foo", 18.0)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", 7.0)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(1, values.nextDoc()); assertEquals(18.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedDoubleLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(18.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(8262.0))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.87))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicFloat() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.FLOAT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new FloatDocValuesField("foo", 18.0f)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", -1.0f)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", 7.0f)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(1, values.nextDoc()); assertEquals(7.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(2, values.nextDoc()); assertEquals(18.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedFloat() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.FLOAT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(29.0f))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(-1.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(34.0f))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(7.0f))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingFloatFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new FloatDocValuesField("foo", 18.0f)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", 7.0f)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(1, values.nextDoc()); assertEquals(7.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(2, values.nextDoc()); assertEquals(18.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedFloatFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(726.0f))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(7.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingFloatLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new FloatDocValuesField("foo", 18.0f)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", 7.0f)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(1, values.nextDoc()); assertEquals(18.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedFloatLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(726.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(12.67f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(7.0f))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testRandom1() throws IOException { boolean withDeletes = random().nextBoolean(); Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); final int numDocs = atLeast(1000); final FixedBitSet deleted = new FixedBitSet(numDocs); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.add(new NumericDocValuesField("foo", random().nextInt(20))); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); w.addDocument(doc); if (random().nextInt(5) == 0) { w.getReader().close(); } else if (random().nextInt(30) == 0) { w.forceMerge(2); } else if (random().nextInt(4) == 0) { final int id = TestUtil.nextInt(random(), 0, i); deleted.set(id); w.deleteDocuments(new Term("id", Integer.toString(id))); } } // Check that segments are sorted DirectoryReader reader = w.getReader(); for (LeafReaderContext ctx : reader.leaves()) { final SegmentReader leaf = (SegmentReader) ctx.reader(); SegmentInfo info = leaf.getSegmentInfo().info; switch (info.getDiagnostics().get(IndexWriter.SOURCE)) { case IndexWriter.SOURCE_FLUSH: case IndexWriter.SOURCE_MERGE: assertEquals(indexSort, info.getIndexSort()); final NumericDocValues values = leaf.getNumericDocValues("foo"); long previous = Long.MIN_VALUE; for (int i = 0; i < leaf.maxDoc(); ++i) { assertEquals(i, values.nextDoc()); final long value = values.longValue(); assertTrue(value >= previous); previous = value; } break; default: fail(); } } // Now check that the index is consistent IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { TermQuery termQuery = new TermQuery(new Term("id", Integer.toString(i))); final TopDocs topDocs = searcher.search(termQuery, 1); if (deleted.get(i)) { assertEquals(0, topDocs.totalHits); } else { assertEquals(1, topDocs.totalHits); NumericDocValues values = MultiDocValues.getNumericValues(reader, "id"); assertEquals(topDocs.scoreDocs[0].doc, values.advance(topDocs.scoreDocs[0].doc)); assertEquals(i, values.longValue()); Document document = reader.document(topDocs.scoreDocs[0].doc); assertEquals(Integer.toString(i), document.get("id")); } } reader.close(); w.close(); dir.close(); } public void testMultiValuedRandom1() throws IOException { boolean withDeletes = random().nextBoolean(); Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); final int numDocs = atLeast(1000); final FixedBitSet deleted = new FixedBitSet(numDocs); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); int num = random().nextInt(10); for (int j = 0; j < num; j++) { doc.add(new SortedNumericDocValuesField("foo", random().nextInt(2000))); } doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); w.addDocument(doc); if (random().nextInt(5) == 0) { w.getReader().close(); } else if (random().nextInt(30) == 0) { w.forceMerge(2); } else if (random().nextInt(4) == 0) { final int id = TestUtil.nextInt(random(), 0, i); deleted.set(id); w.deleteDocuments(new Term("id", Integer.toString(id))); } } DirectoryReader reader = w.getReader(); // Now check that the index is consistent IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { TermQuery termQuery = new TermQuery(new Term("id", Integer.toString(i))); final TopDocs topDocs = searcher.search(termQuery, 1); if (deleted.get(i)) { assertEquals(0, topDocs.totalHits); } else { assertEquals(1, topDocs.totalHits); NumericDocValues values = MultiDocValues.getNumericValues(reader, "id"); assertEquals(topDocs.scoreDocs[0].doc, values.advance(topDocs.scoreDocs[0].doc)); assertEquals(i, values.longValue()); Document document = reader.document(topDocs.scoreDocs[0].doc); assertEquals(Integer.toString(i), document.get("id")); } } reader.close(); w.close(); dir.close(); } static class UpdateRunnable implements Runnable { private final int numDocs; private final Random random; private final AtomicInteger updateCount; private final IndexWriter w; private final Map<Integer, Long> values; private final CountDownLatch latch; UpdateRunnable(int numDocs, Random random, CountDownLatch latch, AtomicInteger updateCount, IndexWriter w, Map<Integer, Long> values) { this.numDocs = numDocs; this.random = random; this.latch = latch; this.updateCount = updateCount; this.w = w; this.values = values; } @Override public void run() { try { latch.await(); while (updateCount.decrementAndGet() >= 0) { final int id = random.nextInt(numDocs); final long value = random.nextInt(20); Document doc = new Document(); doc.add(new StringField("id", Integer.toString(id), Store.NO)); doc.add(new NumericDocValuesField("foo", value)); synchronized (values) { w.updateDocument(new Term("id", Integer.toString(id)), doc); values.put(id, value); } switch (random.nextInt(10)) { case 0: case 1: // reopen DirectoryReader.open(w).close(); break; case 2: w.forceMerge(3); break; } } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } } // There is tricky logic to resolve deletes that happened while merging public void testConcurrentUpdates() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Map<Integer, Long> values = new HashMap<>(); final int numDocs = atLeast(100); Thread[] threads = new Thread[2]; final AtomicInteger updateCount = new AtomicInteger(atLeast(1000)); final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < threads.length; ++i) { Random r = new Random(random().nextLong()); threads[i] = new Thread(new UpdateRunnable(numDocs, r, latch, updateCount, w, values)); } for (Thread thread : threads) { thread.start(); } latch.countDown(); for (Thread thread : threads) { thread.join(); } w.forceMerge(1); DirectoryReader reader = DirectoryReader.open(w); IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { final TopDocs topDocs = searcher.search(new TermQuery(new Term("id", Integer.toString(i))), 1); if (values.containsKey(i) == false) { assertEquals(0, topDocs.totalHits); } else { assertEquals(1, topDocs.totalHits); NumericDocValues dvs = MultiDocValues.getNumericValues(reader, "foo"); int docID = topDocs.scoreDocs[0].doc; assertEquals(docID, dvs.advance(docID)); assertEquals(values.get(i).longValue(), dvs.longValue()); } } reader.close(); w.close(); dir.close(); } // docvalues fields involved in the index sort cannot be updated public void testBadDVUpdate() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new StringField("id", new BytesRef("0"), Store.NO)); doc.add(new NumericDocValuesField("foo", random().nextInt())); w.addDocument(doc); w.commit(); IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> w.updateDocValues(new Term("id", "0"), new NumericDocValuesField("foo", -1))); assertEquals(exc.getMessage(), "cannot update docvalues field involved in the index sort, field=foo, sort=<long: \"foo\">"); exc = expectThrows(IllegalArgumentException.class, () -> w.updateNumericDocValue(new Term("id", "0"), "foo", -1)); assertEquals(exc.getMessage(), "cannot update docvalues field involved in the index sort, field=foo, sort=<long: \"foo\">"); w.close(); dir.close(); } static class DVUpdateRunnable implements Runnable { private final int numDocs; private final Random random; private final AtomicInteger updateCount; private final IndexWriter w; private final Map<Integer, Long> values; private final CountDownLatch latch; DVUpdateRunnable(int numDocs, Random random, CountDownLatch latch, AtomicInteger updateCount, IndexWriter w, Map<Integer, Long> values) { this.numDocs = numDocs; this.random = random; this.latch = latch; this.updateCount = updateCount; this.w = w; this.values = values; } @Override public void run() { try { latch.await(); while (updateCount.decrementAndGet() >= 0) { final int id = random.nextInt(numDocs); final long value = random.nextInt(20); synchronized (values) { w.updateDocValues(new Term("id", Integer.toString(id)), new NumericDocValuesField("bar", value)); values.put(id, value); } switch (random.nextInt(10)) { case 0: case 1: // reopen DirectoryReader.open(w).close(); break; case 2: w.forceMerge(3); break; } } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } } // There is tricky logic to resolve dv updates that happened while merging public void testConcurrentDVUpdates() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Map<Integer, Long> values = new HashMap<>(); final int numDocs = atLeast(100); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.NO)); doc.add(new NumericDocValuesField("foo", random().nextInt())); doc.add(new NumericDocValuesField("bar", -1)); w.addDocument(doc); values.put(i, -1L); } Thread[] threads = new Thread[2]; final AtomicInteger updateCount = new AtomicInteger(atLeast(1000)); final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < threads.length; ++i) { Random r = new Random(random().nextLong()); threads[i] = new Thread(new DVUpdateRunnable(numDocs, r, latch, updateCount, w, values)); } for (Thread thread : threads) { thread.start(); } latch.countDown(); for (Thread thread : threads) { thread.join(); } w.forceMerge(1); DirectoryReader reader = DirectoryReader.open(w); IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { final TopDocs topDocs = searcher.search(new TermQuery(new Term("id", Integer.toString(i))), 1); assertEquals(1, topDocs.totalHits); NumericDocValues dvs = MultiDocValues.getNumericValues(reader, "bar"); int hitDoc = topDocs.scoreDocs[0].doc; assertEquals(hitDoc, dvs.advance(hitDoc)); assertEquals(values.get(i).longValue(), dvs.longValue()); } reader.close(); w.close(); dir.close(); } public void testAddIndexes(boolean withDeletes, boolean useReaders) throws Exception { Directory dir = newDirectory(); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); IndexWriterConfig iwc1 = newIndexWriterConfig(); if (random().nextBoolean()) { iwc1.setIndexSort(indexSort); } RandomIndexWriter w = new RandomIndexWriter(random(), dir); final int numDocs = atLeast(100); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.NO)); doc.add(new NumericDocValuesField("foo", random().nextInt(20))); w.addDocument(doc); } if (withDeletes) { for (int i = random().nextInt(5); i < numDocs; i += TestUtil.nextInt(random(), 1, 5)) { w.deleteDocuments(new Term("id", Integer.toString(i))); } } if (random().nextBoolean()) { w.forceMerge(1); } final IndexReader reader = w.getReader(); w.close(); Directory dir2 = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); iwc.setIndexSort(indexSort); IndexWriter w2 = new IndexWriter(dir2, iwc); if (useReaders) { CodecReader[] codecReaders = new CodecReader[reader.leaves().size()]; for (int i = 0; i < codecReaders.length; ++i) { codecReaders[i] = (CodecReader) reader.leaves().get(i).reader(); } w2.addIndexes(codecReaders); } else { w2.addIndexes(dir); } final IndexReader reader2 = w2.getReader(); final IndexSearcher searcher = newSearcher(reader); final IndexSearcher searcher2 = newSearcher(reader2); for (int i = 0; i < numDocs; ++i) { Query query = new TermQuery(new Term("id", Integer.toString(i))); final TopDocs topDocs = searcher.search(query, 1); final TopDocs topDocs2 = searcher2.search(query, 1); assertEquals(topDocs.totalHits, topDocs2.totalHits); if (topDocs.totalHits == 1) { NumericDocValues dvs1 = MultiDocValues.getNumericValues(reader, "foo"); int hitDoc1 = topDocs.scoreDocs[0].doc; assertEquals(hitDoc1, dvs1.advance(hitDoc1)); long value1 = dvs1.longValue(); NumericDocValues dvs2 = MultiDocValues.getNumericValues(reader2, "foo"); int hitDoc2 = topDocs2.scoreDocs[0].doc; assertEquals(hitDoc2, dvs2.advance(hitDoc2)); long value2 = dvs2.longValue(); assertEquals(value1, value2); } } IOUtils.close(reader, reader2, w2, dir, dir2); } public void testAddIndexes() throws Exception { testAddIndexes(false, true); } public void testAddIndexesWithDeletions() throws Exception { testAddIndexes(true, true); } public void testAddIndexesWithDirectory() throws Exception { testAddIndexes(false, false); } public void testAddIndexesWithDeletionsAndDirectory() throws Exception { testAddIndexes(true, false); } public void testBadSort() throws Exception { IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> { iwc.setIndexSort(Sort.RELEVANCE); }); assertEquals("invalid SortField type: must be one of [STRING, INT, FLOAT, LONG, DOUBLE] but got: <score>", expected.getMessage()); } // you can't change the index sort on an existing index: public void testIllegalChangeSort() throws Exception { final Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); iwc.setIndexSort(new Sort(new SortField("foo", SortField.Type.LONG))); IndexWriter w = new IndexWriter(dir, iwc); w.addDocument(new Document()); DirectoryReader.open(w).close(); w.addDocument(new Document()); w.forceMerge(1); w.close(); final IndexWriterConfig iwc2 = new IndexWriterConfig(new MockAnalyzer(random())); iwc2.setIndexSort(new Sort(new SortField("bar", SortField.Type.LONG))); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { new IndexWriter(dir, iwc2); }); String message = e.getMessage(); assertTrue(message.contains("cannot change previous indexSort=<long: \"foo\">")); assertTrue(message.contains("to new indexSort=<long: \"bar\">")); dir.close(); } static final class NormsSimilarity extends Similarity { private final Similarity in; public NormsSimilarity(Similarity in) { this.in = in; } @Override public long computeNorm(FieldInvertState state) { if (state.getName().equals("norms")) { return state.getLength(); } else { return in.computeNorm(state); } } @Override public SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) { return in.computeWeight(boost, collectionStats, termStats); } @Override public SimScorer simScorer(SimWeight weight, LeafReaderContext context) throws IOException { return in.simScorer(weight, context); } } static final class PositionsTokenStream extends TokenStream { private final CharTermAttribute term; private final PayloadAttribute payload; private final OffsetAttribute offset; private int pos, off; public PositionsTokenStream() { term = addAttribute(CharTermAttribute.class); payload = addAttribute(PayloadAttribute.class); offset = addAttribute(OffsetAttribute.class); } @Override public boolean incrementToken() throws IOException { if (pos == 0) { return false; } clearAttributes(); term.append("#all#"); payload.setPayload(new BytesRef(Integer.toString(pos))); offset.setOffset(off, off); --pos; ++off; return true; } void setId(int id) { pos = id / 10 + 1; off = 0; } } public void testRandom2() throws Exception { int numDocs = atLeast(100); FieldType POSITIONS_TYPE = new FieldType(TextField.TYPE_NOT_STORED); POSITIONS_TYPE.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); POSITIONS_TYPE.freeze(); FieldType TERM_VECTORS_TYPE = new FieldType(TextField.TYPE_NOT_STORED); TERM_VECTORS_TYPE.setStoreTermVectors(true); TERM_VECTORS_TYPE.freeze(); Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new MockTokenizer(); return new TokenStreamComponents(tokenizer, tokenizer); } }; List<Document> docs = new ArrayList<>(); for (int i=0;i<numDocs;i++) { int id = i * 10; Document doc = new Document(); doc.add(new StringField("id", Integer.toString(id), Store.YES)); doc.add(new StringField("docs", "#all#", Store.NO)); PositionsTokenStream positions = new PositionsTokenStream(); positions.setId(id); doc.add(new Field("positions", positions, POSITIONS_TYPE)); doc.add(new NumericDocValuesField("numeric", id)); String value = IntStream.range(0, id).mapToObj(k -> Integer.toString(id)).collect(Collectors.joining(" ")); TextField norms = new TextField("norms", value, Store.NO); doc.add(norms); doc.add(new BinaryDocValuesField("binary", new BytesRef(Integer.toString(id)))); doc.add(new SortedDocValuesField("sorted", new BytesRef(Integer.toString(id)))); doc.add(new SortedSetDocValuesField("multi_valued_string", new BytesRef(Integer.toString(id)))); doc.add(new SortedSetDocValuesField("multi_valued_string", new BytesRef(Integer.toString(id + 1)))); doc.add(new SortedNumericDocValuesField("multi_valued_numeric", id)); doc.add(new SortedNumericDocValuesField("multi_valued_numeric", id + 1)); doc.add(new Field("term_vectors", Integer.toString(id), TERM_VECTORS_TYPE)); byte[] bytes = new byte[4]; NumericUtils.intToSortableBytes(id, bytes, 0); doc.add(new BinaryPoint("points", bytes)); docs.add(doc); } // Must use the same seed for both RandomIndexWriters so they behave identically long seed = random().nextLong(); // We add document alread in ID order for the first writer: Directory dir1 = newFSDirectory(createTempDir()); Random random1 = new Random(seed); IndexWriterConfig iwc1 = newIndexWriterConfig(random1, a); iwc1.setSimilarity(new NormsSimilarity(iwc1.getSimilarity())); // for testing norms field // preserve docIDs iwc1.setMergePolicy(newLogMergePolicy()); if (VERBOSE) { System.out.println("TEST: now index pre-sorted"); } RandomIndexWriter w1 = new RandomIndexWriter(random1, dir1, iwc1); for(Document doc : docs) { ((PositionsTokenStream) ((Field) doc.getField("positions")).tokenStreamValue()).setId(Integer.parseInt(doc.get("id"))); w1.addDocument(doc); } // We shuffle documents, but set index sort, for the second writer: Directory dir2 = newFSDirectory(createTempDir()); Random random2 = new Random(seed); IndexWriterConfig iwc2 = newIndexWriterConfig(random2, a); iwc2.setSimilarity(new NormsSimilarity(iwc2.getSimilarity())); // for testing norms field Sort sort = new Sort(new SortField("numeric", SortField.Type.INT)); iwc2.setIndexSort(sort); Collections.shuffle(docs, random()); if (VERBOSE) { System.out.println("TEST: now index with index-time sorting"); } RandomIndexWriter w2 = new RandomIndexWriter(random2, dir2, iwc2); int count = 0; int commitAtCount = TestUtil.nextInt(random(), 1, numDocs-1); for(Document doc : docs) { ((PositionsTokenStream) ((Field) doc.getField("positions")).tokenStreamValue()).setId(Integer.parseInt(doc.get("id"))); if (count++ == commitAtCount) { // Ensure forceMerge really does merge w2.commit(); } w2.addDocument(doc); } if (VERBOSE) { System.out.println("TEST: now force merge"); } w2.forceMerge(1); DirectoryReader r1 = w1.getReader(); DirectoryReader r2 = w2.getReader(); if (VERBOSE) { System.out.println("TEST: now compare r1=" + r1 + " r2=" + r2); } assertEquals(sort, getOnlyLeafReader(r2).getMetaData().getSort()); assertReaderEquals("left: sorted by hand; right: sorted by Lucene", r1, r2); IOUtils.close(w1, w2, r1, r2, dir1, dir2); } private static final class RandomDoc { public final int id; public final int intValue; public final int[] intValues; public final long longValue; public final long[] longValues; public final float floatValue; public final float[] floatValues; public final double doubleValue; public final double[] doubleValues; public final byte[] bytesValue; public final byte[][] bytesValues; public RandomDoc(int id) { this.id = id; intValue = random().nextInt(); longValue = random().nextLong(); floatValue = random().nextFloat(); doubleValue = random().nextDouble(); bytesValue = new byte[TestUtil.nextInt(random(), 1, 50)]; random().nextBytes(bytesValue); int numValues = random().nextInt(10); intValues = new int[numValues]; longValues = new long[numValues]; floatValues = new float[numValues]; doubleValues = new double[numValues]; bytesValues = new byte[numValues][]; for (int i = 0; i < numValues; i++) { intValues[i] = random().nextInt(); longValues[i] = random().nextLong(); floatValues[i] = random().nextFloat(); doubleValues[i] = random().nextDouble(); bytesValues[i] = new byte[TestUtil.nextInt(random(), 1, 50)]; random().nextBytes(bytesValue); } } } private static SortField randomIndexSortField() { boolean reversed = random().nextBoolean(); SortField sortField; switch(random().nextInt(10)) { case 0: sortField = new SortField("int", SortField.Type.INT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextInt()); } break; case 1: sortField = new SortedNumericSortField("multi_valued_int", SortField.Type.INT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextInt()); } break; case 2: sortField = new SortField("long", SortField.Type.LONG, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextLong()); } break; case 3: sortField = new SortedNumericSortField("multi_valued_long", SortField.Type.LONG, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextLong()); } break; case 4: sortField = new SortField("float", SortField.Type.FLOAT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextFloat()); } break; case 5: sortField = new SortedNumericSortField("multi_valued_float", SortField.Type.FLOAT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextFloat()); } break; case 6: sortField = new SortField("double", SortField.Type.DOUBLE, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextDouble()); } break; case 7: sortField = new SortedNumericSortField("multi_valued_double", SortField.Type.DOUBLE, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextDouble()); } break; case 8: sortField = new SortField("bytes", SortField.Type.STRING, reversed); if (random().nextBoolean()) { sortField.setMissingValue(SortField.STRING_LAST); } break; case 9: sortField = new SortedSetSortField("multi_valued_bytes", reversed); if (random().nextBoolean()) { sortField.setMissingValue(SortField.STRING_LAST); } break; default: sortField = null; fail(); } return sortField; } private static Sort randomSort() { // at least 2 int numFields = TestUtil.nextInt(random(), 2, 4); SortField[] sortFields = new SortField[numFields]; for(int i=0;i<numFields-1;i++) { SortField sortField = randomIndexSortField(); sortFields[i] = sortField; } // tie-break by id: sortFields[numFields-1] = new SortField("id", SortField.Type.INT); return new Sort(sortFields); } // pits index time sorting against query time sorting public void testRandom3() throws Exception { int numDocs; if (TEST_NIGHTLY) { numDocs = atLeast(100000); } else { numDocs = atLeast(1000); } List<RandomDoc> docs = new ArrayList<>(); Sort sort = randomSort(); if (VERBOSE) { System.out.println("TEST: numDocs=" + numDocs + " use sort=" + sort); } // no index sorting, all search-time sorting: Directory dir1 = newFSDirectory(createTempDir()); IndexWriterConfig iwc1 = newIndexWriterConfig(new MockAnalyzer(random())); IndexWriter w1 = new IndexWriter(dir1, iwc1); // use index sorting: Directory dir2 = newFSDirectory(createTempDir()); IndexWriterConfig iwc2 = newIndexWriterConfig(new MockAnalyzer(random())); iwc2.setIndexSort(sort); IndexWriter w2 = new IndexWriter(dir2, iwc2); Set<Integer> toDelete = new HashSet<>(); double deleteChance = random().nextDouble(); for(int id=0;id<numDocs;id++) { RandomDoc docValues = new RandomDoc(id); docs.add(docValues); if (VERBOSE) { System.out.println("TEST: doc id=" + id); System.out.println(" int=" + docValues.intValue); System.out.println(" long=" + docValues.longValue); System.out.println(" float=" + docValues.floatValue); System.out.println(" double=" + docValues.doubleValue); System.out.println(" bytes=" + new BytesRef(docValues.bytesValue)); } Document doc = new Document(); doc.add(new StringField("id", Integer.toString(id), Field.Store.YES)); doc.add(new NumericDocValuesField("id", id)); doc.add(new NumericDocValuesField("int", docValues.intValue)); doc.add(new NumericDocValuesField("long", docValues.longValue)); doc.add(new DoubleDocValuesField("double", docValues.doubleValue)); doc.add(new FloatDocValuesField("float", docValues.floatValue)); doc.add(new SortedDocValuesField("bytes", new BytesRef(docValues.bytesValue))); for (int value : docValues.intValues) { doc.add(new SortedNumericDocValuesField("multi_valued_int", value)); } for (long value : docValues.longValues) { doc.add(new SortedNumericDocValuesField("multi_valued_long", value)); } for (float value : docValues.floatValues) { doc.add(new SortedNumericDocValuesField("multi_valued_float", NumericUtils.floatToSortableInt(value))); } for (double value : docValues.doubleValues) { doc.add(new SortedNumericDocValuesField("multi_valued_double", NumericUtils.doubleToSortableLong(value))); } for (byte[] value : docValues.bytesValues) { doc.add(new SortedSetDocValuesField("multi_valued_bytes", new BytesRef(value))); } w1.addDocument(doc); w2.addDocument(doc); if (random().nextDouble() < deleteChance) { toDelete.add(id); } } for(int id : toDelete) { w1.deleteDocuments(new Term("id", Integer.toString(id))); w2.deleteDocuments(new Term("id", Integer.toString(id))); } DirectoryReader r1 = DirectoryReader.open(w1); IndexSearcher s1 = newSearcher(r1); if (random().nextBoolean()) { int maxSegmentCount = TestUtil.nextInt(random(), 1, 5); if (VERBOSE) { System.out.println("TEST: now forceMerge(" + maxSegmentCount + ")"); } w2.forceMerge(maxSegmentCount); } DirectoryReader r2 = DirectoryReader.open(w2); IndexSearcher s2 = newSearcher(r2); /* System.out.println("TEST: full index:"); SortedDocValues docValues = MultiDocValues.getSortedValues(r2, "bytes"); for(int i=0;i<r2.maxDoc();i++) { System.out.println(" doc " + i + " id=" + r2.document(i).get("id") + " bytes=" + docValues.get(i)); } */ for(int iter=0;iter<100;iter++) { int numHits = TestUtil.nextInt(random(), 1, numDocs); if (VERBOSE) { System.out.println("TEST: iter=" + iter + " numHits=" + numHits); } TopFieldCollector c1 = TopFieldCollector.create(sort, numHits, true, true, true); s1.search(new MatchAllDocsQuery(), c1); TopDocs hits1 = c1.topDocs(); TopFieldCollector c2 = TopFieldCollector.create(sort, numHits, true, true, true); EarlyTerminatingSortingCollector c3 = new EarlyTerminatingSortingCollector(c2, sort, numHits); s2.search(new MatchAllDocsQuery(), c3); TopDocs hits2 = c2.topDocs(); if (VERBOSE) { System.out.println(" topDocs query-time sort: totalHits=" + hits1.totalHits); for(ScoreDoc scoreDoc : hits1.scoreDocs) { System.out.println(" " + scoreDoc.doc); } System.out.println(" topDocs index-time sort: totalHits=" + hits2.totalHits); for(ScoreDoc scoreDoc : hits2.scoreDocs) { System.out.println(" " + scoreDoc.doc); } } assertTrue(hits2.totalHits <= hits1.totalHits); assertEquals(hits2.scoreDocs.length, hits1.scoreDocs.length); for(int i=0;i<hits2.scoreDocs.length;i++) { ScoreDoc hit1 = hits1.scoreDocs[i]; ScoreDoc hit2 = hits2.scoreDocs[i]; assertEquals(r1.document(hit1.doc).get("id"), r2.document(hit2.doc).get("id")); assertEquals(((FieldDoc) hit1).fields, ((FieldDoc) hit2).fields); } } IOUtils.close(r1, r2, w1, w2, dir1, dir2); } public void testTieBreak() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setIndexSort(new Sort(new SortField("foo", SortField.Type.STRING))); iwc.setMergePolicy(newLogMergePolicy()); IndexWriter w = new IndexWriter(dir, iwc); for(int id=0;id<1000;id++) { Document doc = new Document(); doc.add(new StoredField("id", id)); String value; if (id < 500) { value = "bar2"; } else { value = "bar1"; } doc.add(new SortedDocValuesField("foo", new BytesRef(value))); w.addDocument(doc); if (id == 500) { w.commit(); } } w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); for(int docID=0;docID<1000;docID++) { int expectedID; if (docID < 500) { expectedID = 500 + docID; } else { expectedID = docID - 500; } assertEquals(expectedID, r.document(docID).getField("id").numericValue().intValue()); } IOUtils.close(r, w, dir); } public void testIndexSortWithSparseField() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("dense_int", SortField.Type.INT, true); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); for (int i = 0; i < 128; i++) { Document doc = new Document(); doc.add(new NumericDocValuesField("dense_int", i)); if (i < 64) { doc.add(new NumericDocValuesField("sparse_int", i)); doc.add(new BinaryDocValuesField("sparse_binary", new BytesRef(Integer.toString(i)))); } w.addDocument(doc); } w.commit(); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); assertEquals(1, r.leaves().size()); LeafReader leafReader = r.leaves().get(0).reader(); NumericDocValues denseValues = leafReader.getNumericDocValues("dense_int"); NumericDocValues sparseValues = leafReader.getNumericDocValues("sparse_int"); BinaryDocValues sparseBinaryValues = leafReader.getBinaryDocValues("sparse_binary"); for(int docID = 0; docID < 128; docID++) { assertTrue(denseValues.advanceExact(docID)); assertEquals(127-docID, (int) denseValues.longValue()); if (docID >= 64) { assertTrue(denseValues.advanceExact(docID)); assertTrue(sparseValues.advanceExact(docID)); assertTrue(sparseBinaryValues.advanceExact(docID)); assertEquals(docID, sparseValues.docID()); assertEquals(127-docID, (int) sparseValues.longValue()); assertEquals(new BytesRef(Integer.toString(127-docID)), sparseBinaryValues.binaryValue()); } else { assertFalse(sparseBinaryValues.advanceExact(docID)); assertFalse(sparseValues.advanceExact(docID)); } } IOUtils.close(r, w, dir); } public void testIndexSortOnSparseField() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("sparse", SortField.Type.INT, false); sortField.setMissingValue(Integer.MIN_VALUE); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); for (int i = 0; i < 128; i++) { Document doc = new Document(); if (i < 64) { doc.add(new NumericDocValuesField("sparse", i)); } w.addDocument(doc); } w.commit(); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); assertEquals(1, r.leaves().size()); LeafReader leafReader = r.leaves().get(0).reader(); NumericDocValues sparseValues = leafReader.getNumericDocValues("sparse"); for(int docID = 0; docID < 128; docID++) { if (docID >= 64) { assertTrue(sparseValues.advanceExact(docID)); assertEquals(docID-64, (int) sparseValues.longValue()); } else { assertFalse(sparseValues.advanceExact(docID)); } } IOUtils.close(r, w, dir); } }
lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.index; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.codecs.FilterCodec; import org.apache.lucene.codecs.PointsFormat; import org.apache.lucene.codecs.PointsReader; import org.apache.lucene.codecs.PointsWriter; import org.apache.lucene.document.BinaryDocValuesField; import org.apache.lucene.document.BinaryPoint; import org.apache.lucene.document.Document; import org.apache.lucene.document.DoubleDocValuesField; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.FloatDocValuesField; import org.apache.lucene.document.IntPoint; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.SortedDocValuesField; import org.apache.lucene.document.SortedNumericDocValuesField; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.search.CollectionStatistics; import org.apache.lucene.search.EarlyTerminatingSortingCollector; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.SortedNumericSortField; import org.apache.lucene.search.SortedSetSortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermStatistics; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.FixedBitSet; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.NumericUtils; import org.apache.lucene.util.TestUtil; import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; public class TestIndexSorting extends LuceneTestCase { static class AssertingNeedsIndexSortCodec extends FilterCodec { boolean needsIndexSort; int numCalls; AssertingNeedsIndexSortCodec() { super(TestUtil.getDefaultCodec().getName(), TestUtil.getDefaultCodec()); } @Override public PointsFormat pointsFormat() { final PointsFormat pf = delegate.pointsFormat(); return new PointsFormat() { @Override public PointsWriter fieldsWriter(SegmentWriteState state) throws IOException { final PointsWriter writer = pf.fieldsWriter(state); return new PointsWriter() { @Override public void merge(MergeState mergeState) throws IOException { // For single segment merge we cannot infer if the segment is already sorted or not. if (mergeState.docMaps.length > 1) { assertEquals(needsIndexSort, mergeState.needsIndexSort); } ++ numCalls; writer.merge(mergeState); } @Override public void writeField(FieldInfo fieldInfo, PointsReader values) throws IOException { writer.writeField(fieldInfo, values); } @Override public void finish() throws IOException { writer.finish(); } @Override public void close() throws IOException { writer.close(); } }; } @Override public PointsReader fieldsReader(SegmentReadState state) throws IOException { return pf.fieldsReader(state); } }; } } private static void assertNeedsIndexSortMerge(SortField sortField, Consumer<Document> defaultValueConsumer, Consumer<Document> randomValueConsumer) throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); AssertingNeedsIndexSortCodec codec = new AssertingNeedsIndexSortCodec(); iwc.setCodec(codec); Sort indexSort = new Sort(sortField, new SortField("id", SortField.Type.INT)); iwc.setIndexSort(indexSort); LogMergePolicy policy = newLogMergePolicy(); // make sure that merge factor is always > 2 if (policy.getMergeFactor() <= 2) { policy.setMergeFactor(3); } iwc.setMergePolicy(policy); // add already sorted documents codec.numCalls = 0; codec.needsIndexSort = false; IndexWriter w = new IndexWriter(dir, iwc); boolean withValues = random().nextBoolean(); for (int i = 100; i < 200; i++) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); doc.add(new IntPoint("point", random().nextInt())); if (withValues) { defaultValueConsumer.accept(doc); } w.addDocument(doc); if (i % 10 == 0) { w.commit(); } } Set<Integer> deletedDocs = new HashSet<> (); int num = random().nextInt(20); for (int i = 0; i < num; i++) { int nextDoc = random().nextInt(100); w.deleteDocuments(new Term("id", Integer.toString(nextDoc))); deletedDocs.add(nextDoc); } w.commit(); w.waitForMerges(); w.forceMerge(1); assertTrue(codec.numCalls > 0); // merge sort is needed codec.numCalls = 0; codec.needsIndexSort = true; for (int i = 10; i >= 0; i--) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); doc.add(new IntPoint("point", random().nextInt())); if (withValues) { defaultValueConsumer.accept(doc); } w.addDocument(doc); w.commit(); } w.commit(); w.waitForMerges(); w.forceMerge(1); assertTrue(codec.numCalls > 0); // segment sort is needed codec.needsIndexSort = true; codec.numCalls = 0; for (int i = 201; i < 300; i++) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); doc.add(new IntPoint("point", random().nextInt())); randomValueConsumer.accept(doc); w.addDocument(doc); if (i % 10 == 0) { w.commit(); } } w.commit(); w.waitForMerges(); w.forceMerge(1); assertTrue(codec.numCalls > 0); w.close(); dir.close(); } public void testNumericAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortField("foo", SortField.Type.INT), (doc) -> doc.add(new NumericDocValuesField("foo", 0)), (doc) -> doc.add(new NumericDocValuesField("foo", random().nextInt()))); } public void testStringAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortField("foo", SortField.Type.STRING), (doc) -> doc.add(new SortedDocValuesField("foo", new BytesRef("default"))), (doc) -> doc.add(new SortedDocValuesField("foo", TestUtil.randomBinaryTerm(random())))); } public void testMultiValuedNumericAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortedNumericSortField("foo", SortField.Type.INT), (doc) -> { doc.add(new SortedNumericDocValuesField("foo", Integer.MIN_VALUE)); int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedNumericDocValuesField("foo", random().nextInt())); } }, (doc) -> { int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedNumericDocValuesField("foo", random().nextInt())); } }); } public void testMultiValuedStringAlreadySorted() throws Exception { assertNeedsIndexSortMerge(new SortedSetSortField("foo", false), (doc) -> { doc.add(new SortedSetDocValuesField("foo", new BytesRef(""))); int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedSetDocValuesField("foo", TestUtil.randomBinaryTerm(random()))); } }, (doc) -> { int num = random().nextInt(5); for (int j = 0; j < num; j++) { doc.add(new SortedSetDocValuesField("foo", TestUtil.randomBinaryTerm(random()))); } }); } public void testBasicString() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.STRING)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("aaa"))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("mmm"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); SortedDocValues values = leaf.getSortedDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals("aaa", values.binaryValue().utf8ToString()); assertEquals(1, values.nextDoc()); assertEquals("mmm", values.binaryValue().utf8ToString()); assertEquals(2, values.nextDoc()); assertEquals("zzz", values.binaryValue().utf8ToString()); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedString() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedSetSortField("foo", false)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("aaa"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("bcg"))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("mmm"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("pppp"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1l, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2l, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3l, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingStringFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.STRING); sortField.setMissingValue(SortField.STRING_FIRST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("mmm"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); SortedDocValues values = leaf.getSortedDocValues("foo"); // docID 0 is missing: assertEquals(1, values.nextDoc()); assertEquals("mmm", values.binaryValue().utf8ToString()); assertEquals(2, values.nextDoc()); assertEquals("zzz", values.binaryValue().utf8ToString()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedStringFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedSetSortField("foo", false); sortField.setMissingValue(SortField.STRING_FIRST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzza"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzzd"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("mmm"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("nnnn"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1l, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2l, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3l, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingStringLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.STRING); sortField.setMissingValue(SortField.STRING_LAST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("zzz"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new SortedDocValuesField("foo", new BytesRef("mmm"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); SortedDocValues values = leaf.getSortedDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals("mmm", values.binaryValue().utf8ToString()); assertEquals(1, values.nextDoc()); assertEquals("zzz", values.binaryValue().utf8ToString()); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedStringLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedSetSortField("foo", false); sortField.setMissingValue(SortField.STRING_LAST); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzz"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("zzzd"))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedSetDocValuesField("foo", new BytesRef("mmm"))); doc.add(new SortedSetDocValuesField("foo", new BytesRef("ppp"))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1l, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2l, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3l, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicLong() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", -1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedLong() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 35)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", -1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 22)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingLongFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); // docID 0 has no value assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedLongFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 27)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 24)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingLongLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(18, values.longValue()); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedLongLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.LONG); sortField.setMissingValue(Long.valueOf(Long.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 65)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 34)); doc.add(new SortedNumericDocValuesField("foo", 74)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicInt() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.INT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", -1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedInt() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.INT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 34)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", -1)); doc.add(new SortedNumericDocValuesField("foo", 34)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 22)); doc.add(new SortedNumericDocValuesField("foo", 27)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingIntFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(1, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(18, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedIntFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MIN_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 187667)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 34)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingIntLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("foo", 18)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("foo", 7)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(18, values.longValue()); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedIntLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.INT); sortField.setMissingValue(Integer.valueOf(Integer.MAX_VALUE)); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", 18)); doc.add(new SortedNumericDocValuesField("foo", 6372)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", 7)); doc.add(new SortedNumericDocValuesField("foo", 8)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicDouble() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.DOUBLE)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new DoubleDocValuesField("foo", 18.0)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", -1.0)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", 7.0)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(1, values.nextDoc()); assertEquals(7.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(2, values.nextDoc()); assertEquals(18.0, Double.longBitsToDouble(values.longValue()), 0.0); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedDouble() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.DOUBLE)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.54))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(27.0))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(-1.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(0.0))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.67))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingDoubleFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new DoubleDocValuesField("foo", 18.0)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", 7.0)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(1, values.nextDoc()); assertEquals(7.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(2, values.nextDoc()); assertEquals(18.0, Double.longBitsToDouble(values.longValue()), 0.0); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedDoubleFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(18.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(18.76))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(70.0))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingDoubleLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new DoubleDocValuesField("foo", 18.0)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new DoubleDocValuesField("foo", 7.0)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(1, values.nextDoc()); assertEquals(18.0, Double.longBitsToDouble(values.longValue()), 0.0); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedDoubleLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.DOUBLE); sortField.setMissingValue(Double.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(18.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(8262.0))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.0))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.doubleToSortableLong(7.87))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testBasicFloat() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.FLOAT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new FloatDocValuesField("foo", 18.0f)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", -1.0f)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", 7.0f)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(-1.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(1, values.nextDoc()); assertEquals(7.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(2, values.nextDoc()); assertEquals(18.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); r.close(); w.close(); dir.close(); } public void testBasicMultiValuedFloat() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.FLOAT)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(29.0f))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(-1.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(34.0f))); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(7.0f))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingFloatFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new FloatDocValuesField("foo", 18.0f)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", 7.0f)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(1, values.nextDoc()); assertEquals(7.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(2, values.nextDoc()); assertEquals(18.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedFloatFirst() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.NEGATIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(726.0f))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(7.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testMissingFloatLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new FloatDocValuesField("foo", 18.0f)); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing w.addDocument(new Document()); w.commit(); doc = new Document(); doc.add(new FloatDocValuesField("foo", 7.0f)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("foo"); assertEquals(0, values.nextDoc()); assertEquals(7.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(1, values.nextDoc()); assertEquals(18.0f, Float.intBitsToFloat((int) values.longValue()), 0.0f); assertEquals(NO_MORE_DOCS, values.nextDoc()); r.close(); w.close(); dir.close(); } public void testMissingMultiValuedFloatLast() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SortField sortField = new SortedNumericSortField("foo", SortField.Type.FLOAT); sortField.setMissingValue(Float.POSITIVE_INFINITY); Sort indexSort = new Sort(sortField); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new NumericDocValuesField("id", 2)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(726.0f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(18.0f))); w.addDocument(doc); // so we get more than one segment, so that forceMerge actually does merge, since we only get a sorted segment by merging: w.commit(); // missing doc = new Document(); doc.add(new NumericDocValuesField("id", 3)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(new NumericDocValuesField("id", 1)); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(12.67f))); doc.add(new SortedNumericDocValuesField("foo", NumericUtils.floatToSortableInt(7.0f))); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); LeafReader leaf = getOnlyLeafReader(r); assertEquals(3, leaf.maxDoc()); NumericDocValues values = leaf.getNumericDocValues("id"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); assertEquals(1, values.nextDoc()); assertEquals(2, values.longValue()); assertEquals(2, values.nextDoc()); assertEquals(3, values.longValue()); r.close(); w.close(); dir.close(); } public void testRandom1() throws IOException { boolean withDeletes = random().nextBoolean(); Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); final int numDocs = atLeast(1000); final FixedBitSet deleted = new FixedBitSet(numDocs); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.add(new NumericDocValuesField("foo", random().nextInt(20))); doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); w.addDocument(doc); if (random().nextInt(5) == 0) { w.getReader().close(); } else if (random().nextInt(30) == 0) { w.forceMerge(2); } else if (random().nextInt(4) == 0) { final int id = TestUtil.nextInt(random(), 0, i); deleted.set(id); w.deleteDocuments(new Term("id", Integer.toString(id))); } } // Check that segments are sorted DirectoryReader reader = w.getReader(); for (LeafReaderContext ctx : reader.leaves()) { final SegmentReader leaf = (SegmentReader) ctx.reader(); SegmentInfo info = leaf.getSegmentInfo().info; switch (info.getDiagnostics().get(IndexWriter.SOURCE)) { case IndexWriter.SOURCE_FLUSH: case IndexWriter.SOURCE_MERGE: assertEquals(indexSort, info.getIndexSort()); final NumericDocValues values = leaf.getNumericDocValues("foo"); long previous = Long.MIN_VALUE; for (int i = 0; i < leaf.maxDoc(); ++i) { assertEquals(i, values.nextDoc()); final long value = values.longValue(); assertTrue(value >= previous); previous = value; } break; default: fail(); } } // Now check that the index is consistent IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { TermQuery termQuery = new TermQuery(new Term("id", Integer.toString(i))); final TopDocs topDocs = searcher.search(termQuery, 1); if (deleted.get(i)) { assertEquals(0, topDocs.totalHits); } else { assertEquals(1, topDocs.totalHits); NumericDocValues values = MultiDocValues.getNumericValues(reader, "id"); assertEquals(topDocs.scoreDocs[0].doc, values.advance(topDocs.scoreDocs[0].doc)); assertEquals(i, values.longValue()); Document document = reader.document(topDocs.scoreDocs[0].doc); assertEquals(Integer.toString(i), document.get("id")); } } reader.close(); w.close(); dir.close(); } public void testMultiValuedRandom1() throws IOException { boolean withDeletes = random().nextBoolean(); Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortedNumericSortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); final int numDocs = atLeast(1000); final FixedBitSet deleted = new FixedBitSet(numDocs); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); int num = random().nextInt(10); for (int j = 0; j < num; j++) { doc.add(new SortedNumericDocValuesField("foo", random().nextInt(2000))); } doc.add(new StringField("id", Integer.toString(i), Store.YES)); doc.add(new NumericDocValuesField("id", i)); w.addDocument(doc); if (random().nextInt(5) == 0) { w.getReader().close(); } else if (random().nextInt(30) == 0) { w.forceMerge(2); } else if (random().nextInt(4) == 0) { final int id = TestUtil.nextInt(random(), 0, i); deleted.set(id); w.deleteDocuments(new Term("id", Integer.toString(id))); } } DirectoryReader reader = w.getReader(); // Now check that the index is consistent IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { TermQuery termQuery = new TermQuery(new Term("id", Integer.toString(i))); final TopDocs topDocs = searcher.search(termQuery, 1); if (deleted.get(i)) { assertEquals(0, topDocs.totalHits); } else { assertEquals(1, topDocs.totalHits); NumericDocValues values = MultiDocValues.getNumericValues(reader, "id"); assertEquals(topDocs.scoreDocs[0].doc, values.advance(topDocs.scoreDocs[0].doc)); assertEquals(i, values.longValue()); Document document = reader.document(topDocs.scoreDocs[0].doc); assertEquals(Integer.toString(i), document.get("id")); } } reader.close(); w.close(); dir.close(); } static class UpdateRunnable implements Runnable { private final int numDocs; private final Random random; private final AtomicInteger updateCount; private final IndexWriter w; private final Map<Integer, Long> values; private final CountDownLatch latch; UpdateRunnable(int numDocs, Random random, CountDownLatch latch, AtomicInteger updateCount, IndexWriter w, Map<Integer, Long> values) { this.numDocs = numDocs; this.random = random; this.latch = latch; this.updateCount = updateCount; this.w = w; this.values = values; } @Override public void run() { try { latch.await(); while (updateCount.decrementAndGet() >= 0) { final int id = random.nextInt(numDocs); final long value = random.nextInt(20); Document doc = new Document(); doc.add(new StringField("id", Integer.toString(id), Store.NO)); doc.add(new NumericDocValuesField("foo", value)); synchronized (values) { w.updateDocument(new Term("id", Integer.toString(id)), doc); values.put(id, value); } switch (random.nextInt(10)) { case 0: case 1: // reopen DirectoryReader.open(w).close(); break; case 2: w.forceMerge(3); break; } } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } } // There is tricky logic to resolve deletes that happened while merging public void testConcurrentUpdates() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Map<Integer, Long> values = new HashMap<>(); final int numDocs = atLeast(100); Thread[] threads = new Thread[2]; final AtomicInteger updateCount = new AtomicInteger(atLeast(1000)); final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < threads.length; ++i) { Random r = new Random(random().nextLong()); threads[i] = new Thread(new UpdateRunnable(numDocs, r, latch, updateCount, w, values)); } for (Thread thread : threads) { thread.start(); } latch.countDown(); for (Thread thread : threads) { thread.join(); } w.forceMerge(1); DirectoryReader reader = DirectoryReader.open(w); IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { final TopDocs topDocs = searcher.search(new TermQuery(new Term("id", Integer.toString(i))), 1); if (values.containsKey(i) == false) { assertEquals(0, topDocs.totalHits); } else { assertEquals(1, topDocs.totalHits); NumericDocValues dvs = MultiDocValues.getNumericValues(reader, "foo"); int docID = topDocs.scoreDocs[0].doc; assertEquals(docID, dvs.advance(docID)); assertEquals(values.get(i).longValue(), dvs.longValue()); } } reader.close(); w.close(); dir.close(); } // docvalues fields involved in the index sort cannot be updated public void testBadDVUpdate() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new StringField("id", new BytesRef("0"), Store.NO)); doc.add(new NumericDocValuesField("foo", random().nextInt())); w.addDocument(doc); w.commit(); IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> w.updateDocValues(new Term("id", "0"), new NumericDocValuesField("foo", -1))); assertEquals(exc.getMessage(), "cannot update docvalues field involved in the index sort, field=foo, sort=<long: \"foo\">"); exc = expectThrows(IllegalArgumentException.class, () -> w.updateNumericDocValue(new Term("id", "0"), "foo", -1)); assertEquals(exc.getMessage(), "cannot update docvalues field involved in the index sort, field=foo, sort=<long: \"foo\">"); w.close(); dir.close(); } static class DVUpdateRunnable implements Runnable { private final int numDocs; private final Random random; private final AtomicInteger updateCount; private final IndexWriter w; private final Map<Integer, Long> values; private final CountDownLatch latch; DVUpdateRunnable(int numDocs, Random random, CountDownLatch latch, AtomicInteger updateCount, IndexWriter w, Map<Integer, Long> values) { this.numDocs = numDocs; this.random = random; this.latch = latch; this.updateCount = updateCount; this.w = w; this.values = values; } @Override public void run() { try { latch.await(); while (updateCount.decrementAndGet() >= 0) { final int id = random.nextInt(numDocs); final long value = random.nextInt(20); synchronized (values) { w.updateDocValues(new Term("id", Integer.toString(id)), new NumericDocValuesField("bar", value)); values.put(id, value); } switch (random.nextInt(10)) { case 0: case 1: // reopen DirectoryReader.open(w).close(); break; case 2: w.forceMerge(3); break; } } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } } // There is tricky logic to resolve dv updates that happened while merging public void testConcurrentDVUpdates() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); iwc.setIndexSort(indexSort); IndexWriter w = new IndexWriter(dir, iwc); Map<Integer, Long> values = new HashMap<>(); final int numDocs = atLeast(100); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.NO)); doc.add(new NumericDocValuesField("foo", random().nextInt())); doc.add(new NumericDocValuesField("bar", -1)); w.addDocument(doc); values.put(i, -1L); } Thread[] threads = new Thread[2]; final AtomicInteger updateCount = new AtomicInteger(atLeast(1000)); final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < threads.length; ++i) { Random r = new Random(random().nextLong()); threads[i] = new Thread(new DVUpdateRunnable(numDocs, r, latch, updateCount, w, values)); } for (Thread thread : threads) { thread.start(); } latch.countDown(); for (Thread thread : threads) { thread.join(); } w.forceMerge(1); DirectoryReader reader = DirectoryReader.open(w); IndexSearcher searcher = newSearcher(reader); for (int i = 0; i < numDocs; ++i) { final TopDocs topDocs = searcher.search(new TermQuery(new Term("id", Integer.toString(i))), 1); assertEquals(1, topDocs.totalHits); NumericDocValues dvs = MultiDocValues.getNumericValues(reader, "bar"); int hitDoc = topDocs.scoreDocs[0].doc; assertEquals(hitDoc, dvs.advance(hitDoc)); assertEquals(values.get(i).longValue(), dvs.longValue()); } reader.close(); w.close(); dir.close(); } public void testAddIndexes(boolean withDeletes, boolean useReaders) throws Exception { Directory dir = newDirectory(); Sort indexSort = new Sort(new SortField("foo", SortField.Type.LONG)); IndexWriterConfig iwc1 = newIndexWriterConfig(); if (random().nextBoolean()) { iwc1.setIndexSort(indexSort); } RandomIndexWriter w = new RandomIndexWriter(random(), dir); final int numDocs = atLeast(100); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.add(new StringField("id", Integer.toString(i), Store.NO)); doc.add(new NumericDocValuesField("foo", random().nextInt(20))); w.addDocument(doc); } if (withDeletes) { for (int i = random().nextInt(5); i < numDocs; i += TestUtil.nextInt(random(), 1, 5)) { w.deleteDocuments(new Term("id", Integer.toString(i))); } } if (random().nextBoolean()) { w.forceMerge(1); } final IndexReader reader = w.getReader(); w.close(); Directory dir2 = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); iwc.setIndexSort(indexSort); IndexWriter w2 = new IndexWriter(dir2, iwc); if (useReaders) { CodecReader[] codecReaders = new CodecReader[reader.leaves().size()]; for (int i = 0; i < codecReaders.length; ++i) { codecReaders[i] = (CodecReader) reader.leaves().get(i).reader(); } w2.addIndexes(codecReaders); } else { w2.addIndexes(dir); } final IndexReader reader2 = w2.getReader(); final IndexSearcher searcher = newSearcher(reader); final IndexSearcher searcher2 = newSearcher(reader2); for (int i = 0; i < numDocs; ++i) { Query query = new TermQuery(new Term("id", Integer.toString(i))); final TopDocs topDocs = searcher.search(query, 1); final TopDocs topDocs2 = searcher2.search(query, 1); assertEquals(topDocs.totalHits, topDocs2.totalHits); if (topDocs.totalHits == 1) { NumericDocValues dvs1 = MultiDocValues.getNumericValues(reader, "foo"); int hitDoc1 = topDocs.scoreDocs[0].doc; assertEquals(hitDoc1, dvs1.advance(hitDoc1)); long value1 = dvs1.longValue(); NumericDocValues dvs2 = MultiDocValues.getNumericValues(reader2, "foo"); int hitDoc2 = topDocs2.scoreDocs[0].doc; assertEquals(hitDoc2, dvs2.advance(hitDoc2)); long value2 = dvs2.longValue(); assertEquals(value1, value2); } } IOUtils.close(reader, reader2, w2, dir, dir2); } public void testAddIndexes() throws Exception { testAddIndexes(false, true); } public void testAddIndexesWithDeletions() throws Exception { testAddIndexes(true, true); } public void testAddIndexesWithDirectory() throws Exception { testAddIndexes(false, false); } public void testAddIndexesWithDeletionsAndDirectory() throws Exception { testAddIndexes(true, false); } public void testBadSort() throws Exception { IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> { iwc.setIndexSort(Sort.RELEVANCE); }); assertEquals("invalid SortField type: must be one of [STRING, INT, FLOAT, LONG, DOUBLE] but got: <score>", expected.getMessage()); } // you can't change the index sort on an existing index: public void testIllegalChangeSort() throws Exception { final Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); iwc.setIndexSort(new Sort(new SortField("foo", SortField.Type.LONG))); IndexWriter w = new IndexWriter(dir, iwc); w.addDocument(new Document()); DirectoryReader.open(w).close(); w.addDocument(new Document()); w.forceMerge(1); w.close(); final IndexWriterConfig iwc2 = new IndexWriterConfig(new MockAnalyzer(random())); iwc2.setIndexSort(new Sort(new SortField("bar", SortField.Type.LONG))); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { new IndexWriter(dir, iwc2); }); String message = e.getMessage(); assertTrue(message.contains("cannot change previous indexSort=<long: \"foo\">")); assertTrue(message.contains("to new indexSort=<long: \"bar\">")); dir.close(); } static final class NormsSimilarity extends Similarity { private final Similarity in; public NormsSimilarity(Similarity in) { this.in = in; } @Override public long computeNorm(FieldInvertState state) { if (state.getName().equals("norms")) { return state.getLength(); } else { return in.computeNorm(state); } } @Override public SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) { return in.computeWeight(boost, collectionStats, termStats); } @Override public SimScorer simScorer(SimWeight weight, LeafReaderContext context) throws IOException { return in.simScorer(weight, context); } } static final class PositionsTokenStream extends TokenStream { private final CharTermAttribute term; private final PayloadAttribute payload; private final OffsetAttribute offset; private int pos, off; public PositionsTokenStream() { term = addAttribute(CharTermAttribute.class); payload = addAttribute(PayloadAttribute.class); offset = addAttribute(OffsetAttribute.class); } @Override public boolean incrementToken() throws IOException { if (pos == 0) { return false; } clearAttributes(); term.append("#all#"); payload.setPayload(new BytesRef(Integer.toString(pos))); offset.setOffset(off, off); --pos; ++off; return true; } void setId(int id) { pos = id / 10 + 1; off = 0; } } public void testRandom2() throws Exception { int numDocs = atLeast(100); FieldType POSITIONS_TYPE = new FieldType(TextField.TYPE_NOT_STORED); POSITIONS_TYPE.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); POSITIONS_TYPE.freeze(); FieldType TERM_VECTORS_TYPE = new FieldType(TextField.TYPE_NOT_STORED); TERM_VECTORS_TYPE.setStoreTermVectors(true); TERM_VECTORS_TYPE.freeze(); Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new MockTokenizer(); return new TokenStreamComponents(tokenizer, tokenizer); } }; List<Document> docs = new ArrayList<>(); for (int i=0;i<numDocs;i++) { int id = i * 10; Document doc = new Document(); doc.add(new StringField("id", Integer.toString(id), Store.YES)); doc.add(new StringField("docs", "#all#", Store.NO)); PositionsTokenStream positions = new PositionsTokenStream(); positions.setId(id); doc.add(new Field("positions", positions, POSITIONS_TYPE)); doc.add(new NumericDocValuesField("numeric", id)); String value = IntStream.range(0, id).mapToObj(k -> Integer.toString(id)).collect(Collectors.joining(" ")); TextField norms = new TextField("norms", value, Store.NO); doc.add(norms); doc.add(new BinaryDocValuesField("binary", new BytesRef(Integer.toString(id)))); doc.add(new SortedDocValuesField("sorted", new BytesRef(Integer.toString(id)))); doc.add(new SortedSetDocValuesField("multi_valued_string", new BytesRef(Integer.toString(id)))); doc.add(new SortedSetDocValuesField("multi_valued_string", new BytesRef(Integer.toString(id + 1)))); doc.add(new SortedNumericDocValuesField("multi_valued_numeric", id)); doc.add(new SortedNumericDocValuesField("multi_valued_numeric", id + 1)); doc.add(new Field("term_vectors", Integer.toString(id), TERM_VECTORS_TYPE)); byte[] bytes = new byte[4]; NumericUtils.intToSortableBytes(id, bytes, 0); doc.add(new BinaryPoint("points", bytes)); docs.add(doc); } // Must use the same seed for both RandomIndexWriters so they behave identically long seed = random().nextLong(); // We add document alread in ID order for the first writer: Directory dir1 = newFSDirectory(createTempDir()); Random random1 = new Random(seed); IndexWriterConfig iwc1 = newIndexWriterConfig(random1, a); iwc1.setSimilarity(new NormsSimilarity(iwc1.getSimilarity())); // for testing norms field // preserve docIDs iwc1.setMergePolicy(newLogMergePolicy()); if (VERBOSE) { System.out.println("TEST: now index pre-sorted"); } RandomIndexWriter w1 = new RandomIndexWriter(random1, dir1, iwc1); for(Document doc : docs) { ((PositionsTokenStream) ((Field) doc.getField("positions")).tokenStreamValue()).setId(Integer.parseInt(doc.get("id"))); w1.addDocument(doc); } // We shuffle documents, but set index sort, for the second writer: Directory dir2 = newFSDirectory(createTempDir()); Random random2 = new Random(seed); IndexWriterConfig iwc2 = newIndexWriterConfig(random2, a); iwc2.setSimilarity(new NormsSimilarity(iwc2.getSimilarity())); // for testing norms field Sort sort = new Sort(new SortField("numeric", SortField.Type.INT)); iwc2.setIndexSort(sort); Collections.shuffle(docs, random()); if (VERBOSE) { System.out.println("TEST: now index with index-time sorting"); } RandomIndexWriter w2 = new RandomIndexWriter(random2, dir2, iwc2); int count = 0; int commitAtCount = TestUtil.nextInt(random(), 1, numDocs-1); for(Document doc : docs) { ((PositionsTokenStream) ((Field) doc.getField("positions")).tokenStreamValue()).setId(Integer.parseInt(doc.get("id"))); if (count++ == commitAtCount) { // Ensure forceMerge really does merge w2.commit(); } w2.addDocument(doc); } if (VERBOSE) { System.out.println("TEST: now force merge"); } w2.forceMerge(1); DirectoryReader r1 = w1.getReader(); DirectoryReader r2 = w2.getReader(); if (VERBOSE) { System.out.println("TEST: now compare r1=" + r1 + " r2=" + r2); } assertEquals(sort, getOnlyLeafReader(r2).getMetaData().getSort()); assertReaderEquals("left: sorted by hand; right: sorted by Lucene", r1, r2); IOUtils.close(w1, w2, r1, r2, dir1, dir2); } private static final class RandomDoc { public final int id; public final int intValue; public final int[] intValues; public final long longValue; public final long[] longValues; public final float floatValue; public final float[] floatValues; public final double doubleValue; public final double[] doubleValues; public final byte[] bytesValue; public final byte[][] bytesValues; public RandomDoc(int id) { this.id = id; intValue = random().nextInt(); longValue = random().nextLong(); floatValue = random().nextFloat(); doubleValue = random().nextDouble(); bytesValue = new byte[TestUtil.nextInt(random(), 1, 50)]; random().nextBytes(bytesValue); int numValues = random().nextInt(10); intValues = new int[numValues]; longValues = new long[numValues]; floatValues = new float[numValues]; doubleValues = new double[numValues]; bytesValues = new byte[numValues][]; for (int i = 0; i < numValues; i++) { intValues[i] = random().nextInt(); longValues[i] = random().nextLong(); floatValues[i] = random().nextFloat(); doubleValues[i] = random().nextDouble(); bytesValues[i] = new byte[TestUtil.nextInt(random(), 1, 50)]; random().nextBytes(bytesValue); } } } private static SortField randomIndexSortField() { boolean reversed = random().nextBoolean(); SortField sortField; switch(random().nextInt(10)) { case 0: sortField = new SortField("int", SortField.Type.INT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextInt()); } break; case 1: sortField = new SortedNumericSortField("multi_valued_int", SortField.Type.INT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextInt()); } break; case 2: sortField = new SortField("long", SortField.Type.LONG, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextLong()); } break; case 3: sortField = new SortedNumericSortField("multi_valued_long", SortField.Type.LONG, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextLong()); } break; case 4: sortField = new SortField("float", SortField.Type.FLOAT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextFloat()); } break; case 5: sortField = new SortedNumericSortField("multi_valued_float", SortField.Type.FLOAT, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextFloat()); } break; case 6: sortField = new SortField("double", SortField.Type.DOUBLE, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextDouble()); } break; case 7: sortField = new SortedNumericSortField("multi_valued_double", SortField.Type.DOUBLE, reversed); if (random().nextBoolean()) { sortField.setMissingValue(random().nextDouble()); } break; case 8: sortField = new SortField("bytes", SortField.Type.STRING, reversed); if (random().nextBoolean()) { sortField.setMissingValue(SortField.STRING_LAST); } break; case 9: sortField = new SortedSetSortField("multi_valued_bytes", reversed); if (random().nextBoolean()) { sortField.setMissingValue(SortField.STRING_LAST); } break; default: sortField = null; fail(); } return sortField; } private static Sort randomSort() { // at least 2 int numFields = TestUtil.nextInt(random(), 2, 4); SortField[] sortFields = new SortField[numFields]; for(int i=0;i<numFields-1;i++) { SortField sortField = randomIndexSortField(); sortFields[i] = sortField; } // tie-break by id: sortFields[numFields-1] = new SortField("id", SortField.Type.INT); return new Sort(sortFields); } // pits index time sorting against query time sorting public void testRandom3() throws Exception { int numDocs; if (TEST_NIGHTLY) { numDocs = atLeast(100000); } else { numDocs = atLeast(1000); } List<RandomDoc> docs = new ArrayList<>(); Sort sort = randomSort(); if (VERBOSE) { System.out.println("TEST: numDocs=" + numDocs + " use sort=" + sort); } // no index sorting, all search-time sorting: Directory dir1 = newFSDirectory(createTempDir()); IndexWriterConfig iwc1 = newIndexWriterConfig(new MockAnalyzer(random())); IndexWriter w1 = new IndexWriter(dir1, iwc1); // use index sorting: Directory dir2 = newFSDirectory(createTempDir()); IndexWriterConfig iwc2 = newIndexWriterConfig(new MockAnalyzer(random())); iwc2.setIndexSort(sort); IndexWriter w2 = new IndexWriter(dir2, iwc2); Set<Integer> toDelete = new HashSet<>(); double deleteChance = random().nextDouble(); for(int id=0;id<numDocs;id++) { RandomDoc docValues = new RandomDoc(id); docs.add(docValues); if (VERBOSE) { System.out.println("TEST: doc id=" + id); System.out.println(" int=" + docValues.intValue); System.out.println(" long=" + docValues.longValue); System.out.println(" float=" + docValues.floatValue); System.out.println(" double=" + docValues.doubleValue); System.out.println(" bytes=" + new BytesRef(docValues.bytesValue)); } Document doc = new Document(); doc.add(new StringField("id", Integer.toString(id), Field.Store.YES)); doc.add(new NumericDocValuesField("id", id)); doc.add(new NumericDocValuesField("int", docValues.intValue)); doc.add(new NumericDocValuesField("long", docValues.longValue)); doc.add(new DoubleDocValuesField("double", docValues.doubleValue)); doc.add(new FloatDocValuesField("float", docValues.floatValue)); doc.add(new SortedDocValuesField("bytes", new BytesRef(docValues.bytesValue))); for (int value : docValues.intValues) { doc.add(new SortedNumericDocValuesField("multi_valued_int", value)); } for (long value : docValues.longValues) { doc.add(new SortedNumericDocValuesField("multi_valued_long", value)); } for (float value : docValues.floatValues) { doc.add(new SortedNumericDocValuesField("multi_valued_float", NumericUtils.floatToSortableInt(value))); } for (double value : docValues.doubleValues) { doc.add(new SortedNumericDocValuesField("multi_valued_double", NumericUtils.doubleToSortableLong(value))); } for (byte[] value : docValues.bytesValues) { doc.add(new SortedSetDocValuesField("multi_valued_bytes", new BytesRef(value))); } w1.addDocument(doc); w2.addDocument(doc); if (random().nextDouble() < deleteChance) { toDelete.add(id); } } for(int id : toDelete) { w1.deleteDocuments(new Term("id", Integer.toString(id))); w2.deleteDocuments(new Term("id", Integer.toString(id))); } DirectoryReader r1 = DirectoryReader.open(w1); IndexSearcher s1 = newSearcher(r1); if (random().nextBoolean()) { int maxSegmentCount = TestUtil.nextInt(random(), 1, 5); if (VERBOSE) { System.out.println("TEST: now forceMerge(" + maxSegmentCount + ")"); } w2.forceMerge(maxSegmentCount); } DirectoryReader r2 = DirectoryReader.open(w2); IndexSearcher s2 = newSearcher(r2); /* System.out.println("TEST: full index:"); SortedDocValues docValues = MultiDocValues.getSortedValues(r2, "bytes"); for(int i=0;i<r2.maxDoc();i++) { System.out.println(" doc " + i + " id=" + r2.document(i).get("id") + " bytes=" + docValues.get(i)); } */ for(int iter=0;iter<100;iter++) { int numHits = TestUtil.nextInt(random(), 1, numDocs); if (VERBOSE) { System.out.println("TEST: iter=" + iter + " numHits=" + numHits); } TopFieldCollector c1 = TopFieldCollector.create(sort, numHits, true, true, true); s1.search(new MatchAllDocsQuery(), c1); TopDocs hits1 = c1.topDocs(); TopFieldCollector c2 = TopFieldCollector.create(sort, numHits, true, true, true); EarlyTerminatingSortingCollector c3 = new EarlyTerminatingSortingCollector(c2, sort, numHits); s2.search(new MatchAllDocsQuery(), c3); TopDocs hits2 = c2.topDocs(); if (VERBOSE) { System.out.println(" topDocs query-time sort: totalHits=" + hits1.totalHits); for(ScoreDoc scoreDoc : hits1.scoreDocs) { System.out.println(" " + scoreDoc.doc); } System.out.println(" topDocs index-time sort: totalHits=" + hits2.totalHits); for(ScoreDoc scoreDoc : hits2.scoreDocs) { System.out.println(" " + scoreDoc.doc); } } assertTrue(hits2.totalHits <= hits1.totalHits); assertEquals(hits2.scoreDocs.length, hits1.scoreDocs.length); for(int i=0;i<hits2.scoreDocs.length;i++) { ScoreDoc hit1 = hits1.scoreDocs[i]; ScoreDoc hit2 = hits2.scoreDocs[i]; assertEquals(r1.document(hit1.doc).get("id"), r2.document(hit2.doc).get("id")); assertEquals(((FieldDoc) hit1).fields, ((FieldDoc) hit2).fields); } } IOUtils.close(r1, r2, w1, w2, dir1, dir2); } public void testTieBreak() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setIndexSort(new Sort(new SortField("foo", SortField.Type.STRING))); iwc.setMergePolicy(newLogMergePolicy()); IndexWriter w = new IndexWriter(dir, iwc); for(int id=0;id<1000;id++) { Document doc = new Document(); doc.add(new StoredField("id", id)); String value; if (id < 500) { value = "bar2"; } else { value = "bar1"; } doc.add(new SortedDocValuesField("foo", new BytesRef(value))); w.addDocument(doc); if (id == 500) { w.commit(); } } w.forceMerge(1); DirectoryReader r = DirectoryReader.open(w); for(int docID=0;docID<1000;docID++) { int expectedID; if (docID < 500) { expectedID = 500 + docID; } else { expectedID = docID - 500; } assertEquals(expectedID, r.document(docID).getField("id").numericValue().intValue()); } IOUtils.close(r, w, dir); } }
LUCENE-7791: add tests with index sorting and sparse docvalues fields
lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java
LUCENE-7791: add tests with index sorting and sparse docvalues fields
<ide><path>ucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java <ide> } <ide> IOUtils.close(r, w, dir); <ide> } <add> <add> public void testIndexSortWithSparseField() throws Exception { <add> Directory dir = newDirectory(); <add> IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); <add> SortField sortField = new SortField("dense_int", SortField.Type.INT, true); <add> Sort indexSort = new Sort(sortField); <add> iwc.setIndexSort(indexSort); <add> IndexWriter w = new IndexWriter(dir, iwc); <add> for (int i = 0; i < 128; i++) { <add> Document doc = new Document(); <add> doc.add(new NumericDocValuesField("dense_int", i)); <add> if (i < 64) { <add> doc.add(new NumericDocValuesField("sparse_int", i)); <add> doc.add(new BinaryDocValuesField("sparse_binary", new BytesRef(Integer.toString(i)))); <add> } <add> w.addDocument(doc); <add> } <add> w.commit(); <add> w.forceMerge(1); <add> DirectoryReader r = DirectoryReader.open(w); <add> assertEquals(1, r.leaves().size()); <add> LeafReader leafReader = r.leaves().get(0).reader(); <add> <add> NumericDocValues denseValues = leafReader.getNumericDocValues("dense_int"); <add> NumericDocValues sparseValues = leafReader.getNumericDocValues("sparse_int"); <add> BinaryDocValues sparseBinaryValues = leafReader.getBinaryDocValues("sparse_binary"); <add> for(int docID = 0; docID < 128; docID++) { <add> assertTrue(denseValues.advanceExact(docID)); <add> assertEquals(127-docID, (int) denseValues.longValue()); <add> if (docID >= 64) { <add> assertTrue(denseValues.advanceExact(docID)); <add> assertTrue(sparseValues.advanceExact(docID)); <add> assertTrue(sparseBinaryValues.advanceExact(docID)); <add> assertEquals(docID, sparseValues.docID()); <add> assertEquals(127-docID, (int) sparseValues.longValue()); <add> assertEquals(new BytesRef(Integer.toString(127-docID)), sparseBinaryValues.binaryValue()); <add> } else { <add> assertFalse(sparseBinaryValues.advanceExact(docID)); <add> assertFalse(sparseValues.advanceExact(docID)); <add> } <add> } <add> IOUtils.close(r, w, dir); <add> } <add> <add> public void testIndexSortOnSparseField() throws Exception { <add> Directory dir = newDirectory(); <add> IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); <add> SortField sortField = new SortField("sparse", SortField.Type.INT, false); <add> sortField.setMissingValue(Integer.MIN_VALUE); <add> Sort indexSort = new Sort(sortField); <add> iwc.setIndexSort(indexSort); <add> IndexWriter w = new IndexWriter(dir, iwc); <add> for (int i = 0; i < 128; i++) { <add> Document doc = new Document(); <add> if (i < 64) { <add> doc.add(new NumericDocValuesField("sparse", i)); <add> } <add> w.addDocument(doc); <add> } <add> w.commit(); <add> w.forceMerge(1); <add> DirectoryReader r = DirectoryReader.open(w); <add> assertEquals(1, r.leaves().size()); <add> LeafReader leafReader = r.leaves().get(0).reader(); <add> NumericDocValues sparseValues = leafReader.getNumericDocValues("sparse"); <add> for(int docID = 0; docID < 128; docID++) { <add> if (docID >= 64) { <add> assertTrue(sparseValues.advanceExact(docID)); <add> assertEquals(docID-64, (int) sparseValues.longValue()); <add> } else { <add> assertFalse(sparseValues.advanceExact(docID)); <add> } <add> } <add> IOUtils.close(r, w, dir); <add> } <add> <ide> }
Java
apache-2.0
17be992d6c9c73536ba3d78b65c02cc0144417a7
0
apache/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,tweise/incubator-apex-malhar,vrozov/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,apache/incubator-apex-malhar,trusli/apex-malhar,DataTorrent/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,ananthc/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/apex-malhar,vrozov/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,tweise/apex-malhar,yogidevendra/incubator-apex-malhar,vrozov/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,DataTorrent/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,tushargosavi/incubator-apex-malhar,yogidevendra/apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/apex-malhar,siyuanh/incubator-apex-malhar,ananthc/apex-malhar,skekre98/apex-mlhr,DataTorrent/Megh,tweise/apex-malhar,siyuanh/apex-malhar,davidyan74/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,siyuanh/apex-malhar,trusli/apex-malhar,DataTorrent/incubator-apex-malhar,brightchen/apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/incubator-apex-malhar,prasannapramod/apex-malhar,yogidevendra/apex-malhar,tweise/incubator-apex-malhar,siyuanh/apex-malhar,skekre98/apex-mlhr,patilvikram/apex-malhar,apache/incubator-apex-malhar,davidyan74/apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/apex-malhar,prasannapramod/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ananthc/apex-malhar,trusli/apex-malhar,tweise/apex-malhar,chinmaykolhatkar/apex-malhar,chinmaykolhatkar/apex-malhar,prasannapramod/apex-malhar,PramodSSImmaneni/apex-malhar,tweise/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,PramodSSImmaneni/apex-malhar,davidyan74/apex-malhar,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,DataTorrent/Megh,ilganeli/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/apex-malhar,tweise/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,apache/incubator-apex-malhar,brightchen/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,ilganeli/incubator-apex-malhar,chandnisingh/apex-malhar,siyuanh/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,vrozov/apex-malhar,tweise/incubator-apex-malhar,vrozov/apex-malhar,davidyan74/apex-malhar,patilvikram/apex-malhar,siyuanh/apex-malhar,vrozov/apex-malhar,ilganeli/incubator-apex-malhar,vrozov/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,sandeep-n/incubator-apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,PramodSSImmaneni/apex-malhar,trusli/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/incubator-apex-malhar,brightchen/apex-malhar,tushargosavi/incubator-apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/apex-malhar,ilganeli/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,patilvikram/apex-malhar,ilganeli/incubator-apex-malhar,patilvikram/apex-malhar,chandnisingh/apex-malhar,brightchen/apex-malhar,apache/incubator-apex-malhar,brightchen/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,ilganeli/incubator-apex-malhar,tweise/apex-malhar,siyuanh/incubator-apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,yogidevendra/apex-malhar,siyuanh/apex-malhar,siyuanh/apex-malhar,vrozov/apex-malhar,brightchen/apex-malhar,ananthc/apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,tweise/apex-malhar,prasannapramod/apex-malhar,ananthc/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/apex-malhar,patilvikram/apex-malhar,skekre98/apex-mlhr,tushargosavi/incubator-apex-malhar,trusli/apex-malhar,skekre98/apex-mlhr,siyuanh/incubator-apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar
/* * Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datatorrent.lib.logs; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.validation.constraints.NotNull; import org.apache.commons.lang.mutable.MutableDouble; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import com.datatorrent.api.Context.OperatorContext; import com.datatorrent.api.DefaultInputPort; import com.datatorrent.api.DefaultOutputPort; import com.datatorrent.api.Operator; import com.datatorrent.lib.util.KeyValPair; /** * <p> * MultiWindowDimensionAggregation class. * </p> * This class aggregates the value of given dimension across windows * * @since 0.3.4 */ public class MultiWindowDimensionAggregation implements Operator { private static final Logger logger = LoggerFactory.getLogger(MultiWindowDimensionAggregation.class); public enum AggregateOperation { SUM, AVERAGE }; private int windowSize = 2; private int currentWindow = 0; private String timeBucket = "m"; private String dimensionKeyVal = "0"; private List<String> dimensionArrayString; @NotNull private List<int[]> dimensionArray; private AggregateOperation operationType = AggregateOperation.SUM; private Map<String, Map<String, KeyValPair<MutableDouble, Integer>>> outputMap; private Map<Integer, Map<String, Map<String, Number>>> cacheOject; private transient List<Pattern> patternList; private transient int applicationWindowSize = 500; public final transient DefaultOutputPort<Map<String, DimensionObject<String>>> output = new DefaultOutputPort<Map<String, DimensionObject<String>>>(); public final transient DefaultInputPort<Map<String, Map<String, Number>>> data = new DefaultInputPort<Map<String, Map<String, Number>>>() { @Override public void process(Map<String, Map<String, Number>> tuple) { cacheOject.put(currentWindow, tuple); for (Map.Entry<String, Map<String, Number>> tupleEntry : tuple.entrySet()) { String tupleKey = tupleEntry.getKey(); Map<String, Number> tupleValue = tupleEntry.getValue(); int currentPattern = 0; for (Pattern pattern : patternList) { Matcher matcher = pattern.matcher(tupleKey); if (matcher.matches()) { String currentPatternString = dimensionArrayString.get(currentPattern); Map<String, KeyValPair<MutableDouble, Integer>> currentPatternMap = outputMap.get(currentPatternString); if (currentPatternMap == null) { currentPatternMap = new HashMap<String, KeyValPair<MutableDouble, Integer>>(); outputMap.put(currentPatternString, currentPatternMap); } StringBuilder builder = new StringBuilder(matcher.group(2)); for (int i = 1; i < dimensionArray.get(currentPattern).length; i++) { builder.append("," + matcher.group(i + 2)); } KeyValPair<MutableDouble, Integer> currentDimensionKeyValPair = currentPatternMap.get(builder.toString()); if (currentDimensionKeyValPair == null) { currentDimensionKeyValPair = new KeyValPair<MutableDouble, Integer>(new MutableDouble(tupleValue.get(dimensionKeyVal)), 1); currentPatternMap.put(builder.toString(), currentDimensionKeyValPair); } else { currentDimensionKeyValPair.getKey().add(tupleValue.get(dimensionKeyVal)); currentDimensionKeyValPair.setValue(currentDimensionKeyValPair.getValue() + 1); } break; } currentPattern++; } } } }; public String getDimensionKeyVal() { return dimensionKeyVal; } public void setDimensionKeyVal(String dimensionKeyVal) { this.dimensionKeyVal = dimensionKeyVal; } public String getTimeBucket() { return timeBucket; } public void setTimeBucket(String timeBucket) { this.timeBucket = timeBucket; } public List<int[]> getDimensionArray() { return dimensionArray; } public void setDimensionArray(List<int[]> dimensionArray) { this.dimensionArray = dimensionArray; dimensionArrayString = new ArrayList<String>(); for (int[] e : dimensionArray) { StringBuilder builder = new StringBuilder("" + e[0]); for (int i = 1; i < e.length; i++) { builder.append("," + e[i]); } dimensionArrayString.add(builder.toString()); } } public int getWindowSize() { return windowSize; } public void setWindowSize(int windowSize) { this.windowSize = windowSize; } @Override public void setup(OperatorContext arg0) { if (arg0 != null) applicationWindowSize = arg0.attrValue(OperatorContext.APPLICATION_WINDOW_COUNT, 500); if (cacheOject == null) cacheOject = new HashMap<Integer, Map<String, Map<String, Number>>>(windowSize); if (outputMap == null) outputMap = new HashMap<String, Map<String, KeyValPair<MutableDouble, Integer>>>(); setUpPatternList(); } private void setUpPatternList() { patternList = new ArrayList<Pattern>(); for (int[] e : dimensionArray) { Pattern pattern; StringBuilder builder = new StringBuilder(timeBucket + "\\|(\\d+)"); for (int i = 0; i < e.length; i++) { builder.append("\\|" + e[i] + ":([^\\|]+)"); } pattern = Pattern.compile(builder.toString()); patternList.add(pattern); } } @Override public void teardown() { } @Override public void beginWindow(long arg0) { Map<String, Map<String, Number>> currentWindowMap = cacheOject.get(currentWindow); if (currentWindowMap == null) { currentWindowMap = new HashMap<String, Map<String, Number>>(); } else { for (Map.Entry<String, Map<String, Number>> tupleEntry : currentWindowMap.entrySet()) { String tupleKey = tupleEntry.getKey(); Map<String, Number> tupleValue = tupleEntry.getValue(); int currentPattern = 0; for (Pattern pattern : patternList) { Matcher matcher = pattern.matcher(tupleKey); if (matcher.matches()) { String currentPatternString = dimensionArrayString.get(currentPattern); Map<String, KeyValPair<MutableDouble, Integer>> currentPatternMap = outputMap.get(currentPatternString); if (currentPatternMap != null) { StringBuilder builder = new StringBuilder(matcher.group(2)); for (int i = 1; i < dimensionArray.get(currentPattern).length; i++) { builder.append("," + matcher.group(i + 2)); } KeyValPair<MutableDouble, Integer> currentDimensionKeyValPair = currentPatternMap.get(builder.toString()); if (currentDimensionKeyValPair != null) { currentDimensionKeyValPair.getKey().add(0 - tupleValue.get(dimensionKeyVal).doubleValue()); currentDimensionKeyValPair.setValue(currentDimensionKeyValPair.getValue() - 1); if (currentDimensionKeyValPair.getKey().doubleValue() == 0.0) { currentPatternMap.remove(builder.toString()); } } } break; } currentPattern++; } } } currentWindowMap.clear(); if (patternList == null || patternList.isEmpty()) setUpPatternList(); } @Override public void endWindow() { int totalWindowsOccupied = cacheOject.size(); for (Map.Entry<String, Map<String, KeyValPair<MutableDouble, Integer>>> e : outputMap.entrySet()) { for (Map.Entry<String, KeyValPair<MutableDouble, Integer>> dimensionValObj : e.getValue().entrySet()) { Map<String, DimensionObject<String>> outputData = new HashMap<String, DimensionObject<String>>(); KeyValPair<MutableDouble, Integer> keyVal = dimensionValObj.getValue(); if (operationType == AggregateOperation.SUM) { outputData.put(e.getKey(), new DimensionObject<String>(keyVal.getKey(), dimensionValObj.getKey())); } else if (operationType == AggregateOperation.AVERAGE) { if (keyVal.getValue() != 0) { double totalCount = ((double) (totalWindowsOccupied * applicationWindowSize)) / 1000; outputData.put(e.getKey(), new DimensionObject<String>(new MutableDouble(keyVal.getKey().doubleValue() / totalCount), dimensionValObj.getKey())); } } if (!outputData.isEmpty()) output.emit(outputData); } } currentWindow = (currentWindow + 1) % windowSize; } public AggregateOperation getOperationType() { return operationType; } public void setOperationType(AggregateOperation operationType) { this.operationType = operationType; } }
library/src/main/java/com/datatorrent/lib/logs/MultiWindowDimensionAggregation.java
/* * Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datatorrent.lib.logs; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.mutable.MutableDouble; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import com.datatorrent.api.Context.OperatorContext; import com.datatorrent.api.DefaultInputPort; import com.datatorrent.api.DefaultOutputPort; import com.datatorrent.api.Operator; import com.datatorrent.lib.util.KeyValPair; /** * <p> * MultiWindowDimensionAggregation class. * </p> * This class aggregates the value of given dimension across windows * * @since 0.3.4 */ public class MultiWindowDimensionAggregation implements Operator { private static final Logger logger = LoggerFactory.getLogger(MultiWindowDimensionAggregation.class); public enum AggregateOperation { SUM, AVERAGE }; private int windowSize = 2; private int currentWindow = 0; private String timeBucket = "m"; private String dimensionKeyVal = "0"; private List<String> dimensionArrayString; private List<int[]> dimensionArray; private AggregateOperation operationType = AggregateOperation.SUM; private Map<String, Map<String, KeyValPair<MutableDouble, Integer>>> outputMap; private Map<Integer, Map<String, Map<String, Number>>> cacheOject; private transient List<Pattern> patternList; private transient int applicationWindowSize = 500; public final transient DefaultOutputPort<Map<String, DimensionObject<String>>> output = new DefaultOutputPort<Map<String, DimensionObject<String>>>(); public final transient DefaultInputPort<Map<String, Map<String, Number>>> data = new DefaultInputPort<Map<String, Map<String, Number>>>() { @Override public void process(Map<String, Map<String, Number>> tuple) { cacheOject.put(currentWindow, tuple); for (Map.Entry<String, Map<String, Number>> tupleEntry : tuple.entrySet()) { String tupleKey = tupleEntry.getKey(); Map<String, Number> tupleValue = tupleEntry.getValue(); int currentPattern = 0; for (Pattern pattern : patternList) { Matcher matcher = pattern.matcher(tupleKey); if (matcher.matches()) { String currentPatternString = dimensionArrayString.get(currentPattern); Map<String, KeyValPair<MutableDouble, Integer>> currentPatternMap = outputMap.get(currentPatternString); if (currentPatternMap == null) { currentPatternMap = new HashMap<String, KeyValPair<MutableDouble, Integer>>(); outputMap.put(currentPatternString, currentPatternMap); } StringBuilder builder = new StringBuilder(matcher.group(2)); for (int i = 1; i < dimensionArray.get(currentPattern).length; i++) { builder.append("," + matcher.group(i + 2)); } KeyValPair<MutableDouble, Integer> currentDimensionKeyValPair = currentPatternMap.get(builder.toString()); if (currentDimensionKeyValPair == null) { currentDimensionKeyValPair = new KeyValPair<MutableDouble, Integer>(new MutableDouble(tupleValue.get(dimensionKeyVal)), 1); currentPatternMap.put(builder.toString(), currentDimensionKeyValPair); } else { currentDimensionKeyValPair.getKey().add(tupleValue.get(dimensionKeyVal)); currentDimensionKeyValPair.setValue(currentDimensionKeyValPair.getValue() + 1); } break; } currentPattern++; } } } }; public String getDimensionKeyVal() { return dimensionKeyVal; } public void setDimensionKeyVal(String dimensionKeyVal) { this.dimensionKeyVal = dimensionKeyVal; } public String getTimeBucket() { return timeBucket; } public void setTimeBucket(String timeBucket) { this.timeBucket = timeBucket; } public List<int[]> getDimensionArray() { return dimensionArray; } public void setDimensionArray(List<int[]> dimensionArray) { this.dimensionArray = dimensionArray; dimensionArrayString = new ArrayList<String>(); for (int[] e : dimensionArray) { StringBuilder builder = new StringBuilder("" + e[0]); for (int i = 1; i < e.length; i++) { builder.append("," + e[i]); } dimensionArrayString.add(builder.toString()); } } public int getWindowSize() { return windowSize; } public void setWindowSize(int windowSize) { this.windowSize = windowSize; } @Override public void setup(OperatorContext arg0) { if (arg0 != null) applicationWindowSize = arg0.attrValue(OperatorContext.APPLICATION_WINDOW_COUNT, 500); if (cacheOject == null) cacheOject = new HashMap<Integer, Map<String, Map<String, Number>>>(windowSize); if (outputMap == null) outputMap = new HashMap<String, Map<String, KeyValPair<MutableDouble, Integer>>>(); setUpPatternList(); } private void setUpPatternList() { patternList = new ArrayList<Pattern>(); for (int[] e : dimensionArray) { Pattern pattern; StringBuilder builder = new StringBuilder(timeBucket + "\\|(\\d+)"); for (int i = 0; i < e.length; i++) { builder.append("\\|" + e[i] + ":([^\\|]+)"); } pattern = Pattern.compile(builder.toString()); patternList.add(pattern); } } @Override public void teardown() { } @Override public void beginWindow(long arg0) { Map<String, Map<String, Number>> currentWindowMap = cacheOject.get(currentWindow); if (currentWindowMap == null) { currentWindowMap = new HashMap<String, Map<String, Number>>(); } else { for (Map.Entry<String, Map<String, Number>> tupleEntry : currentWindowMap.entrySet()) { String tupleKey = tupleEntry.getKey(); Map<String, Number> tupleValue = tupleEntry.getValue(); int currentPattern = 0; for (Pattern pattern : patternList) { Matcher matcher = pattern.matcher(tupleKey); if (matcher.matches()) { String currentPatternString = dimensionArrayString.get(currentPattern); Map<String, KeyValPair<MutableDouble, Integer>> currentPatternMap = outputMap.get(currentPatternString); if (currentPatternMap != null) { StringBuilder builder = new StringBuilder(matcher.group(2)); for (int i = 1; i < dimensionArray.get(currentPattern).length; i++) { builder.append("," + matcher.group(i + 2)); } KeyValPair<MutableDouble, Integer> currentDimensionKeyValPair = currentPatternMap.get(builder.toString()); if (currentDimensionKeyValPair != null) { currentDimensionKeyValPair.getKey().add(0 - tupleValue.get(dimensionKeyVal).doubleValue()); currentDimensionKeyValPair.setValue(currentDimensionKeyValPair.getValue() - 1); } } break; } currentPattern++; } } } currentWindowMap.clear(); if (patternList == null || patternList.isEmpty()) setUpPatternList(); } @Override public void endWindow() { int totalWindowsOccupied = cacheOject.size(); for (Map.Entry<String, Map<String, KeyValPair<MutableDouble, Integer>>> e : outputMap.entrySet()) { for (Map.Entry<String, KeyValPair<MutableDouble, Integer>> dimensionValObj : e.getValue().entrySet()) { Map<String, DimensionObject<String>> outputData = new HashMap<String, DimensionObject<String>>(); KeyValPair<MutableDouble, Integer> keyVal = dimensionValObj.getValue(); if (operationType == AggregateOperation.SUM) { outputData.put(e.getKey(), new DimensionObject<String>(keyVal.getKey(), dimensionValObj.getKey())); } else if (operationType == AggregateOperation.AVERAGE) { if (keyVal.getValue() != 0) { double totalCount = ((double) (totalWindowsOccupied * applicationWindowSize)) / 1000; outputData.put(e.getKey(), new DimensionObject<String>(new MutableDouble(keyVal.getKey().doubleValue() / totalCount), dimensionValObj.getKey())); } } if(!outputData.isEmpty()) output.emit(outputData); } } currentWindow = (currentWindow + 1) % windowSize; } public AggregateOperation getOperationType() { return operationType; } public void setOperationType(AggregateOperation operationType) { this.operationType = operationType; } }
removing the elements from cache after end of window
library/src/main/java/com/datatorrent/lib/logs/MultiWindowDimensionAggregation.java
removing the elements from cache after end of window
<ide><path>ibrary/src/main/java/com/datatorrent/lib/logs/MultiWindowDimensionAggregation.java <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> <add>import javax.validation.constraints.NotNull; <add> <ide> import org.apache.commons.lang.mutable.MutableDouble; <ide> import org.slf4j.LoggerFactory; <ide> import org.slf4j.Logger; <ide> private String timeBucket = "m"; <ide> private String dimensionKeyVal = "0"; <ide> private List<String> dimensionArrayString; <add> @NotNull <ide> private List<int[]> dimensionArray; <ide> private AggregateOperation operationType = AggregateOperation.SUM; <ide> private Map<String, Map<String, KeyValPair<MutableDouble, Integer>>> outputMap; <ide> if (currentDimensionKeyValPair != null) { <ide> currentDimensionKeyValPair.getKey().add(0 - tupleValue.get(dimensionKeyVal).doubleValue()); <ide> currentDimensionKeyValPair.setValue(currentDimensionKeyValPair.getValue() - 1); <add> if (currentDimensionKeyValPair.getKey().doubleValue() == 0.0) { <add> currentPatternMap.remove(builder.toString()); <add> } <ide> } <ide> } <ide> break; <ide> outputData.put(e.getKey(), new DimensionObject<String>(new MutableDouble(keyVal.getKey().doubleValue() / totalCount), dimensionValObj.getKey())); <ide> } <ide> } <del> if(!outputData.isEmpty()) <add> if (!outputData.isEmpty()) <ide> output.emit(outputData); <ide> } <ide> }
JavaScript
mpl-2.0
f8ce8e14d36480488691e33e3fc43bbf385a408e
0
kapy2010/treeherder,kapy2010/treeherder,tojonmz/treeherder,tojonmz/treeherder,kapy2010/treeherder,edmorley/treeherder,KWierso/treeherder,kapy2010/treeherder,KWierso/treeherder,tojonmz/treeherder,tojonmz/treeherder,kapy2010/treeherder,tojonmz/treeherder,tojon/treeherder,tojon/treeherder,KWierso/treeherder,KWierso/treeherder,edmorley/treeherder,tojon/treeherder,edmorley/treeherder,tojonmz/treeherder,edmorley/treeherder,tojon/treeherder
"use strict"; treeherder.controller('PinboardCtrl', [ '$scope', '$rootScope', '$document', '$timeout','thEvents', 'thPinboard', 'thNotify', 'ThLog', function PinboardCtrl( $scope, $rootScope, $document, $timeout, thEvents, thPinboard, thNotify, ThLog) { var $log = new ThLog(this.constructor.name); $rootScope.$on(thEvents.toggleJobPin, function(event, job) { $scope.toggleJobPin(job); if (!$scope.$$phase){ $scope.$digest(); } }); $rootScope.$on(thEvents.jobPin, function(event, job) { $scope.pinJob(job); if (!$scope.$$phase){ $scope.$digest(); } }); $rootScope.$on(thEvents.addRelatedBug, function(event, job) { $scope.pinJob(job); $scope.toggleEnterBugNumber(true); }); $rootScope.$on(thEvents.saveClassification, function() { if ($scope.isPinboardVisible) { $scope.save(); } }); $rootScope.$on(thEvents.clearPinboard, function() { if ($scope.isPinboardVisible) { $scope.unPinAll(); } }); $scope.toggleJobPin = function(job) { thPinboard.toggleJobPin(job); if (!$scope.selectedJob) { $scope.viewJob(job); } }; $scope.pulsePinCount = function() { $( ".pin-count-group" ).addClass( "pin-count-pulse" ); $timeout(function() { $( ".pin-count-group" ).removeClass( "pin-count-pulse" ); }, 700); }; // Triggered on pin api events eg. from the job details navbar $rootScope.$on(thEvents.pulsePinCount, function() { $scope.pulsePinCount(); }); $scope.pinJob = function(job) { thPinboard.pinJob(job); if (!$scope.selectedJob) { $scope.viewJob(job); } $scope.pulsePinCount(); }; $scope.unPinJob = function(id) { thPinboard.unPinJob(id); }; $scope.addBug = function(bug) { thPinboard.addBug(bug); }; $scope.removeBug = function(id) { thPinboard.removeBug(id); }; $scope.unPinAll = function() { thPinboard.unPinAll(); $scope.classification = thPinboard.createNewClassification(); }; $scope.save = function() { var errorFree = true; if (!$scope.canSaveClassifications()) { thNotify.send("Please classify this failure before saving", "danger"); errorFree = false; } if (!$scope.user.loggedin) { thNotify.send("Must be logged in to save job classifications", "danger"); errorFree = false; } if (errorFree) { if ($scope.enteringBugNumber) { // we should save this for the user, as they likely // just forgot to hit enter. $scope.saveEnteredBugNumber(); } $scope.classification.who = $scope.user.email; var classification = $scope.classification; thPinboard.save(classification); $scope.completeClassification(); $scope.classification = thPinboard.createNewClassification(); // HACK: it looks like Firefox on Linux and Windows doesn't // want to accept keyboard input after this change for some // reason which I don't understand. Chrome (any platform) // or Firefox on Mac works fine though. document.activeElement.blur(); } }; $scope.saveClassificationOnly = function() { if ($scope.user.loggedin) { $scope.classification.who = $scope.user.email; thPinboard.saveClassificationOnly($scope.classification); } else { thNotify.send("Must be logged in to save job classifications", "danger"); } }; $scope.saveBugsOnly = function() { if ($scope.user.loggedin) { thPinboard.saveBugsOnly(); } else { thNotify.send("Must be logged in to save job classifications", "danger"); } }; $scope.retriggerAllPinnedJobs = function() { // pushing pinned jobs to a list. $scope.retriggerJob(_.values($scope.pinnedJobs)); }; $scope.cancelAllPinnedJobsTitle = function() { if (!$scope.user.loggedin) { return "Not logged in"; } else if ($scope.canCancelAllPinnedJobs()) { return "No pending / running jobs in pinboard"; } return "Cancel all the pinned jobs"; }; $scope.canCancelAllPinnedJobs = function() { var cancellableJobs = _.values($scope.pinnedJobs).filter( job => (job.state === 'pending' || job.state === 'running')); return $scope.user.loggedin && cancellableJobs.length > 0; }; $scope.cancelAllPinnedJobs = function() { if (window.confirm('This will cancel all the selected jobs. Are you sure?')) { $scope.cancelJobs(_.values($scope.pinnedJobs)); } }; $scope.canSaveClassifications = function() { var thisClass = $scope.classification; return $scope.hasPinnedJobs() && (thPinboard.hasRelatedBugs() && $scope.user.loggedin || thisClass.failure_classification_id !== 4 && thisClass.failure_classification_id !== 2 || $rootScope.currentRepo.repository_group.name === "try" || $rootScope.currentRepo.repository_group.name === "project repositories" || (thisClass.failure_classification_id === 4 && thisClass.text.length > 0) || (thisClass.failure_classification_id === 2 && thisClass.text.length > 7)); }; // Dyanmic btn/anchor title for classification save $scope.saveUITitle = function(category) { var title = ""; if (!$scope.user.loggedin) { title = title.concat("not logged in / "); } if (category === "classification") { if (!$scope.canSaveClassifications()) { title = title.concat("ineligible classification data / "); } if (!$scope.hasPinnedJobs()) { title = title.concat("no pinned jobs"); } // We don't check pinned jobs because the menu dropdown handles it } else if (category === "bug") { if (!$scope.hasRelatedBugs()) { title = title.concat("no related bugs"); } } if (title === "") { title = "Save " + category + " data"; } else { // Cut off trailing "/ " if one exists, capitalize first letter title = title.replace(/\/ $/,""); title = title.replace(/^./, function(l) { return l.toUpperCase(); }); } return title; }; $scope.hasPinnedJobs = function() { return thPinboard.hasPinnedJobs(); }; $scope.hasRelatedBugs = function() { return thPinboard.hasRelatedBugs(); }; function handleRelatedBugDocumentClick(event) { if (!$(event.target).hasClass("add-related-bugs-input")) { $scope.$apply(function() { $scope.toggleEnterBugNumber(false); }); } } $scope.toggleEnterBugNumber = function(tf) { $scope.enteringBugNumber = tf; $scope.focusInput = tf; $document.off('click', handleRelatedBugDocumentClick); if (tf) { // Rebind escape to canceling the bug entry, pressing escape // again will close the pinboard as usual. Mousetrap.bind('escape', function() { var cancel = _.bind($scope.toggleEnterBugNumber, $scope, false); $scope.$evalAsync(cancel); }); // Install a click handler on the document so that clicking // outside of the input field will close it. A blur handler // can't be used because it would have timing issues with the // click handler on the + icon. $timeout(function() { $document.on('click', handleRelatedBugDocumentClick); }, 0); } else { $scope.newEnteredBugNumber = ''; } }; $scope.completeClassification = function() { $rootScope.$broadcast('blur-this', "classification-comment"); }; $scope.saveEnteredBugNumber = function() { if ($scope.enteringBugNumber) { if (!$scope.newEnteredBugNumber) { $scope.toggleEnterBugNumber(false); } else { $log.debug("new bug number to be saved: ", $scope.newEnteredBugNumber); thPinboard.addBug({id:$scope.newEnteredBugNumber}); $scope.toggleEnterBugNumber(false); } } }; $scope.viewJob = function(job) { $rootScope.selectedJob = job; $rootScope.$emit(thEvents.jobClick, job); $rootScope.$emit(thEvents.selectJob, job); }; $scope.classification = thPinboard.createNewClassification(); $scope.pinnedJobs = thPinboard.pinnedJobs; $scope.relatedBugs = thPinboard.relatedBugs; } ]);
ui/plugins/pinboard.js
"use strict"; treeherder.controller('PinboardCtrl', [ '$scope', '$rootScope', '$document', '$timeout','thEvents', 'thPinboard', 'thNotify', 'ThLog', function PinboardCtrl( $scope, $rootScope, $document, $timeout, thEvents, thPinboard, thNotify, ThLog) { var $log = new ThLog(this.constructor.name); $rootScope.$on(thEvents.toggleJobPin, function(event, job) { $scope.toggleJobPin(job); if (!$scope.$$phase){ $scope.$digest(); } }); $rootScope.$on(thEvents.jobPin, function(event, job) { $scope.pinJob(job); if (!$scope.$$phase){ $scope.$digest(); } }); $rootScope.$on(thEvents.addRelatedBug, function(event, job) { $scope.pinJob(job); $scope.toggleEnterBugNumber(true); }); $rootScope.$on(thEvents.saveClassification, function() { if ($scope.isPinboardVisible) { $scope.save(); } }); $rootScope.$on(thEvents.clearPinboard, function() { if ($scope.isPinboardVisible) { $scope.unPinAll(); } }); $scope.toggleJobPin = function(job) { thPinboard.toggleJobPin(job); if (!$scope.selectedJob) { $scope.viewJob(job); } }; $scope.pulsePinCount = function() { $( ".pin-count-group" ).addClass( "pin-count-pulse" ); $timeout(function() { $( ".pin-count-group" ).removeClass( "pin-count-pulse" ); }, 700); }; // Triggered on pin api events eg. from the job details navbar $rootScope.$on(thEvents.pulsePinCount, function() { $scope.pulsePinCount(); }); $scope.pinJob = function(job) { thPinboard.pinJob(job); if (!$scope.selectedJob) { $scope.viewJob(job); } $scope.pulsePinCount(); }; $scope.unPinJob = function(id) { thPinboard.unPinJob(id); }; $scope.addBug = function(bug) { thPinboard.addBug(bug); }; $scope.removeBug = function(id) { thPinboard.removeBug(id); }; $scope.unPinAll = function() { thPinboard.unPinAll(); $scope.classification = thPinboard.createNewClassification(); }; $scope.save = function() { var errorFree = true; if (!$scope.canSaveClassifications()) { thNotify.send("Please classify this failure before saving", "danger"); errorFree = false; } if (!$scope.user.loggedin) { thNotify.send("Must be logged in to save job classifications", "danger"); errorFree = false; } if (errorFree) { if ($scope.enteringBugNumber) { // we should save this for the user, as they likely // just forgot to hit enter. $scope.saveEnteredBugNumber(); } $scope.classification.who = $scope.user.email; var classification = $scope.classification; thPinboard.save(classification); $scope.completeClassification(); $scope.classification = thPinboard.createNewClassification(); // HACK: it looks like Firefox on Linux and Windows doesn't // want to accept keyboard input after this change for some // reason which I don't understand. Chrome (any platform) // or Firefox on Mac works fine though. document.activeElement.blur(); } }; $scope.saveClassificationOnly = function() { if ($scope.user.loggedin) { $scope.classification.who = $scope.user.email; thPinboard.saveClassificationOnly($scope.classification); } else { thNotify.send("Must be logged in to save job classifications", "danger"); } }; $scope.saveBugsOnly = function() { if ($scope.user.loggedin) { thPinboard.saveBugsOnly(); } else { thNotify.send("Must be logged in to save job classifications", "danger"); } }; $scope.retriggerAllPinnedJobs = function() { // pushing pinned jobs to a list. $scope.retriggerJob(_.values($scope.pinnedJobs)); }; $scope.cancelAllPinnedJobsTitle = function() { if (!$scope.user.loggedin) { return "Not logged in"; } else if ($scope.canCancelAllPinnedJobs()) { return "No pending / running jobs in pinboard"; } return "Cancel all the pinned jobs"; }; $scope.canCancelAllPinnedJobs = function() { var cancellableJobs = _.values($scope.pinnedJobs).filter( job => (job.state === 'pending' || job.state === 'running')); return $scope.user.loggedin && cancellableJobs.length > 0; }; $scope.cancelAllPinnedJobs = function() { $scope.cancelJobs(_.values($scope.pinnedJobs)); }; $scope.canSaveClassifications = function() { var thisClass = $scope.classification; return $scope.hasPinnedJobs() && (thPinboard.hasRelatedBugs() && $scope.user.loggedin || thisClass.failure_classification_id !== 4 && thisClass.failure_classification_id !== 2 || $rootScope.currentRepo.repository_group.name === "try" || $rootScope.currentRepo.repository_group.name === "project repositories" || (thisClass.failure_classification_id === 4 && thisClass.text.length > 0) || (thisClass.failure_classification_id === 2 && thisClass.text.length > 7)); }; // Dyanmic btn/anchor title for classification save $scope.saveUITitle = function(category) { var title = ""; if (!$scope.user.loggedin) { title = title.concat("not logged in / "); } if (category === "classification") { if (!$scope.canSaveClassifications()) { title = title.concat("ineligible classification data / "); } if (!$scope.hasPinnedJobs()) { title = title.concat("no pinned jobs"); } // We don't check pinned jobs because the menu dropdown handles it } else if (category === "bug") { if (!$scope.hasRelatedBugs()) { title = title.concat("no related bugs"); } } if (title === "") { title = "Save " + category + " data"; } else { // Cut off trailing "/ " if one exists, capitalize first letter title = title.replace(/\/ $/,""); title = title.replace(/^./, function(l) { return l.toUpperCase(); }); } return title; }; $scope.hasPinnedJobs = function() { return thPinboard.hasPinnedJobs(); }; $scope.hasRelatedBugs = function() { return thPinboard.hasRelatedBugs(); }; function handleRelatedBugDocumentClick(event) { if (!$(event.target).hasClass("add-related-bugs-input")) { $scope.$apply(function() { $scope.toggleEnterBugNumber(false); }); } } $scope.toggleEnterBugNumber = function(tf) { $scope.enteringBugNumber = tf; $scope.focusInput = tf; $document.off('click', handleRelatedBugDocumentClick); if (tf) { // Rebind escape to canceling the bug entry, pressing escape // again will close the pinboard as usual. Mousetrap.bind('escape', function() { var cancel = _.bind($scope.toggleEnterBugNumber, $scope, false); $scope.$evalAsync(cancel); }); // Install a click handler on the document so that clicking // outside of the input field will close it. A blur handler // can't be used because it would have timing issues with the // click handler on the + icon. $timeout(function() { $document.on('click', handleRelatedBugDocumentClick); }, 0); } else { $scope.newEnteredBugNumber = ''; } }; $scope.completeClassification = function() { $rootScope.$broadcast('blur-this', "classification-comment"); }; $scope.saveEnteredBugNumber = function() { if ($scope.enteringBugNumber) { if (!$scope.newEnteredBugNumber) { $scope.toggleEnterBugNumber(false); } else { $log.debug("new bug number to be saved: ", $scope.newEnteredBugNumber); thPinboard.addBug({id:$scope.newEnteredBugNumber}); $scope.toggleEnterBugNumber(false); } } }; $scope.viewJob = function(job) { $rootScope.selectedJob = job; $rootScope.$emit(thEvents.jobClick, job); $rootScope.$emit(thEvents.selectJob, job); }; $scope.classification = thPinboard.createNewClassification(); $scope.pinnedJobs = thPinboard.pinnedJobs; $scope.relatedBugs = thPinboard.relatedBugs; } ]);
Bug 1217570 - Confirm that user really wants to cancel all jobs in pinboard (#2141)
ui/plugins/pinboard.js
Bug 1217570 - Confirm that user really wants to cancel all jobs in pinboard (#2141)
<ide><path>i/plugins/pinboard.js <ide> }; <ide> <ide> $scope.cancelAllPinnedJobs = function() { <del> $scope.cancelJobs(_.values($scope.pinnedJobs)); <add> if (window.confirm('This will cancel all the selected jobs. Are you sure?')) { <add> $scope.cancelJobs(_.values($scope.pinnedJobs)); <add> } <ide> }; <ide> <ide> $scope.canSaveClassifications = function() {
Java
apache-2.0
af76254e41ec53ecf1393d32e2a31bb6ef73d36a
0
bbrownz/kite,megnataraj/kite,bbaugher/kite,prazanna/kite,rbrush/kite,joey/kite,rdblue/kite,tomwhite/kite,bbrownz/kite,busbey/kite,EdwardSkoviak/kite,whoschek/kite,dlanza1/kite,kite-sdk/kite,mkwhitacre/kite,yuzhu712/cdk,yuzhu712/cdk,andrewrothstein/kite,megnataraj/kite,yuzhu712/cdk,busbey/kite,tinkujohn/kite,stevek-ngdata/kite,scalingdata/cdk,rbrush/kite,andrewrothstein/kite,rdblue/kite,StephanieMak/kite,dlanza1/kite,kite-sdk/kite,andrewrothstein/kite,gabrielreid/kite,ronanstokes/kite,whoschek/kite,EdwardSkoviak/kite,prazanna/kite,ronanstokes/kite,StephanieMak/kite,busbey/kite,tomwhite/kite,cloudera/cdk,joey/kite,stevek-ngdata/kite,EdwardSkoviak/kite,scalingdata/cdk,rbrush/kite,prazanna/kite,megnataraj/kite,bbrownz/kite,rdblue/kite,scalingdata/cdk,gabrielreid/kite,tinkujohn/kite,kite-sdk/kite,bbaugher/kite,stevek-ngdata/kite,gabrielreid/kite,mkwhitacre/kite,bbaugher/kite,StephanieMak/kite,ronanstokes/kite,tinkujohn/kite,joey/kite,cloudera/cdk,mkwhitacre/kite
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.cdk.data; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.io.Closeables; import java.net.MalformedURLException; import java.net.URI; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileStream; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import org.apache.avro.reflect.ReflectData; /** * <p> * The structural definition of a {@link Dataset}. * </p> * <p> * Each {@code Dataset} has an associated {@link Schema} and optional * {@link PartitionStrategy} defined at the time of creation. Instances of this * class are used to hold this information. Users are strongly encouraged to use * the inner {@link Builder} to create new instances. * </p> */ @Immutable public class DatasetDescriptor { private final Schema schema; private final URL schemaUrl; private final Format format; private final URI location; private final PartitionStrategy partitionStrategy; /** * Create an instance of this class with the supplied {@link Schema}, * and optional {@link PartitionStrategy}. The default {@link Format}, * {@link Formats#AVRO}, will be used. */ public DatasetDescriptor(Schema schema, @Nullable PartitionStrategy partitionStrategy) { this(schema, null, Formats.AVRO, null, partitionStrategy); } /** * Create an instance of this class with the supplied {@link Schema}, * optional URL, {@link Format}, optional location URL, and optional * {@link PartitionStrategy}. */ DatasetDescriptor(Schema schema, @Nullable URL schemaUrl, Format format, @Nullable URI location, @Nullable PartitionStrategy partitionStrategy) { this.schema = schema; this.schemaUrl = schemaUrl; this.format = format; this.location = location; this.partitionStrategy = partitionStrategy; } /** * Get the associated {@link Schema}. Depending on the underlying storage * system, this schema may be simple (i.e. records made up of only scalar * types) or complex (i.e. containing other records, lists, and so on). * Validation of the supported schemas is performed by the managing * repository, not the dataset or descriptor itself. * * @return the schema */ public Schema getSchema() { return schema; } /** * Get a URL from which the {@link Schema} may be retrieved (optional). This * method may return {@code null} if the schema is not stored at a persistent * URL, e.g. if it was constructed from a literal string. * * @return a URL from which the schema may be retrieved * @since 0.3.0 */ @Nullable public URL getSchemaUrl() { return schemaUrl; } /** * Get the associated {@link Format} that the data is stored in. * * @return the format * @since 0.2.0 */ public Format getFormat() { return format; } /** * Get the URL location where the data for this {@link Dataset} is stored * (optional). * * @return a location URL or null if one is not set * * @since 0.8.0 */ @Nullable public URI getLocation() { return location; } /** * Get the {@link PartitionStrategy}, if this dataset is partitioned. Calling * this method on a non-partitioned dataset is an error. Instead, use the * {@link #isPartitioned()} method prior to invocation. */ public PartitionStrategy getPartitionStrategy() { Preconditions .checkState( isPartitioned(), "Attempt to retrieve the partition strategy on a non-partitioned descriptor:%s", this); return partitionStrategy; } /** * Returns true if an associated dataset is partitioned (that is, has an * associated {@link PartitionStrategy}), false otherwise. */ public boolean isPartitioned() { return partitionStrategy != null; } @Override public String toString() { return Objects.toStringHelper(this).add("schema", schema) .add("partitionStrategy", partitionStrategy).toString(); } /** * A fluent builder to aid in the construction of {@link DatasetDescriptor}s. */ public static class Builder implements Supplier<DatasetDescriptor> { private Schema schema; private URL schemaUrl; private Format format = Formats.AVRO; private URI location; private PartitionStrategy partitionStrategy; public Builder() { } /** * Creates a Builder configured to copy {@code descriptor}, if it is not * modified. This is intended to help callers copy and update descriptors * even though they are {@link Immutable}. * * @param descriptor A {@link DatasetDescriptor} to copy settings from * @since 0.7.0 */ public Builder(DatasetDescriptor descriptor) { this.schema = descriptor.getSchema(); this.schemaUrl = descriptor.getSchemaUrl(); this.format = descriptor.getFormat(); this.location = descriptor.getLocation(); if (descriptor.isPartitioned()) { this.partitionStrategy = descriptor.getPartitionStrategy(); } } /** * Configure the dataset's schema. A schema is required, and may be set * using one of the methods: {@code schema}, {@code schemaLiteral}, or * {@code schemaFromAvroDataFile}. * * @return An instance of the builder for method chaining. */ public Builder schema(Schema schema) { this.schema = schema; return this; } /** * Configure the dataset's schema from a {@link File}. A schema is required, * and may be set using one of the methods: {@code schema}, * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. * * @return An instance of the builder for method chaining. */ public Builder schema(File file) throws IOException { this.schema = new Schema.Parser().parse(file); // don't set schema URL since it is a local file not on a DFS return this; } /** * Configure the dataset's schema from an {@link InputStream}. It is the * caller's responsibility to close the {@link InputStream}. A schema is * required, and may be set using one of the methods: {@code schema}, * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. * * @return An instance of the builder for method chaining. */ public Builder schema(InputStream in) throws IOException { this.schema = new Schema.Parser().parse(in); return this; } /** * Configure the dataset's schema from a {@link URI}. A schema is required, * and may be set using one of the methods: {@code schema}, * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. * * @return An instance of the builder for method chaining. */ public Builder schema(URI uri) throws IOException { this.schemaUrl = toURL(uri); InputStream in = null; boolean threw = true; try { in = schemaUrl.openStream(); threw = false; return schema(in); } finally { Closeables.close(in, threw); } } /** * Configure the {@link Dataset}'s schema from a String URI. A schema is * required, and may be set using one of the methods: {@code schema}, * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. * @param uri * @return * @throws URISyntaxException * @throws MalformedURLException * @throws IOException */ public Builder schema(String uri) throws URISyntaxException, MalformedURLException, IOException { return schema(new URI(uri)); } private URL toURL(URI uri) throws MalformedURLException { try { // try with installed URLStreamHandlers first... return uri.toURL(); } catch (MalformedURLException e) { // if that fails then try using the Hadoop protocol handler return new URL(null, uri.toString(), new HadoopFileSystemURLStreamHandler()); } } /** * Configure the dataset's schema from a {@link String}. A schema is * required, and may be set using one of the methods: {@code schema}, * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. * * @return An instance of the builder for method chaining. * @since 0.2.0 */ public Builder schemaLiteral(String s) { this.schema = new Schema.Parser().parse(s); return this; } /** * Configure the dataset's schema via a Java class type. A schema is * required, and may be set using one of the methods: {@code schema}, * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. * * @return An instance of the builder for method chaining. * @since 0.2.0 */ public <T> Builder schema(Class<T> type) { this.schema = ReflectData.get().getSchema(type); return this; } /** * Configure the dataset's schema by using the schema from an existing Avro * data file. A schema is required, and may be set using one of the * <code>schema</code> or <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schemaFromAvroDataFile(File file) throws IOException { GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileReader<GenericRecord> reader = null; boolean threw = true; try { reader = new DataFileReader<GenericRecord>(file, datumReader); this.schema = reader.getSchema(); threw = false; } finally { Closeables.close(reader, threw); } return this; } /** * Configure the dataset's schema by using the schema from an existing Avro * data file. It is the caller's responsibility to close the * {@link InputStream}. A schema is required, and may be set using one of * the <code>schema</code> or <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schemaFromAvroDataFile(InputStream in) throws IOException { GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileStream<GenericRecord> stream = null; boolean threw = true; try { stream = new DataFileStream<GenericRecord>(in, datumReader); this.schema = stream.getSchema(); threw = false; } finally { Closeables.close(stream, threw); } return this; } /** * Configure the dataset's schema by using the schema from an existing Avro * data file. A schema is required, and may be set using one of the * <code>schema</code> or <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schemaFromAvroDataFile(URI uri) throws IOException { InputStream in = null; boolean threw = true; try { in = toURL(uri).openStream(); threw = false; return schemaFromAvroDataFile(in); } finally { Closeables.close(in, threw); } } /** * Configure the dataset's format (optional). If not specified * {@link Formats#AVRO} is used by default. * * @return An instance of the builder for method chaining. * @since 0.2.0 */ public Builder format(Format format) { this.format = format; return this; } /** * Configure the dataset's format from a format name String (optional). If * not specified, {@link Formats#AVRO} will be used. * * @param formatName a String format name * @return An instance of the builder for method chaining. * @throws UnknownFormatException if the format name is not recognized. */ public Builder format(String formatName) { boolean found = false; for (Format knownFormat : Arrays.asList(Formats.AVRO, Formats.PARQUET)) { if (knownFormat.getName().equals(formatName)) { this.format = knownFormat; found = true; break; } } if (!found) { throw new UnknownFormatException( "Cannot find a known format named:" + formatName); } return this; } /** * Configure the {@link Dataset}'s location (optional). * * @param uri A URI location * @return An instance of the builder for method chaining. */ public Builder location(URI uri) { this.location = uri; return this; } /** * Configure the {@link Dataset}'s location (optional). * * @param uri A location URI string * @return An instance of the builder for method chaining. * @throws URISyntaxException */ public Builder location(String uri) throws URISyntaxException { return location(new URI(uri)); } /** * Configure the dataset's partitioning strategy (optional). * * @return An instance of the builder for method chaining. */ public Builder partitionStrategy( @Nullable PartitionStrategy partitionStrategy) { this.partitionStrategy = partitionStrategy; return this; } /** * Get an instance of the configured dataset descriptor. Subsequent calls * will produce new instances that are similarly configure. */ @Override public DatasetDescriptor get() { Preconditions.checkState(schema != null, "Descriptor schema may not be null"); return new DatasetDescriptor(schema, schemaUrl, format, location, partitionStrategy); } } }
cdk-data/cdk-data-core/src/main/java/com/cloudera/cdk/data/DatasetDescriptor.java
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.cdk.data; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.io.Closeables; import java.net.MalformedURLException; import java.net.URI; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileStream; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.avro.reflect.ReflectData; /** * <p> * The structural definition of a {@link Dataset}. * </p> * <p> * Each {@code Dataset} has an associated {@link Schema} and optional * {@link PartitionStrategy} defined at the time of creation. Instances of this * class are used to hold this information. Users are strongly encouraged to use * the inner {@link Builder} to create new instances. * </p> */ @Immutable public class DatasetDescriptor { private final Schema schema; private final URL schemaUrl; private final Format format; private final PartitionStrategy partitionStrategy; /** * Create an instance of this class with the supplied {@link Schema}, * and optional {@link PartitionStrategy}. The default {@link Format}, * {@link Formats#AVRO}, will be used. */ public DatasetDescriptor(Schema schema, @Nullable PartitionStrategy partitionStrategy) { this(schema, null, Formats.AVRO, partitionStrategy); } /** * Create an instance of this class with the supplied {@link Schema}, optional URL, * {@link Format} and optional {@link PartitionStrategy}. */ DatasetDescriptor(Schema schema, @Nullable URL schemaUrl, Format format, @Nullable PartitionStrategy partitionStrategy) { this.schema = schema; this.schemaUrl = schemaUrl; this.format = format; this.partitionStrategy = partitionStrategy; } /** * Get the associated {@link Schema}. Depending on the underlying storage * system, this schema may be simple (i.e. records made up of only scalar * types) or complex (i.e. containing other records, lists, and so on). * Validation of the supported schemas is performed by the managing * repository, not the dataset or descriptor itself. * * @return the schema */ public Schema getSchema() { return schema; } /** * Get a URL from which the {@link Schema} may be retrieved. Optional. This method * may return <code>null</code> if the schema is not stored at a persistent URL, * e.g. if it was constructed from a literal string. * * @return a URL from which the schema may be retrieved * @since 0.3.0 */ @Nullable public URL getSchemaUrl() { return schemaUrl; } /** * Get the associated {@link Format} that the data is stored in. * * @return the format * @since 0.2.0 */ public Format getFormat() { return format; } /** * Get the {@link PartitionStrategy}, if this dataset is partitioned. Calling * this method on a non-partitioned dataset is an error. Instead, use the * {@link #isPartitioned()} method prior to invocation. */ public PartitionStrategy getPartitionStrategy() { Preconditions .checkState( isPartitioned(), "Attempt to retrieve the partition strategy on a non-partitioned descriptor:%s", this); return partitionStrategy; } /** * Returns true if an associated dataset is partitioned (that is, has an * associated {@link PartitionStrategy}), false otherwise. */ public boolean isPartitioned() { return partitionStrategy != null; } @Override public String toString() { return Objects.toStringHelper(this).add("schema", schema) .add("partitionStrategy", partitionStrategy).toString(); } /** * A fluent builder to aid in the construction of {@link DatasetDescriptor}s. */ public static class Builder implements Supplier<DatasetDescriptor> { private Schema schema; private URL schemaUrl; private Format format = Formats.AVRO; private PartitionStrategy partitionStrategy; public Builder() { } /** * Creates a Builder configured to copy {@code descriptor}, if it is not * modified. This is intended to help callers copy and update descriptors * even though they are {@link Immutable}. * * @param descriptor A {@link DatasetDescriptor} to copy settings from * @since 0.7.0 */ public Builder(DatasetDescriptor descriptor) { this.schema = descriptor.getSchema(); this.schemaUrl = descriptor.getSchemaUrl(); this.format = descriptor.getFormat(); if (descriptor.isPartitioned()) { this.partitionStrategy = descriptor.getPartitionStrategy(); } } /** * Configure the dataset's schema. A schema is required, and may be set * using one of the <code>schema</code> or * <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schema(Schema schema) { this.schema = schema; return this; } /** * Configure the dataset's schema from a {@link File}. A schema is required, * and may be set using one of the <code>schema</code> or * <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schema(File file) throws IOException { this.schema = new Schema.Parser().parse(file); // don't set schema URL since it is a local file not on a DFS return this; } /** * Configure the dataset's schema from an {@link InputStream}. It is the * caller's responsibility to close the {@link InputStream}. A schema is * required, and may be set using one of the <code>schema</code> or * <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schema(InputStream in) throws IOException { this.schema = new Schema.Parser().parse(in); return this; } /** * Configure the dataset's schema from a {@link URI}. A schema is required, * and may be set using one of the <code>schema</code> or * <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schema(URI uri) throws IOException { this.schemaUrl = toURL(uri); InputStream in = null; boolean threw = true; try { in = schemaUrl.openStream(); threw = false; return schema(in); } finally { Closeables.close(in, threw); } } private URL toURL(URI uri) throws MalformedURLException { try { // try with installed URLStreamHandlers first... return uri.toURL(); } catch (MalformedURLException e) { // if that fails then try using the Hadoop protocol handler return new URL(null, uri.toString(), new HadoopFileSystemURLStreamHandler()); } } /** * Configure the dataset's schema from a {@link String}. A schema is * required, and may be set using one of the <code>schema</code> or * <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. * @since 0.2.0 */ public Builder schema(String s) { this.schema = new Schema.Parser().parse(s); return this; } /** * Configure the dataset's schema via a Java class type. A schema is required, * and may be set using one of the <code>schema</code> or * <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. * @since 0.2.0 */ public <T> Builder schema(Class<T> type) { this.schema = ReflectData.get().getSchema(type); return this; } /** * Configure the dataset's schema by using the schema from an existing Avro * data file. A schema is required, and may be set using one of the * <code>schema</code> or <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schemaFromAvroDataFile(File file) throws IOException { GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileReader<GenericRecord> reader = null; boolean threw = true; try { reader = new DataFileReader<GenericRecord>(file, datumReader); this.schema = reader.getSchema(); threw = false; } finally { Closeables.close(reader, threw); } return this; } /** * Configure the dataset's schema by using the schema from an existing Avro * data file. It is the caller's responsibility to close the * {@link InputStream}. A schema is required, and may be set using one of * the <code>schema</code> or <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schemaFromAvroDataFile(InputStream in) throws IOException { GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileStream<GenericRecord> stream = null; boolean threw = true; try { stream = new DataFileStream<GenericRecord>(in, datumReader); this.schema = stream.getSchema(); threw = false; } finally { Closeables.close(stream, threw); } return this; } /** * Configure the dataset's schema by using the schema from an existing Avro * data file. A schema is required, and may be set using one of the * <code>schema</code> or <code>schemaFromAvroDataFile</code> methods. * * @return An instance of the builder for method chaining. */ public Builder schemaFromAvroDataFile(URI uri) throws IOException { InputStream in = null; boolean threw = true; try { in = toURL(uri).openStream(); threw = false; return schemaFromAvroDataFile(in); } finally { Closeables.close(in, threw); } } /** * Configure the dataset's format. Optional. If not specified {@link Formats#AVRO} * is used by default. * * @return An instance of the builder for method chaining. * @since 0.2.0 */ public Builder format(Format format) { this.format = format; return this; } /** * Configure the dataset's partitioning strategy. Optional. * * @return An instance of the builder for method chaining. */ public Builder partitionStrategy( @Nullable PartitionStrategy partitionStrategy) { this.partitionStrategy = partitionStrategy; return this; } /** * Get an instance of the configured dataset descriptor. Subsequent calls * will produce new instances that are similarly configure. */ @Override public DatasetDescriptor get() { Preconditions.checkState(schema != null, "Descriptor schema may not be null"); return new DatasetDescriptor(schema, schemaUrl, format, partitionStrategy); } } }
CDK-139: Adding location to DatasetDescriptors. This adds a location URL to the DatasetDescriptor, which is accessible through getLocation(). This also adds location(String) and location(URI) and hasLocation() methods to the Builder and changes the schema(String) to be a URI rather than a schema literal. To set a schema literal from a String, schemaLiteral(String) was added.
cdk-data/cdk-data-core/src/main/java/com/cloudera/cdk/data/DatasetDescriptor.java
CDK-139: Adding location to DatasetDescriptors.
<ide><path>dk-data/cdk-data-core/src/main/java/com/cloudera/cdk/data/DatasetDescriptor.java <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.io.InputStream; <add>import java.net.URISyntaxException; <ide> import java.net.URL; <add>import java.util.Arrays; <ide> import org.apache.avro.reflect.ReflectData; <ide> <ide> /** <ide> private final Schema schema; <ide> private final URL schemaUrl; <ide> private final Format format; <add> private final URI location; <ide> private final PartitionStrategy partitionStrategy; <ide> <ide> /** <ide> public DatasetDescriptor(Schema schema, @Nullable PartitionStrategy <ide> partitionStrategy) { <ide> <del> this(schema, null, Formats.AVRO, partitionStrategy); <del> } <del> <del> /** <del> * Create an instance of this class with the supplied {@link Schema}, optional URL, <del> * {@link Format} and optional {@link PartitionStrategy}. <add> this(schema, null, Formats.AVRO, null, partitionStrategy); <add> } <add> <add> /** <add> * Create an instance of this class with the supplied {@link Schema}, <add> * optional URL, {@link Format}, optional location URL, and optional <add> * {@link PartitionStrategy}. <ide> */ <ide> DatasetDescriptor(Schema schema, @Nullable URL schemaUrl, Format format, <del> @Nullable PartitionStrategy partitionStrategy) { <add> @Nullable URI location, @Nullable PartitionStrategy partitionStrategy) { <ide> <ide> this.schema = schema; <ide> this.schemaUrl = schemaUrl; <ide> this.format = format; <add> this.location = location; <ide> this.partitionStrategy = partitionStrategy; <ide> } <ide> <ide> } <ide> <ide> /** <del> * Get a URL from which the {@link Schema} may be retrieved. Optional. This method <del> * may return <code>null</code> if the schema is not stored at a persistent URL, <del> * e.g. if it was constructed from a literal string. <add> * Get a URL from which the {@link Schema} may be retrieved (optional). This <add> * method may return {@code null} if the schema is not stored at a persistent <add> * URL, e.g. if it was constructed from a literal string. <ide> * <ide> * @return a URL from which the schema may be retrieved <ide> * @since 0.3.0 <ide> */ <ide> public Format getFormat() { <ide> return format; <add> } <add> <add> /** <add> * Get the URL location where the data for this {@link Dataset} is stored <add> * (optional). <add> * <add> * @return a location URL or null if one is not set <add> * <add> * @since 0.8.0 <add> */ <add> @Nullable <add> public URI getLocation() { <add> return location; <ide> } <ide> <ide> /** <ide> private Schema schema; <ide> private URL schemaUrl; <ide> private Format format = Formats.AVRO; <add> private URI location; <ide> private PartitionStrategy partitionStrategy; <ide> <ide> public Builder() { <ide> this.schema = descriptor.getSchema(); <ide> this.schemaUrl = descriptor.getSchemaUrl(); <ide> this.format = descriptor.getFormat(); <add> this.location = descriptor.getLocation(); <ide> <ide> if (descriptor.isPartitioned()) { <ide> this.partitionStrategy = descriptor.getPartitionStrategy(); <ide> <ide> /** <ide> * Configure the dataset's schema. A schema is required, and may be set <del> * using one of the <code>schema</code> or <del> * <code>schemaFromAvroDataFile</code> methods. <add> * using one of the methods: {@code schema}, {@code schemaLiteral}, or <add> * {@code schemaFromAvroDataFile}. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> */ <ide> <ide> /** <ide> * Configure the dataset's schema from a {@link File}. A schema is required, <del> * and may be set using one of the <code>schema</code> or <del> * <code>schemaFromAvroDataFile</code> methods. <add> * and may be set using one of the methods: {@code schema}, <add> * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> */ <ide> /** <ide> * Configure the dataset's schema from an {@link InputStream}. It is the <ide> * caller's responsibility to close the {@link InputStream}. A schema is <del> * required, and may be set using one of the <code>schema</code> or <del> * <code>schemaFromAvroDataFile</code> methods. <add> * required, and may be set using one of the methods: {@code schema}, <add> * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> */ <ide> <ide> /** <ide> * Configure the dataset's schema from a {@link URI}. A schema is required, <del> * and may be set using one of the <code>schema</code> or <del> * <code>schemaFromAvroDataFile</code> methods. <add> * and may be set using one of the methods: {@code schema}, <add> * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> */ <ide> } <ide> } <ide> <add> /** <add> * Configure the {@link Dataset}'s schema from a String URI. A schema is <add> * required, and may be set using one of the methods: {@code schema}, <add> * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. <add> * @param uri <add> * @return <add> * @throws URISyntaxException <add> * @throws MalformedURLException <add> * @throws IOException <add> */ <add> public Builder schema(String uri) throws <add> URISyntaxException, MalformedURLException, IOException { <add> return schema(new URI(uri)); <add> } <add> <ide> private URL toURL(URI uri) throws MalformedURLException { <ide> try { <ide> // try with installed URLStreamHandlers first... <ide> <ide> /** <ide> * Configure the dataset's schema from a {@link String}. A schema is <del> * required, and may be set using one of the <code>schema</code> or <del> * <code>schemaFromAvroDataFile</code> methods. <add> * required, and may be set using one of the methods: {@code schema}, <add> * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> * @since 0.2.0 <ide> */ <del> public Builder schema(String s) { <add> public Builder schemaLiteral(String s) { <ide> this.schema = new Schema.Parser().parse(s); <ide> return this; <ide> } <ide> <ide> /** <del> * Configure the dataset's schema via a Java class type. A schema is required, <del> * and may be set using one of the <code>schema</code> or <del> * <code>schemaFromAvroDataFile</code> methods. <add> * Configure the dataset's schema via a Java class type. A schema is <add> * required, and may be set using one of the methods: {@code schema}, <add> * {@code schemaLiteral}, or {@code schemaFromAvroDataFile}. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> * @since 0.2.0 <ide> } <ide> <ide> /** <del> * Configure the dataset's format. Optional. If not specified {@link Formats#AVRO} <del> * is used by default. <add> * Configure the dataset's format (optional). If not specified <add> * {@link Formats#AVRO} is used by default. <ide> * <ide> * @return An instance of the builder for method chaining. <ide> * @since 0.2.0 <ide> } <ide> <ide> /** <del> * Configure the dataset's partitioning strategy. Optional. <add> * Configure the dataset's format from a format name String (optional). If <add> * not specified, {@link Formats#AVRO} will be used. <add> * <add> * @param formatName a String format name <add> * @return An instance of the builder for method chaining. <add> * @throws UnknownFormatException if the format name is not recognized. <add> */ <add> public Builder format(String formatName) { <add> boolean found = false; <add> for (Format knownFormat : Arrays.asList(Formats.AVRO, Formats.PARQUET)) { <add> if (knownFormat.getName().equals(formatName)) { <add> this.format = knownFormat; <add> found = true; <add> break; <add> } <add> } <add> if (!found) { <add> throw new UnknownFormatException( <add> "Cannot find a known format named:" + formatName); <add> } <add> return this; <add> } <add> <add> /** <add> * Configure the {@link Dataset}'s location (optional). <add> * <add> * @param uri A URI location <add> * @return An instance of the builder for method chaining. <add> */ <add> public Builder location(URI uri) { <add> this.location = uri; <add> return this; <add> } <add> <add> /** <add> * Configure the {@link Dataset}'s location (optional). <add> * <add> * @param uri A location URI string <add> * @return An instance of the builder for method chaining. <add> * @throws URISyntaxException <add> */ <add> public Builder location(String uri) throws URISyntaxException { <add> return location(new URI(uri)); <add> } <add> <add> /** <add> * Configure the dataset's partitioning strategy (optional). <ide> * <ide> * @return An instance of the builder for method chaining. <ide> */ <ide> Preconditions.checkState(schema != null, <ide> "Descriptor schema may not be null"); <ide> <del> return new DatasetDescriptor(schema, schemaUrl, format, partitionStrategy); <add> return new DatasetDescriptor(schema, schemaUrl, format, location, partitionStrategy); <ide> } <ide> <ide> }
Java
apache-2.0
53f038ff2cbbd27a085219687191c315404ebd0e
0
apache/wicket,bitstorm/wicket,martin-g/wicket-osgi,mosoft521/wicket,bitstorm/wicket,selckin/wicket,apache/wicket,dashorst/wicket,freiheit-com/wicket,AlienQueen/wicket,freiheit-com/wicket,mosoft521/wicket,AlienQueen/wicket,dashorst/wicket,selckin/wicket,astrapi69/wicket,mosoft521/wicket,klopfdreh/wicket,klopfdreh/wicket,AlienQueen/wicket,klopfdreh/wicket,dashorst/wicket,Servoy/wicket,selckin/wicket,aldaris/wicket,apache/wicket,AlienQueen/wicket,apache/wicket,bitstorm/wicket,freiheit-com/wicket,mosoft521/wicket,klopfdreh/wicket,topicusonderwijs/wicket,astrapi69/wicket,dashorst/wicket,selckin/wicket,astrapi69/wicket,mafulafunk/wicket,zwsong/wicket,Servoy/wicket,Servoy/wicket,selckin/wicket,topicusonderwijs/wicket,dashorst/wicket,zwsong/wicket,freiheit-com/wicket,topicusonderwijs/wicket,Servoy/wicket,aldaris/wicket,klopfdreh/wicket,mosoft521/wicket,zwsong/wicket,AlienQueen/wicket,mafulafunk/wicket,topicusonderwijs/wicket,apache/wicket,topicusonderwijs/wicket,martin-g/wicket-osgi,astrapi69/wicket,bitstorm/wicket,aldaris/wicket,bitstorm/wicket,zwsong/wicket,aldaris/wicket,mafulafunk/wicket,Servoy/wicket,martin-g/wicket-osgi,aldaris/wicket,freiheit-com/wicket
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.model; import org.apache.wicket.Component; /** * This is a marker interface for models that can be inherited from components higher in the * hierarchy. * * If a model implements this interface then you can give the parent container this model and all * the child (recursively) components will also get and then set that model on their own if they are * created with a null model * * <pre> * Form form = new Form(&quot;form&quot;, new ModelImplementingIInheritableModel()); * new TextField(&quot;textfield&quot;); // notice textfield is created with a null model * </pre> * * @author jcompagner * @author Igor Vaynberg (ivaynberg) */ public interface IComponentInheritedModel extends IModel { /** * @param component * @return The WrapModel that wraps this model */ IWrapModel wrapOnInheritance(Component component); }
jdk-1.4/wicket/src/main/java/org/apache/wicket/model/IComponentInheritedModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.model; import org.apache.wicket.Component; /** * This is a marker interface for models that can be inherited from components higher in the * hierarchy. * * If a model implements this interface then you can give the parent container this model and all * the child (recursively) components will also get and then set that model on their own if they are * created with a null model * * <pre> * Form form = new Form(getPage(), &quot;form&quot;, new ModelImplementingIInheritableModel()); * new TextField(form, &quot;textfield&quot;); // notice textfield is created with a null model * </pre> * * @author jcompagner * @author Igor Vaynberg (ivaynberg) */ public interface IComponentInheritedModel extends IModel { /** * @param component * @return The WrapModel that wraps this model */ IWrapModel wrapOnInheritance(Component component); }
WICKET-1461: javadoc fixes git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@642535 13f79535-47bb-0310-9956-ffa450edef68
jdk-1.4/wicket/src/main/java/org/apache/wicket/model/IComponentInheritedModel.java
WICKET-1461: javadoc fixes
<ide><path>dk-1.4/wicket/src/main/java/org/apache/wicket/model/IComponentInheritedModel.java <ide> * created with a null model <ide> * <ide> * <pre> <del> * Form form = new Form(getPage(), &quot;form&quot;, new ModelImplementingIInheritableModel()); <del> * new TextField(form, &quot;textfield&quot;); // notice textfield is created with a null model <add> * Form form = new Form(&quot;form&quot;, new ModelImplementingIInheritableModel()); <add> * new TextField(&quot;textfield&quot;); // notice textfield is created with a null model <ide> * </pre> <ide> * <ide> * @author jcompagner
Java
mit
eca531a395c9cbf0ae5ba4b5c331deb4a45c96e9
0
kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper
package us.kbase.narrativejobservice.sdkjobs; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.model.AccessMode; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Volume; import com.google.common.html.HtmlEscapers; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import us.kbase.auth.AuthConfig; import us.kbase.auth.AuthToken; import us.kbase.auth.ConfigurableAuthService; import us.kbase.catalog.*; import us.kbase.common.executionengine.*; import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig; import us.kbase.common.service.*; import us.kbase.common.utils.NetUtils; import us.kbase.narrativejobservice.*; import us.kbase.narrativejobservice.JobState; import us.kbase.narrativejobservice.MethodCall; import us.kbase.narrativejobservice.RpcContext; import us.kbase.narrativejobservice.subjobs.NJSCallbackServer; import java.io.*; import java.net.*; import java.nio.file.Paths; import java.time.Instant; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SDKLocalMethodRunner { private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(); public static final String DEV = JobRunnerConstants.DEV; public static final String BETA = JobRunnerConstants.BETA; public static final String RELEASE = JobRunnerConstants.RELEASE; public static final Set<String> RELEASE_TAGS = JobRunnerConstants.RELEASE_TAGS; private static final long MAX_OUTPUT_SIZE = JobRunnerConstants.MAX_IO_BYTE_SIZE; public static final String JOB_CONFIG_FILE = JobRunnerConstants.JOB_CONFIG_FILE; public static final String CFG_PROP_EE_SERVER_VERSION = JobRunnerConstants.CFG_PROP_EE_SERVER_VERSION; public static final String CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS = JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS; public static long milliSecondsToLive(String token, Map<String, String> config) throws Exception { String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2); } //Check to see if http links are allowed String authAllowInsecure = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM); if (!"true".equals(authAllowInsecure) && !authUrl.startsWith("https://")) { throw new Exception("Only https links are allowed: " + authUrl); } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet request = new HttpGet(authUrl); request.setHeader(HttpHeaders.AUTHORIZATION, token); InputStream response = httpclient.execute(request).getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jsonMap = mapper.readValue(response, Map.class); Object expire = jsonMap.getOrDefault("expires", null); //Calculate ms till expiration if (expire == null) throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString()); long ms = ((long) expire - Instant.now().toEpochMilli()); //Time of token expiration - N time String time_before_expiration = config.get(NarrativeJobServiceServer.CFG_PROP_TIME_BEFORE_EXPIRATION); //10 Minute Default if (time_before_expiration == null) return ms - (10 * 60 * 1000); //Number of minutes / 60 * 1000 return ms - (Long.parseLong(time_before_expiration) / 60) * 1000; } public static void canceljob(NarrativeJobServiceClient jobSrvClient, String jobId) throws Exception { jobSrvClient.cancelJob(new CancelJobParams().withJobId(jobId)); } public static void main(String[] args) throws Exception { System.out.println("Starting docker runner EDIT EDIT EDIT with args " + StringUtils.join(args, ", ")); if (args.length != 2) { System.err.println("Usage: <program> <job_id> <job_service_url>"); for (int i = 0; i < args.length; i++) System.err.println("\tArgument[" + i + "]: " + args[i]); System.exit(1); } Thread shutdownHook = new Thread() { @Override public void run() { try { DockerRunner.killSubJobs(); } catch (Exception e) { e.printStackTrace(); } } }; Runtime.getRuntime().addShutdownHook(shutdownHook); String[] hostnameAndIP = getHostnameAndIP(); final String jobId = args[0]; String jobSrvUrl = args[1]; String tokenStr = System.getenv("KB_AUTH_TOKEN"); if (tokenStr == null || tokenStr.isEmpty()) tokenStr = System.getProperty("KB_AUTH_TOKEN"); // For tests if (tokenStr == null || tokenStr.isEmpty()) throw new IllegalStateException("Token is not defined"); // We should skip token validation now because we don't have auth service URL yet. final AuthToken tempToken = new AuthToken(tokenStr, "<unknown>"); final NarrativeJobServiceClient jobSrvClient = getJobClient( jobSrvUrl, tempToken); Thread logFlusher = null; final List<LogLine> logLines = new ArrayList<LogLine>(); final LineLogger log = new LineLogger() { @Override public void logNextLine(String line, boolean isError) { addLogLine(jobSrvClient, jobId, logLines, new LogLine().withLine(line) .withIsError(isError ? 1L : 0L)); } }; Server callbackServer = null; try { JobState jobState = jobSrvClient.checkJob(jobId); if (jobState.getFinished() != null && jobState.getFinished() == 1L) { if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) { log.logNextLine("Job was canceled", false); } else { log.logNextLine("Job was already done before", true); } flushLog(jobSrvClient, jobId, logLines); return; } Tuple2<RunJobParams, Map<String, String>> jobInput = jobSrvClient.getJobParams(jobId); Map<String, String> config = jobInput.getE2(); if (System.getenv("CALLBACK_INTERFACE") != null) config.put(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS, System.getenv("CALLBACK_INTERFACE")); if (System.getenv("REFDATA_DIR") != null) config.put(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE, System.getenv("REFDATA_DIR")); ConfigurableAuthService auth = getAuth(config); // We couldn't validate token earlier because we didn't have auth service URL. AuthToken token = auth.validateToken(tokenStr); final URL catalogURL = getURL(config, NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL); final URI dockerURI = getURI(config, NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_DOCKER_URI, true); RunJobParams job = jobInput.getE1(); for (String msg : jobSrvClient.updateJob(new UpdateJobParams().withJobId(jobId) .withIsStarted(1L)).getMessages()) { log.logNextLine(msg, false); } File jobDir = getJobDir(jobInput.getE2(), jobId); if (!mountExists()) { log.logNextLine("Cannot find mount point as defined in condor-submit-workdir", true); throw new IOException("Cannot find mount point condor-submit-workdir"); } final ModuleMethod modMeth = new ModuleMethod(job.getMethod()); RpcContext context = job.getRpcContext(); if (context == null) context = new RpcContext().withRunId(""); if (context.getCallStack() == null) context.setCallStack(new ArrayList<MethodCall>()); context.getCallStack().add(new MethodCall().withJobId(jobId).withMethod(job.getMethod()) .withTime(DATE_FORMATTER.print(new DateTime()))); Map<String, Object> rpc = new LinkedHashMap<String, Object>(); rpc.put("version", "1.1"); rpc.put("method", job.getMethod()); rpc.put("params", job.getParams()); rpc.put("context", context); File workDir = new File(jobDir, "workdir"); if (!workDir.exists()) workDir.mkdir(); File scratchDir = new File(workDir, "tmp"); if (!scratchDir.exists()) scratchDir.mkdir(); File inputFile = new File(workDir, "input.json"); UObject.getMapper().writeValue(inputFile, rpc); File outputFile = new File(workDir, "output.json"); File configFile = new File(workDir, JOB_CONFIG_FILE); String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT); String clientDetails = hostnameAndIP[1]; String clientName = System.getenv("AWE_CLIENTNAME"); if (clientName != null && !clientName.isEmpty()) { clientDetails += ", client-name=" + clientName; } log.logNextLine("Running on " + hostnameAndIP[0] + " (" + clientDetails + "), in " + new File(".").getCanonicalPath(), false); String clientGroup = System.getenv("AWE_CLIENTGROUP"); if (clientGroup == null) clientGroup = "<unknown>"; log.logNextLine("Client group: " + clientGroup, false); String codeEeVer = NarrativeJobServiceServer.VERSION; String runtimeEeVersion = config.get(CFG_PROP_EE_SERVER_VERSION); if (runtimeEeVersion == null) runtimeEeVersion = "<unknown>"; if (codeEeVer.equals(runtimeEeVersion)) { log.logNextLine("Server version of Execution Engine: " + runtimeEeVersion + " (matches to version of runner script)", false); } else { log.logNextLine("WARNING: Server version of Execution Engine (" + runtimeEeVersion + ") doesn't match to version of runner script " + "(" + codeEeVer + ")", true); } CatalogClient catClient = new CatalogClient(catalogURL, token); catClient.setIsInsecureHttpConnectionAllowed(true); catClient.setAllSSLCertificatesTrusted(true); // the NJSW always passes the githash in service ver final String imageVersion = job.getServiceVer(); final String requestedRelease = (String) job .getAdditionalProperties().get(SDKMethodRunner.REQ_REL); final ModuleVersion mv; try { mv = catClient.getModuleVersion(new SelectModuleVersion() .withModuleName(modMeth.getModule()) .withVersion(imageVersion)); } catch (ServerException se) { throw new IllegalArgumentException(String.format( "Error looking up module %s with version %s: %s", modMeth.getModule(), imageVersion, se.getLocalizedMessage())); } String imageName = mv.getDockerImgName(); File refDataDir = null; String refDataBase = config.get(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE); if (mv.getDataFolder() != null && mv.getDataVersion() != null) { if (refDataBase == null) throw new IllegalStateException("Reference data parameters are defined for image but " + NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE + " property isn't set in configuration"); refDataDir = new File(new File(refDataBase, mv.getDataFolder()), mv.getDataVersion()); if (!refDataDir.exists()) throw new IllegalStateException("Reference data directory doesn't exist: " + refDataDir); } if (imageName == null) { throw new IllegalStateException("Image is not stored in catalog"); } else { log.logNextLine("Image name received from catalog: " + imageName, false); } logFlusher = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } flushLog(jobSrvClient, jobId, logLines); if (Thread.currentThread().isInterrupted()) break; } } }); logFlusher.setDaemon(true); logFlusher.start(); // Let's check if there are some volume mount rules or secure configuration parameters // set up for this module List<Bind> additionalBinds = null; Map<String, String> envVars = null; List<SecureConfigParameter> secureCfgParams = null; String adminTokenStr = System.getenv("KB_ADMIN_AUTH_TOKEN"); if (adminTokenStr == null || adminTokenStr.isEmpty()) adminTokenStr = System.getProperty("KB_ADMIN_AUTH_TOKEN"); // For tests String miniKB = System.getenv("MINI_KB"); boolean useVolumeMounts = true; if (miniKB != null && !miniKB.isEmpty() && miniKB.equals("true")) { useVolumeMounts = false; } if (adminTokenStr != null && !adminTokenStr.isEmpty() && useVolumeMounts) { final AuthToken adminToken = auth.validateToken(adminTokenStr); final CatalogClient adminCatClient = new CatalogClient(catalogURL, adminToken); adminCatClient.setIsInsecureHttpConnectionAllowed(true); adminCatClient.setAllSSLCertificatesTrusted(true); List<VolumeMountConfig> vmc = null; try { vmc = adminCatClient.listVolumeMounts(new VolumeMountFilter().withModuleName( modMeth.getModule()).withClientGroup(clientGroup) .withFunctionName(modMeth.getMethod())); } catch (Exception ex) { log.logNextLine("Error requesing volume mounts from Catalog: " + ex.getMessage(), true); } if (vmc != null && vmc.size() > 0) { if (vmc.size() > 1) throw new IllegalStateException("More than one rule for Docker volume mounts was found"); additionalBinds = new ArrayList<Bind>(); for (VolumeMount vm : vmc.get(0).getVolumeMounts()) { boolean isReadOnly = vm.getReadOnly() != null && vm.getReadOnly() != 0L; File hostDir = new File(processHostPathForVolumeMount(vm.getHostDir(), token.getUserName())); if (!hostDir.exists()) { if (isReadOnly) { throw new IllegalStateException("Volume mount directory doesn't exist: " + hostDir); } else { hostDir.mkdirs(); } } String contDir = vm.getContainerDir(); AccessMode am = isReadOnly ? AccessMode.ro : AccessMode.rw; additionalBinds.add(new Bind(hostDir.getCanonicalPath(), new Volume(contDir), am)); } } secureCfgParams = adminCatClient.getSecureConfigParams( new GetSecureConfigParamsInput().withModuleName(modMeth.getModule()) .withVersion(mv.getGitCommitHash()).withLoadAllVersions(0L)); envVars = new TreeMap<String, String>(); for (SecureConfigParameter param : secureCfgParams) { envVars.put("KBASE_SECURE_CONFIG_PARAM_" + param.getParamName(), param.getParamValue()); } } PrintWriter pw = new PrintWriter(configFile); pw.println("[global]"); if (kbaseEndpoint != null) pw.println("kbase_endpoint = " + kbaseEndpoint); pw.println("job_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL)); pw.println("workspace_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL)); pw.println("shock_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SHOCK_URL)); pw.println("handle_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_HANDLE_SRV_URL)); pw.println("srv_wiz_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SRV_WIZ_URL)); pw.println("njsw_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL)); pw.println("auth_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL)); pw.println("auth_service_url_allow_insecure = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM)); if (secureCfgParams != null) { for (SecureConfigParameter param : secureCfgParams) { pw.println(param.getParamName() + " = " + param.getParamValue()); } } pw.close(); // Cancellation checker CancellationChecker cancellationChecker = new CancellationChecker() { Boolean canceled = null; @Override public boolean isJobCanceled() { if (canceled != null) return canceled; try { final CheckJobCanceledResult jobState = jobSrvClient.checkJobCanceled( new CancelJobParams().withJobId(jobId)); if (jobState.getFinished() != null && jobState.getFinished() == 1L) { canceled = true; if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) { // Print cancellation message after DockerRunner is done } else { log.logNextLine("Job was registered as finished by another worker", true); } flushLog(jobSrvClient, jobId, logLines); return true; } } catch (Exception ex) { log.logNextLine("Non-critical error checking for job cancelation - " + String.format("Will check again in %s seconds. ", DockerRunner.CANCELLATION_CHECK_PERIOD_SEC) + "Error reported by execution engine was: " + HtmlEscapers.htmlEscaper().escape(ex.getMessage()), true); } return false; } }; // Starting up callback server String[] callbackNetworks = null; String callbackNetworksText = config.get(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS); if (callbackNetworksText != null) { callbackNetworks = callbackNetworksText.trim().split("\\s*,\\s*"); } final int callbackPort = NetUtils.findFreePort(); final URL callbackUrl = CallbackServer. getCallbackUrl(callbackPort, callbackNetworks); if (callbackUrl != null) { log.logNextLine("Job runner recieved callback URL: " + callbackUrl, false); final ModuleRunVersion runver = new ModuleRunVersion( new URL(mv.getGitUrl()), modMeth, mv.getGitCommitHash(), mv.getVersion(), requestedRelease); final CallbackServerConfig cbcfg = new CallbackServerConfigBuilder(config, callbackUrl, jobDir.toPath(), Paths.get(refDataBase), log).build(); final JsonServerServlet callback = new NJSCallbackServer( token, cbcfg, runver, job.getParams(), job.getSourceWsObjects(), additionalBinds, cancellationChecker); callbackServer = new Server(callbackPort); final ServletContextHandler srvContext = new ServletContextHandler( ServletContextHandler.SESSIONS); srvContext.setContextPath("/"); callbackServer.setHandler(srvContext); srvContext.addServlet(new ServletHolder(callback), "/*"); callbackServer.start(); } else { if (callbackNetworks != null && callbackNetworks.length > 0) { throw new IllegalStateException("No proper callback IP was found, " + "please check 'awe.client.callback.networks' parameter in " + "execution engine configuration"); } log.logNextLine("WARNING: No callback URL was recieved " + "by the job runner. Local callbacks are disabled.", true); } Map<String, String> labels = new HashMap<>(); labels.put("job_id", "" + jobId); labels.put("image_name", imageName); String method = job.getMethod(); String[] appNameMethodName = method.split("\\."); if (appNameMethodName.length == 2) { labels.put("app_name", appNameMethodName[0]); labels.put("method_name", appNameMethodName[1]); } else { labels.put("app_name", method); labels.put("method_name", method); } labels.put("parent_job_id", job.getParentJobId()); labels.put("image_version", imageVersion); labels.put("wsid", "" + job.getWsid()); labels.put("app_id", "" + job.getAppId()); labels.put("user_name", token.getUserName()); Map<String, String> resourceRequirements = new HashMap<String, String>(); String[] resourceStrings = {"request_cpus", "request_memory", "request_disk"}; for (String resourceKey : resourceStrings) { String resourceValue = System.getenv(resourceKey); if (resourceValue != null && !resourceKey.isEmpty()) { resourceRequirements.put(resourceKey, resourceValue); } } if (resourceRequirements.isEmpty()) { resourceRequirements = null; log.logNextLine("Resource Requirements are not specified.", false); } else { log.logNextLine("Resource Requirements are:", false); log.logNextLine(resourceRequirements.toString(), false); } //Get number of milliseconds to live for this token //Set a timer before job is cancelled for having an expired token to //the expiration time minus 10 minutes (default) or higher final long msToLive = milliSecondsToLive(tokenStr, config); Thread tokenExpirationHook = new Thread() { @Override public void run() { try { if (msToLive > 0) { Thread.sleep(msToLive); canceljob(jobSrvClient, jobId); log.logNextLine("Job was canceled due to token expiration", false); } else { canceljob(jobSrvClient, jobId); log.logNextLine("Job was canceled due to invalid token expiration state:" + msToLive, false); } } catch (Exception e) { e.printStackTrace(); } } }; tokenExpirationHook.start(); // Calling Runner if (System.getenv("USE_SHIFTER") != null) { new ShifterRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log, outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds, cancellationChecker, envVars, labels); } else { new DockerRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log, outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds, cancellationChecker, envVars, labels, resourceRequirements); } if (cancellationChecker.isJobCanceled()) { log.logNextLine("Job was canceled", false); flushLog(jobSrvClient, jobId, logLines); logFlusher.interrupt(); return; } if (outputFile.length() > MAX_OUTPUT_SIZE) { Reader r = new FileReader(outputFile); char[] chars = new char[1000]; r.read(chars); r.close(); String error = "Method " + job.getMethod() + " returned value longer than " + MAX_OUTPUT_SIZE + " bytes. This may happen as a result of returning actual data instead of saving it to " + "kbase data stores (Workspace, Shock, ...) and returning reference to it. Returned " + "value starts with \"" + new String(chars) + "...\""; throw new IllegalStateException(error); } FinishJobParams result = UObject.getMapper().readValue(outputFile, FinishJobParams.class); // flush logs to execution engine if (result.getError() != null) { String err = ""; if (notNullOrEmpty(result.getError().getName())) { err = result.getError().getName(); } if (notNullOrEmpty(result.getError().getMessage())) { if (!err.isEmpty()) { err += ": "; } err += result.getError().getMessage(); } if (notNullOrEmpty(result.getError().getError())) { if (!err.isEmpty()) { err += "\n"; } err += result.getError().getError(); } if (err == "") err = "Unknown error (please ask administrator for details providing full output log)"; log.logNextLine("Error: " + err, true); } else { log.logNextLine("Job is done", false); } flushLog(jobSrvClient, jobId, logLines); // push results to execution engine jobSrvClient.finishJob(jobId, result); logFlusher.interrupt(); //Turn off cancellation hook tokenExpirationHook.interrupt(); } catch (Exception ex) { ex.printStackTrace(); try { flushLog(jobSrvClient, jobId, logLines); } catch (Exception ignore) { } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.close(); String err = "Fatal error: " + sw.toString(); if (ex instanceof ServerException) { err += "\nServer exception:\n" + ((ServerException) ex).getData(); } try { log.logNextLine(err, true); flushLog(jobSrvClient, jobId, logLines); logFlusher.interrupt(); } catch (Exception ignore) { } try { FinishJobParams result = new FinishJobParams().withError( new JsonRpcError().withCode(-1L).withName("JSONRPCError") .withMessage("Job service side error: " + ex.getMessage()) .withError(err)); jobSrvClient.finishJob(jobId, result); } catch (Exception ex2) { ex2.printStackTrace(); } } finally { if (callbackServer != null) try { callbackServer.stop(); System.out.println("Callback server was shutdown"); } catch (Exception ignore) { System.err.println("Error shutting down callback server: " + ignore.getMessage()); } } Runtime.getRuntime().removeShutdownHook(shutdownHook); } public static String processHostPathForVolumeMount(String path, String username) { return path.replace("${username}", username); } private static boolean notNullOrEmpty(final String s) { return s != null && !s.isEmpty(); } private static synchronized void addLogLine(NarrativeJobServiceClient jobSrvClient, String jobId, List<LogLine> logLines, LogLine line) { logLines.add(line); if (line.getIsError() != null && line.getIsError() == 1L) { System.err.println(line.getLine()); } else { System.out.println(line.getLine()); } } private static synchronized void flushLog(NarrativeJobServiceClient jobSrvClient, String jobId, List<LogLine> logLines) { if (logLines.isEmpty()) return; try { jobSrvClient.addJobLogs(jobId, logLines); logLines.clear(); } catch (Exception ex) { ex.printStackTrace(); } } public static String decamelize(final String s) { final Matcher m = Pattern.compile("([A-Z])").matcher(s.substring(1)); return (s.substring(0, 1) + m.replaceAll("_$1")).toLowerCase(); } private static File getJobDir(Map<String, String> config, String jobId) { String rootDirPath = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_SCRATCH); File rootDir = new File(rootDirPath == null ? "." : rootDirPath); if (!rootDir.exists()) rootDir.mkdirs(); File ret = new File(rootDir, "job_" + jobId); if (!ret.exists()) ret.mkdir(); return ret; } /** * Check to see if the basedir exists, which is in * a format similar to /mnt/condor/<username> * * @return */ private static boolean mountExists() { File mountPath = new File(System.getenv("BASE_DIR")); return mountPath.exists() && mountPath.canWrite(); } public static NarrativeJobServiceClient getJobClient(String jobSrvUrl, AuthToken token) throws UnauthorizedException, IOException, MalformedURLException { final NarrativeJobServiceClient jobSrvClient = new NarrativeJobServiceClient(new URL(jobSrvUrl), token); jobSrvClient.setIsInsecureHttpConnectionAllowed(true); return jobSrvClient; } private static ConfigurableAuthService getAuth(final Map<String, String> config) throws Exception { String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL); } String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM); final AuthConfig c = new AuthConfig().withKBaseAuthServerURL(new URL(authUrl)); if ("true".equals(authAllowInsecure)) { c.withAllowInsecureURLs(true); } return new ConfigurableAuthService(c); } private static URL getURL(final Map<String, String> config, final String param) { final String urlStr = config.get(param); if (urlStr == null || urlStr.isEmpty()) { throw new IllegalStateException("Parameter '" + param + "' is not defined in configuration"); } try { return new URL(urlStr); } catch (MalformedURLException mal) { throw new IllegalStateException("The configuration parameter '" + param + " = " + urlStr + "' is not a valid URL"); } } private static URI getURI(final Map<String, String> config, final String param, boolean allowAbsent) { final String urlStr = config.get(param); if (urlStr == null || urlStr.isEmpty()) { if (allowAbsent) { return null; } throw new IllegalStateException("Parameter '" + param + "' is not defined in configuration"); } try { return new URI(urlStr); } catch (URISyntaxException use) { throw new IllegalStateException("The configuration parameter '" + param + " = " + urlStr + "' is not a valid URI"); } } public static String[] getHostnameAndIP() { String hostname = null; String ip = null; try { InetAddress ia = InetAddress.getLocalHost(); ip = ia.getHostAddress(); hostname = ia.getHostName(); } catch (Throwable ignore) { } if (hostname == null) { try { hostname = System.getenv("HOSTNAME"); if (hostname != null && hostname.isEmpty()) hostname = null; } catch (Throwable ignore) { } } if (ip == null && hostname != null) { try { ip = InetAddress.getByName(hostname).getHostAddress(); } catch (Throwable ignore) { } } return new String[]{hostname == null ? "unknown" : hostname, ip == null ? "unknown" : ip}; } }
src/us/kbase/narrativejobservice/sdkjobs/SDKLocalMethodRunner.java
package us.kbase.narrativejobservice.sdkjobs; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.model.AccessMode; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Volume; import com.google.common.html.HtmlEscapers; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import us.kbase.auth.AuthConfig; import us.kbase.auth.AuthToken; import us.kbase.auth.ConfigurableAuthService; import us.kbase.catalog.*; import us.kbase.common.executionengine.*; import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig; import us.kbase.common.service.*; import us.kbase.common.utils.NetUtils; import us.kbase.narrativejobservice.*; import us.kbase.narrativejobservice.JobState; import us.kbase.narrativejobservice.MethodCall; import us.kbase.narrativejobservice.RpcContext; import us.kbase.narrativejobservice.subjobs.NJSCallbackServer; import java.io.*; import java.net.*; import java.nio.file.Paths; import java.time.Instant; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SDKLocalMethodRunner { private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(); public static final String DEV = JobRunnerConstants.DEV; public static final String BETA = JobRunnerConstants.BETA; public static final String RELEASE = JobRunnerConstants.RELEASE; public static final Set<String> RELEASE_TAGS = JobRunnerConstants.RELEASE_TAGS; private static final long MAX_OUTPUT_SIZE = JobRunnerConstants.MAX_IO_BYTE_SIZE; public static final String JOB_CONFIG_FILE = JobRunnerConstants.JOB_CONFIG_FILE; public static final String CFG_PROP_EE_SERVER_VERSION = JobRunnerConstants.CFG_PROP_EE_SERVER_VERSION; public static final String CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS = JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS; public static long milliSecondsToLive(String token, Map<String, String> config) throws Exception { String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2); } //Check to see if http links are allowed String authAllowInsecure = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM); if (!"true".equals(authAllowInsecure) && !authUrl.startsWith("https://")) { throw new Exception("Only https links are allowed: " + authUrl); } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet request = new HttpGet(authUrl); request.setHeader(HttpHeaders.AUTHORIZATION, token); InputStream response = httpclient.execute(request).getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jsonMap = mapper.readValue(response, Map.class); Object expire = jsonMap.getOrDefault("expires", null); //Calculate ms till expiration if (expire == null) throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString()); long ms = ( (long)expire - Instant.now().toEpochMilli()); //Time of token expiration - N time String time_before_expiration = config.get(NarrativeJobServiceServer.CFG_PROP_TIME_BEFORE_EXPIRATION); //10 Minute Default if (time_before_expiration == null) return ms - (10 * 60 * 1000); //Number of minutes / 60 * 1000 return ms - (Long.parseLong(time_before_expiration) / 60) * 1000; } public static void canceljob(NarrativeJobServiceClient jobSrvClient, String jobId) throws Exception { jobSrvClient.cancelJob(new CancelJobParams().withJobId(jobId)); } public static void main(String[] args) throws Exception { System.out.println("Starting docker runner EDIT EDIT EDIT with args " + StringUtils.join(args, ", ")); if (args.length != 2) { System.err.println("Usage: <program> <job_id> <job_service_url>"); for (int i = 0; i < args.length; i++) System.err.println("\tArgument[" + i + "]: " + args[i]); System.exit(1); } Thread shutdownHook = new Thread() { @Override public void run() { try { DockerRunner.killSubJobs(); } catch (Exception e) { e.printStackTrace(); } } }; Runtime.getRuntime().addShutdownHook(shutdownHook); String[] hostnameAndIP = getHostnameAndIP(); final String jobId = args[0]; String jobSrvUrl = args[1]; String tokenStr = System.getenv("KB_AUTH_TOKEN"); if (tokenStr == null || tokenStr.isEmpty()) tokenStr = System.getProperty("KB_AUTH_TOKEN"); // For tests if (tokenStr == null || tokenStr.isEmpty()) throw new IllegalStateException("Token is not defined"); // We should skip token validation now because we don't have auth service URL yet. final AuthToken tempToken = new AuthToken(tokenStr, "<unknown>"); final NarrativeJobServiceClient jobSrvClient = getJobClient( jobSrvUrl, tempToken); Thread logFlusher = null; final List<LogLine> logLines = new ArrayList<LogLine>(); final LineLogger log = new LineLogger() { @Override public void logNextLine(String line, boolean isError) { addLogLine(jobSrvClient, jobId, logLines, new LogLine().withLine(line) .withIsError(isError ? 1L : 0L)); } }; Server callbackServer = null; try { JobState jobState = jobSrvClient.checkJob(jobId); if (jobState.getFinished() != null && jobState.getFinished() == 1L) { if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) { log.logNextLine("Job was canceled", false); } else { log.logNextLine("Job was already done before", true); } flushLog(jobSrvClient, jobId, logLines); return; } Tuple2<RunJobParams, Map<String, String>> jobInput = jobSrvClient.getJobParams(jobId); Map<String, String> config = jobInput.getE2(); if (System.getenv("CALLBACK_INTERFACE") != null) config.put(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS, System.getenv("CALLBACK_INTERFACE")); if (System.getenv("REFDATA_DIR") != null) config.put(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE, System.getenv("REFDATA_DIR")); ConfigurableAuthService auth = getAuth(config); // We couldn't validate token earlier because we didn't have auth service URL. AuthToken token = auth.validateToken(tokenStr); final URL catalogURL = getURL(config, NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL); final URI dockerURI = getURI(config, NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_DOCKER_URI, true); RunJobParams job = jobInput.getE1(); for (String msg : jobSrvClient.updateJob(new UpdateJobParams().withJobId(jobId) .withIsStarted(1L)).getMessages()) { log.logNextLine(msg, false); } File jobDir = getJobDir(jobInput.getE2(), jobId); if (!mountExists()) { log.logNextLine("Cannot find mount point as defined in condor-submit-workdir", true); throw new IOException("Cannot find mount point condor-submit-workdir"); } final ModuleMethod modMeth = new ModuleMethod(job.getMethod()); RpcContext context = job.getRpcContext(); if (context == null) context = new RpcContext().withRunId(""); if (context.getCallStack() == null) context.setCallStack(new ArrayList<MethodCall>()); context.getCallStack().add(new MethodCall().withJobId(jobId).withMethod(job.getMethod()) .withTime(DATE_FORMATTER.print(new DateTime()))); Map<String, Object> rpc = new LinkedHashMap<String, Object>(); rpc.put("version", "1.1"); rpc.put("method", job.getMethod()); rpc.put("params", job.getParams()); rpc.put("context", context); File workDir = new File(jobDir, "workdir"); if (!workDir.exists()) workDir.mkdir(); File scratchDir = new File(workDir, "tmp"); if (!scratchDir.exists()) scratchDir.mkdir(); File inputFile = new File(workDir, "input.json"); UObject.getMapper().writeValue(inputFile, rpc); File outputFile = new File(workDir, "output.json"); File configFile = new File(workDir, JOB_CONFIG_FILE); String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT); String clientDetails = hostnameAndIP[1]; String clientName = System.getenv("AWE_CLIENTNAME"); if (clientName != null && !clientName.isEmpty()) { clientDetails += ", client-name=" + clientName; } log.logNextLine("Running on " + hostnameAndIP[0] + " (" + clientDetails + "), in " + new File(".").getCanonicalPath(), false); String clientGroup = System.getenv("AWE_CLIENTGROUP"); if (clientGroup == null) clientGroup = "<unknown>"; log.logNextLine("Client group: " + clientGroup, false); String codeEeVer = NarrativeJobServiceServer.VERSION; String runtimeEeVersion = config.get(CFG_PROP_EE_SERVER_VERSION); if (runtimeEeVersion == null) runtimeEeVersion = "<unknown>"; if (codeEeVer.equals(runtimeEeVersion)) { log.logNextLine("Server version of Execution Engine: " + runtimeEeVersion + " (matches to version of runner script)", false); } else { log.logNextLine("WARNING: Server version of Execution Engine (" + runtimeEeVersion + ") doesn't match to version of runner script " + "(" + codeEeVer + ")", true); } CatalogClient catClient = new CatalogClient(catalogURL, token); catClient.setIsInsecureHttpConnectionAllowed(true); catClient.setAllSSLCertificatesTrusted(true); // the NJSW always passes the githash in service ver final String imageVersion = job.getServiceVer(); final String requestedRelease = (String) job .getAdditionalProperties().get(SDKMethodRunner.REQ_REL); final ModuleVersion mv; try { mv = catClient.getModuleVersion(new SelectModuleVersion() .withModuleName(modMeth.getModule()) .withVersion(imageVersion)); } catch (ServerException se) { throw new IllegalArgumentException(String.format( "Error looking up module %s with version %s: %s", modMeth.getModule(), imageVersion, se.getLocalizedMessage())); } String imageName = mv.getDockerImgName(); File refDataDir = null; String refDataBase = config.get(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE); if (mv.getDataFolder() != null && mv.getDataVersion() != null) { if (refDataBase == null) throw new IllegalStateException("Reference data parameters are defined for image but " + NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE + " property isn't set in configuration"); refDataDir = new File(new File(refDataBase, mv.getDataFolder()), mv.getDataVersion()); if (!refDataDir.exists()) throw new IllegalStateException("Reference data directory doesn't exist: " + refDataDir); } if (imageName == null) { throw new IllegalStateException("Image is not stored in catalog"); } else { log.logNextLine("Image name received from catalog: " + imageName, false); } logFlusher = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } flushLog(jobSrvClient, jobId, logLines); if (Thread.currentThread().isInterrupted()) break; } } }); logFlusher.setDaemon(true); logFlusher.start(); // Let's check if there are some volume mount rules or secure configuration parameters // set up for this module List<Bind> additionalBinds = null; Map<String, String> envVars = null; List<SecureConfigParameter> secureCfgParams = null; String adminTokenStr = System.getenv("KB_ADMIN_AUTH_TOKEN"); if (adminTokenStr == null || adminTokenStr.isEmpty()) adminTokenStr = System.getProperty("KB_ADMIN_AUTH_TOKEN"); // For tests String miniKB = System.getenv("MINI_KB"); boolean useVolumeMounts = true; if (miniKB != null && !miniKB.isEmpty() && miniKB.equals("true")) { useVolumeMounts = false; } if (adminTokenStr != null && !adminTokenStr.isEmpty() && useVolumeMounts) { final AuthToken adminToken = auth.validateToken(adminTokenStr); final CatalogClient adminCatClient = new CatalogClient(catalogURL, adminToken); adminCatClient.setIsInsecureHttpConnectionAllowed(true); adminCatClient.setAllSSLCertificatesTrusted(true); List<VolumeMountConfig> vmc = null; try { vmc = adminCatClient.listVolumeMounts(new VolumeMountFilter().withModuleName( modMeth.getModule()).withClientGroup(clientGroup) .withFunctionName(modMeth.getMethod())); } catch (Exception ex) { log.logNextLine("Error requesing volume mounts from Catalog: " + ex.getMessage(), true); } if (vmc != null && vmc.size() > 0) { if (vmc.size() > 1) throw new IllegalStateException("More than one rule for Docker volume mounts was found"); additionalBinds = new ArrayList<Bind>(); for (VolumeMount vm : vmc.get(0).getVolumeMounts()) { boolean isReadOnly = vm.getReadOnly() != null && vm.getReadOnly() != 0L; File hostDir = new File(processHostPathForVolumeMount(vm.getHostDir(), token.getUserName())); if (!hostDir.exists()) { if (isReadOnly) { throw new IllegalStateException("Volume mount directory doesn't exist: " + hostDir); } else { hostDir.mkdirs(); } } String contDir = vm.getContainerDir(); AccessMode am = isReadOnly ? AccessMode.ro : AccessMode.rw; additionalBinds.add(new Bind(hostDir.getCanonicalPath(), new Volume(contDir), am)); } } secureCfgParams = adminCatClient.getSecureConfigParams( new GetSecureConfigParamsInput().withModuleName(modMeth.getModule()) .withVersion(mv.getGitCommitHash()).withLoadAllVersions(0L)); envVars = new TreeMap<String, String>(); for (SecureConfigParameter param : secureCfgParams) { envVars.put("KBASE_SECURE_CONFIG_PARAM_" + param.getParamName(), param.getParamValue()); } } PrintWriter pw = new PrintWriter(configFile); pw.println("[global]"); if (kbaseEndpoint != null) pw.println("kbase_endpoint = " + kbaseEndpoint); pw.println("job_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL)); pw.println("workspace_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL)); pw.println("shock_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SHOCK_URL)); pw.println("handle_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_HANDLE_SRV_URL)); pw.println("srv_wiz_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SRV_WIZ_URL)); pw.println("njsw_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL)); pw.println("auth_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL)); pw.println("auth_service_url_allow_insecure = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM)); if (secureCfgParams != null) { for (SecureConfigParameter param : secureCfgParams) { pw.println(param.getParamName() + " = " + param.getParamValue()); } } pw.close(); // Cancellation checker CancellationChecker cancellationChecker = new CancellationChecker() { Boolean canceled = null; @Override public boolean isJobCanceled() { if (canceled != null) return canceled; try { final CheckJobCanceledResult jobState = jobSrvClient.checkJobCanceled( new CancelJobParams().withJobId(jobId)); if (jobState.getFinished() != null && jobState.getFinished() == 1L) { canceled = true; if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) { // Print cancellation message after DockerRunner is done } else { log.logNextLine("Job was registered as finished by another worker", true); } flushLog(jobSrvClient, jobId, logLines); return true; } } catch (Exception ex) { log.logNextLine("Non-critical error checking for job cancelation - " + String.format("Will check again in %s seconds. ", DockerRunner.CANCELLATION_CHECK_PERIOD_SEC) + "Error reported by execution engine was: " + HtmlEscapers.htmlEscaper().escape(ex.getMessage()), true); } return false; } }; // Starting up callback server String[] callbackNetworks = null; String callbackNetworksText = config.get(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS); if (callbackNetworksText != null) { callbackNetworks = callbackNetworksText.trim().split("\\s*,\\s*"); } final int callbackPort = NetUtils.findFreePort(); final URL callbackUrl = CallbackServer. getCallbackUrl(callbackPort, callbackNetworks); if (callbackUrl != null) { log.logNextLine("Job runner recieved callback URL: " + callbackUrl, false); final ModuleRunVersion runver = new ModuleRunVersion( new URL(mv.getGitUrl()), modMeth, mv.getGitCommitHash(), mv.getVersion(), requestedRelease); final CallbackServerConfig cbcfg = new CallbackServerConfigBuilder(config, callbackUrl, jobDir.toPath(), Paths.get(refDataBase), log).build(); final JsonServerServlet callback = new NJSCallbackServer( token, cbcfg, runver, job.getParams(), job.getSourceWsObjects(), additionalBinds, cancellationChecker); callbackServer = new Server(callbackPort); final ServletContextHandler srvContext = new ServletContextHandler( ServletContextHandler.SESSIONS); srvContext.setContextPath("/"); callbackServer.setHandler(srvContext); srvContext.addServlet(new ServletHolder(callback), "/*"); callbackServer.start(); } else { if (callbackNetworks != null && callbackNetworks.length > 0) { throw new IllegalStateException("No proper callback IP was found, " + "please check 'awe.client.callback.networks' parameter in " + "execution engine configuration"); } log.logNextLine("WARNING: No callback URL was recieved " + "by the job runner. Local callbacks are disabled.", true); } Map<String, String> labels = new HashMap<>(); labels.put("job_id", "" + jobId); labels.put("image_name", imageName); String method = job.getMethod(); String[] appNameMethodName = method.split("\\."); if (appNameMethodName.length == 2) { labels.put("app_name", appNameMethodName[0]); labels.put("method_name", appNameMethodName[1]); } else { labels.put("app_name", method); labels.put("method_name", method); } labels.put("parent_job_id", job.getParentJobId()); labels.put("image_version", imageVersion); labels.put("wsid", "" + job.getWsid()); labels.put("app_id", "" + job.getAppId()); labels.put("user_name", token.getUserName()); Map<String, String> resourceRequirements = new HashMap<String, String>(); String[] resourceStrings = {"request_cpus", "request_memory", "request_disk"}; for (String resourceKey : resourceStrings) { String resourceValue = System.getenv(resourceKey); if (resourceValue != null && !resourceKey.isEmpty()) { resourceRequirements.put(resourceKey, resourceValue); } } if (resourceRequirements.isEmpty()) { resourceRequirements = null; log.logNextLine("Resource Requirements are not specified.", false); } else { log.logNextLine("Resource Requirements are:", false); log.logNextLine(resourceRequirements.toString(), false); } //Get number of milliseconds to live for this token //Set a timer before job is cancelled for having an expired token to //the expiration time minus 10 minutes (default) or higher final long msToLive = milliSecondsToLive(tokenStr, config); Thread tokenExpirationHook = new Thread() { @Override public void run() { try { if (msToLive > 0) { Thread.sleep(msToLive); canceljob(jobSrvClient, jobId); log.logNextLine("Job was canceled due to token expiration", false); } else { canceljob(jobSrvClient, jobId); log.logNextLine("Job was canceled due to invalid token expiration state:" + msToLive, false); } } catch (Exception e) { e.printStackTrace(); } } }; tokenExpirationHook.start(); // Calling Runner if (System.getenv("USE_SHIFTER") != null) { new ShifterRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log, outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds, cancellationChecker, envVars, labels); } else { new DockerRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log, outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds, cancellationChecker, envVars, labels, resourceRequirements); } if (cancellationChecker.isJobCanceled()) { log.logNextLine("Job was canceled", false); flushLog(jobSrvClient, jobId, logLines); logFlusher.interrupt(); return; } if (outputFile.length() > MAX_OUTPUT_SIZE) { Reader r = new FileReader(outputFile); char[] chars = new char[1000]; r.read(chars); r.close(); String error = "Method " + job.getMethod() + " returned value longer than " + MAX_OUTPUT_SIZE + " bytes. This may happen as a result of returning actual data instead of saving it to " + "kbase data stores (Workspace, Shock, ...) and returning reference to it. Returned " + "value starts with \"" + new String(chars) + "...\""; throw new IllegalStateException(error); } FinishJobParams result = UObject.getMapper().readValue(outputFile, FinishJobParams.class); // flush logs to execution engine if (result.getError() != null) { String err = ""; if (notNullOrEmpty(result.getError().getName())) { err = result.getError().getName(); } if (notNullOrEmpty(result.getError().getMessage())) { if (!err.isEmpty()) { err += ": "; } err += result.getError().getMessage(); } if (notNullOrEmpty(result.getError().getError())) { if (!err.isEmpty()) { err += "\n"; } err += result.getError().getError(); } if (err == "") err = "Unknown error (please ask administrator for details providing full output log)"; log.logNextLine("Error: " + err, true); } else { log.logNextLine("Job is done", false); } flushLog(jobSrvClient, jobId, logLines); // push results to execution engine jobSrvClient.finishJob(jobId, result); logFlusher.interrupt(); //Turn off cancellation hook tokenExpirationHook.interrupt(); } catch (Exception ex) { ex.printStackTrace(); try { flushLog(jobSrvClient, jobId, logLines); } catch (Exception ignore) { } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.close(); String err = "Fatal error: " + sw.toString(); if (ex instanceof ServerException) { err += "\nServer exception:\n" + ((ServerException) ex).getData(); } try { log.logNextLine(err, true); flushLog(jobSrvClient, jobId, logLines); logFlusher.interrupt(); } catch (Exception ignore) { } try { FinishJobParams result = new FinishJobParams().withError( new JsonRpcError().withCode(-1L).withName("JSONRPCError") .withMessage("Job service side error: " + ex.getMessage()) .withError(err)); jobSrvClient.finishJob(jobId, result); } catch (Exception ex2) { ex2.printStackTrace(); } } finally { if (callbackServer != null) try { callbackServer.stop(); System.out.println("Callback server was shutdown"); } catch (Exception ignore) { System.err.println("Error shutting down callback server: " + ignore.getMessage()); } } Runtime.getRuntime().removeShutdownHook(shutdownHook); } public static String processHostPathForVolumeMount(String path, String username) { return path.replace("${username}", username); } private static boolean notNullOrEmpty(final String s) { return s != null && !s.isEmpty(); } private static synchronized void addLogLine(NarrativeJobServiceClient jobSrvClient, String jobId, List<LogLine> logLines, LogLine line) { logLines.add(line); if (line.getIsError() != null && line.getIsError() == 1L) { System.err.println(line.getLine()); } else { System.out.println(line.getLine()); } } private static synchronized void flushLog(NarrativeJobServiceClient jobSrvClient, String jobId, List<LogLine> logLines) { if (logLines.isEmpty()) return; try { jobSrvClient.addJobLogs(jobId, logLines); logLines.clear(); } catch (Exception ex) { ex.printStackTrace(); } } public static String decamelize(final String s) { final Matcher m = Pattern.compile("([A-Z])").matcher(s.substring(1)); return (s.substring(0, 1) + m.replaceAll("_$1")).toLowerCase(); } private static File getJobDir(Map<String, String> config, String jobId) { String rootDirPath = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_SCRATCH); File rootDir = new File(rootDirPath == null ? "." : rootDirPath); if (!rootDir.exists()) rootDir.mkdirs(); File ret = new File(rootDir, "job_" + jobId); if (!ret.exists()) ret.mkdir(); return ret; } /** * Check to see if the basedir exists, which is in * a format similar to /mnt/condor/<username> * * @return */ private static boolean mountExists() { File mountPath = new File(System.getenv("BASE_DIR")); return mountPath.exists() && mountPath.canWrite(); } public static NarrativeJobServiceClient getJobClient(String jobSrvUrl, AuthToken token) throws UnauthorizedException, IOException, MalformedURLException { final NarrativeJobServiceClient jobSrvClient = new NarrativeJobServiceClient(new URL(jobSrvUrl), token); jobSrvClient.setIsInsecureHttpConnectionAllowed(true); return jobSrvClient; } private static ConfigurableAuthService getAuth(final Map<String, String> config) throws Exception { String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL); } String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM); final AuthConfig c = new AuthConfig().withKBaseAuthServerURL(new URL(authUrl)); if ("true".equals(authAllowInsecure)) { c.withAllowInsecureURLs(true); } return new ConfigurableAuthService(c); } private static URL getURL(final Map<String, String> config, final String param) { final String urlStr = config.get(param); if (urlStr == null || urlStr.isEmpty()) { throw new IllegalStateException("Parameter '" + param + "' is not defined in configuration"); } try { return new URL(urlStr); } catch (MalformedURLException mal) { throw new IllegalStateException("The configuration parameter '" + param + " = " + urlStr + "' is not a valid URL"); } } private static URI getURI(final Map<String, String> config, final String param, boolean allowAbsent) { final String urlStr = config.get(param); if (urlStr == null || urlStr.isEmpty()) { if (allowAbsent) { return null; } throw new IllegalStateException("Parameter '" + param + "' is not defined in configuration"); } try { return new URI(urlStr); } catch (URISyntaxException use) { throw new IllegalStateException("The configuration parameter '" + param + " = " + urlStr + "' is not a valid URI"); } } public static String[] getHostnameAndIP() { String hostname = null; String ip = null; try { InetAddress ia = InetAddress.getLocalHost(); ip = ia.getHostAddress(); hostname = ia.getHostName(); } catch (Throwable ignore) { } if (hostname == null) { try { hostname = System.getenv("HOSTNAME"); if (hostname != null && hostname.isEmpty()) hostname = null; } catch (Throwable ignore) { } } if (ip == null && hostname != null) { try { ip = InetAddress.getByName(hostname).getHostAddress(); } catch (Throwable ignore) { } } return new String[]{hostname == null ? "unknown" : hostname, ip == null ? "unknown" : ip}; } }
Formatting
src/us/kbase/narrativejobservice/sdkjobs/SDKLocalMethodRunner.java
Formatting
<ide><path>rc/us/kbase/narrativejobservice/sdkjobs/SDKLocalMethodRunner.java <ide> if (expire == null) <ide> throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString()); <ide> <del> long ms = ( (long)expire - Instant.now().toEpochMilli()); <add> long ms = ((long) expire - Instant.now().toEpochMilli()); <ide> <ide> //Time of token expiration - N time <ide> String time_before_expiration = config.get(NarrativeJobServiceServer.CFG_PROP_TIME_BEFORE_EXPIRATION);
Java
lgpl-2.1
ff06043ee7e8924547b10c32898910619aff706a
0
ervandew/formic,ervandew/formic
/** * Formic installer framework. * Copyright (C) 2005 - 2006 Eric Van Dewoestine * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.formic.wizard.impl.models; import java.util.Stack; import org.pietschy.wizard.PanelWizardStep; import org.pietschy.wizard.WizardStep; import org.pietschy.wizard.models.Path; import org.pietschy.wizard.models.SimplePath; /** * Extension to original MultiPathModel that supports paths containing no steps. * * @author Eric Van Dewoestine ([email protected]) * @version $Revision$ */ public class MultiPathModel extends org.pietschy.wizard.models.MultiPathModel { private Stack history = new Stack(); private Path firstPath = null; public MultiPathModel(Path firstPath) { super(firstPath); this.firstPath = firstPath; } /** * {@inheritDoc} */ public void nextStep() { WizardStep currentStep = getActiveStep(); Path currentPath = getPathForStep(currentStep); // CHANGE // NEW CODE if (currentPath.getSteps().size() == 0 || currentPath.isLastStep(currentStep)) { Path nextPath = getNextPath(currentPath); while(nextPath.getSteps().size() == 0){ nextPath = getNextPath(nextPath); } setActiveStep(nextPath.firstStep()); } // OLD CODE /*if (currentPath.isLastStep(currentStep)) { Path nextPath = currentPath.getNextPath(this); setActiveStep(nextPath.firstStep()); }*/ // END CHANGE else { setActiveStep(currentPath.nextStep(currentStep)); } history.push(currentStep); } /** * Gets the next path. */ private Path getNextPath (Path path) { if(path instanceof SimplePath){ return ((SimplePath)path).getNextPath(); } return ((BranchingPath)path).getNextPath(this); } /** * {@inheritDoc} */ public void previousStep() { WizardStep step = (WizardStep) history.pop(); setActiveStep(step); } /** * {@inheritDoc} */ public void lastStep() { history.push(getActiveStep()); WizardStep lastStep = getLastPath().lastStep(); setActiveStep(lastStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.WizardModel#isLastVisible() */ public boolean isLastVisible () { return false; } /** * Determines if the supplied step is the first step. * * @param step The step. * @return true if the first step, false otherwise. */ public boolean isFirstStep (WizardStep step) { Path path = getPathForStep(step); return path.equals(getFirstPath()) && path.isFirstStep(step); } /** * {@inheritDoc} */ public void reset() { history.clear(); WizardStep firstStep = firstPath.firstStep(); setActiveStep(firstStep); history.push(firstStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setNextAvailable(boolean) */ public void setNextAvailable (boolean available) { super.setNextAvailable(available); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setPreviousAvailable(boolean) */ public void setPreviousAvailable (boolean available) { super.setPreviousAvailable(available); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setCancelAvailable(boolean) */ public void setCancelAvailable (boolean available) { super.setCancelAvailable(available); } /** * {@inheritDoc} * @see org.pietschy.wizard.models.MultiPathModel#refreshModelState() */ public void refreshModelState () { // do nothing. } }
src/java/org/formic/wizard/impl/models/MultiPathModel.java
/** * Formic installer framework. * Copyright (C) 2005 - 2006 Eric Van Dewoestine * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.formic.wizard.impl.models; import java.util.Stack; import org.pietschy.wizard.PanelWizardStep; import org.pietschy.wizard.WizardStep; import org.pietschy.wizard.models.Path; import org.pietschy.wizard.models.SimplePath; /** * Extension to original MultiPathModel that supports paths containing no steps. * * @author Eric Van Dewoestine ([email protected]) * @version $Revision$ */ public class MultiPathModel extends org.pietschy.wizard.models.MultiPathModel { private Stack history = new Stack(); private Path firstPath = null; public MultiPathModel(Path firstPath) { super(firstPath); this.firstPath = firstPath; } /** * {@inheritDoc} */ public void nextStep() { WizardStep currentStep = getActiveStep(); Path currentPath = getPathForStep(currentStep); // CHANGE // NEW CODE if (currentPath.getSteps().size() == 0 || currentPath.isLastStep(currentStep)) { Path nextPath = getNextPath(currentPath); while(nextPath.getSteps().size() == 0){ nextPath = getNextPath(nextPath); } setActiveStep(nextPath.firstStep()); } // OLD CODE /*if (currentPath.isLastStep(currentStep)) { Path nextPath = currentPath.getNextPath(this); setActiveStep(nextPath.firstStep()); }*/ // END CHANGE else { setActiveStep(currentPath.nextStep(currentStep)); } history.push(currentStep); } /** * Gets the next path. */ private Path getNextPath (Path path) { if(path instanceof SimplePath){ return ((SimplePath)path).getNextPath(); } return ((BranchingPath)path).getNextPath(this); } /** * {@inheritDoc} */ public void previousStep() { WizardStep step = (WizardStep) history.pop(); setActiveStep(step); } /** * {@inheritDoc} */ public void lastStep() { history.push(getActiveStep()); WizardStep lastStep = getLastPath().lastStep(); setActiveStep(lastStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.WizardModel#isLastVisible() */ public boolean isLastVisible () { return false; } /** * Determines if the supplied step is the first step. * * @param step The step. * @return true if the first step, false otherwise. */ public boolean isFirstStep (WizardStep step) { Path path = getPathForStep(step); return path.equals(getFirstPath()) && path.isFirstStep(step); } /** * {@inheritDoc} */ public void reset() { history.clear(); WizardStep firstStep = firstPath.firstStep(); setActiveStep(firstStep); history.push(firstStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setPreviousAvailable(boolean) */ public void setPreviousAvailable (boolean available) { super.setPreviousAvailable(available); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setCancelAvailable(boolean) */ public void setCancelAvailable (boolean available) { super.setCancelAvailable(available); } }
override refreshModelState to do nothing and added public setNextAvailable git-svn-id: 64dca1223d331db67f04737d5e1336182ee12169@261 1a7380c6-1923-0410-bcea-c2eae4ba7d6c
src/java/org/formic/wizard/impl/models/MultiPathModel.java
override refreshModelState to do nothing and added public setNextAvailable
<ide><path>rc/java/org/formic/wizard/impl/models/MultiPathModel.java <ide> <ide> /** <ide> * {@inheritDoc} <add> * @see org.pietschy.wizard.AbstractWizardModel#setNextAvailable(boolean) <add> */ <add> public void setNextAvailable (boolean available) <add> { <add> super.setNextAvailable(available); <add> } <add> <add> /** <add> * {@inheritDoc} <ide> * @see org.pietschy.wizard.AbstractWizardModel#setPreviousAvailable(boolean) <ide> */ <ide> public void setPreviousAvailable (boolean available) <ide> { <ide> super.setCancelAvailable(available); <ide> } <add> <add> /** <add> * {@inheritDoc} <add> * @see org.pietschy.wizard.models.MultiPathModel#refreshModelState() <add> */ <add> public void refreshModelState () <add> { <add> // do nothing. <add> } <ide> }
Java
lgpl-2.1
00628d846d8126d4f6bbf37715e8bc3d4dbbb323
0
sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,spotbugs/spotbugs
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2007 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.internalAnnotations; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.regex.Pattern; import javax.annotation.Nonnull; import javax.annotation.meta.TypeQualifier; import javax.annotation.meta.TypeQualifierValidator; import javax.annotation.meta.When; /** * * Denotes a class name or package name where the / character is used to * separate package/class name components. * * @author pugh */ @Documented @TypeQualifier(applicableTo = CharSequence.class) @Retention(RetentionPolicy.RUNTIME) public @interface SlashedClassName { public static final String NOT_AVAILABLE = "./."; When when() default When.ALWAYS; static class Checker implements TypeQualifierValidator<SlashedClassName> { final static String simpleName = "(\\p{javaJavaIdentifierStart}(\\p{javaJavaIdentifierPart}|\\$)*)"; final static String slashedClassName = simpleName + "(/" + simpleName + ")*"; final static Pattern simplePattern = Pattern.compile(simpleName); final static Pattern pattern = Pattern.compile(slashedClassName); @Nonnull public When forConstantValue(@Nonnull SlashedClassName annotation, Object value) { if (value == null) return When.MAYBE; if (!(value instanceof String)) return When.NEVER; if (pattern.matcher((String) value).matches()) return When.ALWAYS; if (value.equals(NOT_AVAILABLE)) return When.MAYBE; return When.NEVER; } } }
findbugs/src/java/edu/umd/cs/findbugs/internalAnnotations/SlashedClassName.java
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2007 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.internalAnnotations; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.regex.Pattern; import javax.annotation.Nonnull; import javax.annotation.meta.TypeQualifier; import javax.annotation.meta.TypeQualifierValidator; import javax.annotation.meta.When; /** * * Denotes a class name or package name where the / character is used to * separate package/class name components. * * @author pugh */ @Documented @TypeQualifier(applicableTo = CharSequence.class) @Retention(RetentionPolicy.RUNTIME) public @interface SlashedClassName { public static final String NOT_AVAILABLE = "./."; When when() default When.ALWAYS; static class Checker implements TypeQualifierValidator<SlashedClassName> { final static String simpleName = "(\\p{javaJavaIdentifierStart}(\\p{javaJavaIdentifierPart}|\\$)*)"; final static String slashedClassName = simpleName + "(/" + simpleName + ")*"; final static Pattern simplePattern = Pattern.compile(simpleName); final static Pattern pattern = Pattern.compile(slashedClassName); @Nonnull public When forConstantValue(@Nonnull SlashedClassName annotation, Object value) { if (!(value instanceof String)) return When.NEVER; if (pattern.matcher((String) value).matches()) return When.ALWAYS; if (value.equals(NOT_AVAILABLE)) return When.MAYBE; return When.NEVER; } } }
fix type qualifier for slashed class names; null can be either slashed or dotted git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14549 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/internalAnnotations/SlashedClassName.java
fix type qualifier for slashed class names; null can be either slashed or dotted
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/internalAnnotations/SlashedClassName.java <ide> /** <ide> * * Denotes a class name or package name where the / character is used to <ide> * separate package/class name components. <del> * <add> * <ide> * @author pugh <ide> */ <ide> @Documented <ide> @TypeQualifier(applicableTo = CharSequence.class) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> public @interface SlashedClassName { <del> <add> <ide> public static final String NOT_AVAILABLE = "./."; <ide> <ide> When when() default When.ALWAYS; <ide> <ide> @Nonnull <ide> public When forConstantValue(@Nonnull SlashedClassName annotation, Object value) { <add> if (value == null) <add> return When.MAYBE; <ide> if (!(value instanceof String)) <ide> return When.NEVER; <ide> <ide> if (pattern.matcher((String) value).matches()) <ide> return When.ALWAYS; <del> <add> <ide> if (value.equals(NOT_AVAILABLE)) <ide> return When.MAYBE; <ide>
Java
bsd-3-clause
b1519ca2552c91f4b2e9d9cb275d93b933163c4a
0
geneontology/minerva,geneontology/minerva,geneontology/minerva
package org.geneontology.minerva.cli; import com.bigdata.journal.Options; import com.bigdata.rdf.sail.BigdataSail; import com.bigdata.rdf.sail.BigdataSailRepository; import com.bigdata.rdf.sail.BigdataSailRepositoryConnection; import com.google.common.base.Optional; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.geneontology.minerva.BlazegraphMolecularModelManager; import org.geneontology.minerva.GafToLegoIndividualTranslator; import org.geneontology.minerva.curie.CurieHandler; import org.geneontology.minerva.curie.CurieMappings; import org.geneontology.minerva.curie.DefaultCurieHandler; import org.geneontology.minerva.curie.MappedCurieHandler; import org.geneontology.minerva.json.InferenceProvider; import org.geneontology.minerva.json.JsonModel; import org.geneontology.minerva.json.MolecularModelJsonRenderer; import org.geneontology.minerva.legacy.GroupingTranslator; import org.geneontology.minerva.legacy.LegoToGeneAnnotationTranslator; import org.geneontology.minerva.legacy.sparql.GPADSPARQLExport; import org.geneontology.minerva.lookup.ExternalLookupService; import org.geneontology.minerva.util.BlazegraphMutationCounter; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.UpdateExecutionException; import org.openrdf.repository.RepositoryException; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.formats.FunctionalSyntaxDocumentFormat; import org.semanticweb.owlapi.formats.ManchesterSyntaxDocumentFormat; import org.semanticweb.owlapi.formats.RDFXMLDocumentFormat; import org.semanticweb.owlapi.formats.TurtleDocumentFormat; import org.semanticweb.owlapi.model.*; import org.semanticweb.owlapi.reasoner.InconsistentOntologyException; import owltools.cli.JsCommandRunner; import owltools.cli.Opts; import owltools.cli.tools.CLIMethod; import owltools.gaf.GafDocument; import owltools.gaf.GeneAnnotation; import owltools.gaf.eco.EcoMapperFactory; import owltools.gaf.eco.SimpleEcoMapper; import owltools.gaf.io.GafWriter; import owltools.gaf.io.GpadWriter; import owltools.graph.OWLGraphWrapper; import uk.ac.manchester.cs.owlapi.modularity.ModuleType; import uk.ac.manchester.cs.owlapi.modularity.SyntacticLocalityModuleExtractor; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.*; public class MinervaCommandRunner extends JsCommandRunner { private static final Logger LOGGER = Logger.getLogger(MinervaCommandRunner.class); @CLIMethod("--dump-owl-models") public void modelsToOWL(Opts opts) throws Exception { opts.info("[-j|--journal JOURNALFILE] [-f|--folder OWLFILESFOLDER] [-p|--prefix MODELIDPREFIX]", "dumps all LEGO models to OWL Turtle files"); // parameters String journalFilePath = null; String outputFolder = null; String modelIdPrefix = "http://model.geneontology.org/"; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-j|--journal")) { opts.info("journal file", "Sets the Blazegraph journal file for the database"); journalFilePath = opts.nextOpt(); } else if (opts.nextEq("-f|--folder")) { opts.info("OWL folder", "Sets the output folder the LEGO model files"); outputFolder = opts.nextOpt(); } else if (opts.nextEq("-p|--prefix")) { opts.info("model ID prefix", "Sets the URI prefix for model IDs"); modelIdPrefix = opts.nextOpt(); } else { break; } } // minimal inputs if (journalFilePath == null) { System.err.println("No journal file was configured."); exit(-1); return; } if (outputFolder == null) { System.err.println("No output folder was configured."); exit(-1); return; } OWLOntology dummy = OWLManager.createOWLOntologyManager().createOntology(IRI.create("http://example.org/dummy")); CurieHandler curieHandler = new MappedCurieHandler(); BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(dummy, curieHandler, modelIdPrefix, journalFilePath, outputFolder); m3.dumpAllStoredModels(); m3.dispose(); } @CLIMethod("--import-owl-models") public void importOWLModels(Opts opts) throws Exception { opts.info("[-j|--journal JOURNALFILE] [-f|--folder OWLFILESFOLDER]", "import all files in folder to database"); // parameters String journalFilePath = null; String inputFolder = null; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-j|--journal")) { opts.info("journal file", "Sets the Blazegraph journal file for the database"); journalFilePath = opts.nextOpt(); } else if (opts.nextEq("-f|--folder")) { opts.info("OWL folder", "Sets the folder containing the LEGO model files"); inputFolder = opts.nextOpt(); } else { break; } } // minimal inputs if (journalFilePath == null) { System.err.println("No journal file was configured."); exit(-1); return; } if (inputFolder == null) { System.err.println("No input folder was configured."); exit(-1); return; } OWLOntology dummy = OWLManager.createOWLOntologyManager().createOntology(IRI.create("http://example.org/dummy")); String modelIdPrefix = "http://model.geneontology.org/"; // this will not be used for anything CurieHandler curieHandler = new MappedCurieHandler(); BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(dummy, curieHandler, modelIdPrefix, journalFilePath, null); for (File file : FileUtils.listFiles(new File(inputFolder), null, true)) { LOGGER.info("Loading " + file); m3.importModelToDatabase(file, true); } m3.dispose(); } @CLIMethod("--sparql-update") public void sparqlUpdate(Opts opts) throws OWLOntologyCreationException, IOException, RepositoryException, MalformedQueryException, UpdateExecutionException { opts.info("[-j|--journal JOURNALFILE] [-f|--file SPARQL UPDATE FILE]", "apply SPARQL update to database"); String journalFilePath = null; String updateFile = null; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-j|--journal")) { opts.info("journal file", "Sets the Blazegraph journal file for the database"); journalFilePath = opts.nextOpt(); } else if (opts.nextEq("-f|--file")) { opts.info("OWL folder", "Sets the file containing a SPARQL update"); updateFile = opts.nextOpt(); } else { break; } } // minimal inputs if (journalFilePath == null) { System.err.println("No journal file was configured."); exit(-1); return; } if (updateFile == null) { System.err.println("No update file was configured."); exit(-1); return; } String update = FileUtils.readFileToString(new File(updateFile), StandardCharsets.UTF_8); Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/org/geneontology/minerva/blazegraph.properties")); properties.setProperty(Options.FILE, journalFilePath); BigdataSail sail = new BigdataSail(properties); BigdataSailRepository repository = new BigdataSailRepository(sail); repository.initialize(); BigdataSailRepositoryConnection conn = repository.getUnisolatedConnection(); BlazegraphMutationCounter counter = new BlazegraphMutationCounter(); conn.addChangeLog(counter); conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); int changes = counter.mutationCount(); conn.removeChangeLog(counter); System.out.println("\nApplied " + changes + " changes"); conn.close(); } @CLIMethod("--owl-lego-to-json") public void owl2LegoJson(Opts opts) throws Exception { opts.info("[-o JSONFILE] [-i OWLFILE] [--pretty-json] [--compact-json]", "converts the LEGO subset of OWL to Minerva-JSON"); // parameters String input = null; String output = null; boolean usePretty = true; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-o|--output")) { opts.info("output", "Sets the output file for the json"); output = opts.nextOpt(); } else if (opts.nextEq("-i|--input")) { opts.info("input", "Sets the input file for the model"); input = opts.nextOpt(); } else if (opts.nextEq("--pretty-json")) { opts.info("", "pretty print the output json"); usePretty = true; } else if (opts.nextEq("--compact-json")) { opts.info("", "compact print the output json"); usePretty = false; } else { break; } } // minimal inputs if (input == null) { System.err.println("No input model was configured."); exit(-1); return; } if (output == null) { System.err.println("No output file was configured."); exit(-1); return; } // configuration CurieHandler curieHandler = DefaultCurieHandler.getDefaultHandler(); GsonBuilder gsonBuilder = new GsonBuilder(); if (usePretty) { gsonBuilder.setPrettyPrinting(); } Gson gson = gsonBuilder.create(); // process each model if (LOGGER.isInfoEnabled()) { LOGGER.info("Loading model from file: "+input); } OWLOntology model = null; final JsonModel jsonModel; try { // load model model = pw.parseOWL(IRI.create(new File(input).getCanonicalFile())); InferenceProvider inferenceProvider = null; // TODO decide if we need reasoning String modelId = null; Optional<IRI> ontologyIRI = model.getOntologyID().getOntologyIRI(); if (ontologyIRI.isPresent()) { modelId = curieHandler.getCuri(ontologyIRI.get()); } // render json final MolecularModelJsonRenderer renderer = new MolecularModelJsonRenderer(modelId, model, inferenceProvider, curieHandler); jsonModel = renderer.renderModel(); } finally { if (model != null) { pw.getManager().removeOntology(model); model = null; } } // save as json string final String json = gson.toJson(jsonModel); final File outputFile = new File(output).getCanonicalFile(); try (OutputStream outputStream = new FileOutputStream(outputFile)) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Saving json to file: "+outputFile); } IOUtils.write(json, outputStream); } } /** * Translate the GeneAnnotations into a lego all individual OWL representation. * * Will merge the source ontology into the graph by default * * @param opts * @throws Exception */ @CLIMethod("--gaf-lego-individuals") public void gaf2LegoIndivduals(Opts opts) throws Exception { boolean addLineNumber = false; boolean merge = true; boolean minimize = false; String output = null; CurieHandler curieHandler = DefaultCurieHandler.getDefaultHandler(); OWLDocumentFormat format = new RDFXMLDocumentFormat(); while (opts.hasOpts()) { if (opts.nextEq("-o|--output")) { output = opts.nextOpt(); } else if (opts.nextEq("--format")) { String formatString = opts.nextOpt(); if ("manchester".equalsIgnoreCase(formatString)) { format = new ManchesterSyntaxDocumentFormat(); } else if ("turtle".equalsIgnoreCase(formatString)) { format = new TurtleDocumentFormat(); } else if ("functional".equalsIgnoreCase(formatString)) { format = new FunctionalSyntaxDocumentFormat(); } } else if (opts.nextEq("--add-line-number")) { addLineNumber = true; } else if (opts.nextEq("--skip-merge")) { merge = false; } else if (opts.nextEq("-m|--minimize")) { opts.info("", "use module extraction to include module of ontology"); minimize = true; } else { break; } } if (g != null && gafdoc != null && output != null) { GafToLegoIndividualTranslator tr = new GafToLegoIndividualTranslator(g, curieHandler, addLineNumber); OWLOntology lego = tr.translate(gafdoc); if (merge) { new OWLGraphWrapper(lego).mergeImportClosure(true); } if (minimize) { final OWLOntologyManager m = lego.getOWLOntologyManager(); SyntacticLocalityModuleExtractor sme = new SyntacticLocalityModuleExtractor(m, lego, ModuleType.BOT); Set<OWLEntity> sig = new HashSet<OWLEntity>(lego.getIndividualsInSignature()); Set<OWLAxiom> moduleAxioms = sme.extract(sig); OWLOntology module = m.createOntology(IRI.generateDocumentIRI()); m.addAxioms(module, moduleAxioms); lego = module; } OWLOntologyManager manager = lego.getOWLOntologyManager(); OutputStream outputStream = null; try { outputStream = new FileOutputStream(output); manager.saveOntology(lego, format, outputStream); } finally { IOUtils.closeQuietly(outputStream); } } else { if (output == null) { System.err.println("No output file was specified."); } if (g == null) { System.err.println("No graph available for gaf-run-check."); } if (gafdoc == null) { System.err.println("No loaded gaf available for gaf-run-check."); } exit(-1); return; } } /** * Output GPAD files via inference+SPARQL, for testing only * @param opts * @throws Exception */ @CLIMethod("--lego-to-gpad-sparql") public void legoToAnnotationsSPARQL(Opts opts) throws Exception { String modelIdPrefix = "http://model.geneontology.org/"; String modelIdcurie = "gomodel"; String inputDB = "blazegraph.jnl"; String gpadOutputFolder = null; String ontologyIRI = "http://purl.obolibrary.org/obo/go/extensions/go-lego.owl"; while (opts.hasOpts()) { if (opts.nextEq("-i|--input")) { inputDB = opts.nextOpt(); } else if (opts.nextEq("--gpad-output")) { gpadOutputFolder = opts.nextOpt(); } else if (opts.nextEq("--model-id-prefix")) { modelIdPrefix = opts.nextOpt(); } else if (opts.nextEq("--model-id-curie")) { modelIdcurie = opts.nextOpt(); } else if (opts.nextEq("--ontology")) { ontologyIRI = opts.nextOpt(); } else { break; } } OWLOntology ontology = OWLManager.createOWLOntologyManager().loadOntology(IRI.create(ontologyIRI)); CurieMappings localMappings = new CurieMappings.SimpleCurieMappings(Collections.singletonMap(modelIdcurie, modelIdPrefix)); CurieHandler curieHandler = new MappedCurieHandler(DefaultCurieHandler.loadDefaultMappings(), localMappings); BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(ontology, curieHandler, modelIdPrefix, inputDB, null); final String immutableModelIdPrefix = modelIdPrefix; final String immutableGpadOutputFolder = gpadOutputFolder; m3.getAvailableModelIds().stream().parallel().forEach(modelIRI -> { try { String gpad = new GPADSPARQLExport(curieHandler, m3.getLegacyRelationShorthandIndex(), m3.getTboxShorthandIndex(), m3.getDoNotAnnotateSubset()).exportGPAD(m3.createInferredModel(modelIRI)); String fileName = StringUtils.replaceOnce(modelIRI.toString(), immutableModelIdPrefix, "") + ".gpad"; Writer writer = new OutputStreamWriter(new FileOutputStream(Paths.get(immutableGpadOutputFolder, fileName).toFile()), StandardCharsets.UTF_8); writer.write(gpad); writer.close(); } catch (InconsistentOntologyException e) { LOGGER.error("Inconsistent ontology: " + modelIRI); } catch (IOException e) { LOGGER.error("Couldn't export GPAD for: " + modelIRI, e); } }); m3.dispose(); } @CLIMethod("--lego-to-gpad") public void legoToAnnotations(Opts opts) throws Exception { String modelIdPrefix = "http://model.geneontology.org/"; String modelIdcurie = "gomodel"; String inputFolder = null; String singleFile = null; String gpadOutputFolder = null; String gafOutputFolder = null; Map<String, String> taxonGroups = null; String defaultTaxonGroup = "other"; boolean addLegoModelId = true; String fileSuffix = "ttl"; while (opts.hasOpts()) { if (opts.nextEq("-i|--input")) { inputFolder = opts.nextOpt(); } else if (opts.nextEq("--input-single-file")) { singleFile = opts.nextOpt(); } else if (opts.nextEq("--gpad-output")) { gpadOutputFolder = opts.nextOpt(); } else if (opts.nextEq("--gaf-output")) { gafOutputFolder = opts.nextOpt(); } else if (opts.nextEq("--remove-lego-model-ids")) { addLegoModelId = false; } else if (opts.nextEq("--model-id-prefix")) { modelIdPrefix = opts.nextOpt(); } else if (opts.nextEq("-s|--input-file-suffix")) { opts.info("SUFFIX", "if a directory is specified, use only files with this suffix. Default is 'ttl'"); fileSuffix = opts.nextOpt(); } else if (opts.nextEq("--model-id-curie")) { modelIdcurie = opts.nextOpt(); } else if (opts.nextEq("--group-by-model-organisms")) { if (taxonGroups == null) { taxonGroups = new HashMap<>(); } // get the pre-defined groups from the model-organism-groups.tsv resource List<String> lines = IOUtils.readLines(MinervaCommandRunner.class.getResourceAsStream("/model-organism-groups.tsv")); for (String line : lines) { line = StringUtils.trimToEmpty(line); if (line.isEmpty() == false && line.charAt(0) != '#') { String[] split = StringUtils.splitByWholeSeparator(line, "\t"); if (split.length > 1) { String group = split[0]; Set<String> taxonIds = new HashSet<>(); for (int i = 1; i < split.length; i++) { taxonIds.add(split[i]); } for(String taxonId : taxonIds) { taxonGroups.put(taxonId, group); } } } } } else if (opts.nextEq("--add-model-organism-group")) { if (taxonGroups == null) { taxonGroups = new HashMap<>(); } String group = opts.nextOpt(); String taxon = opts.nextOpt(); taxonGroups.put(taxon, group); } else if (opts.nextEq("--set-default-model-group")) { defaultTaxonGroup = opts.nextOpt(); } else { break; } } // create curie handler CurieMappings localMappings = new CurieMappings.SimpleCurieMappings(Collections.singletonMap(modelIdcurie, modelIdPrefix)); CurieHandler curieHandler = new MappedCurieHandler(DefaultCurieHandler.loadDefaultMappings(), localMappings); ExternalLookupService lookup= null; SimpleEcoMapper mapper = EcoMapperFactory.createSimple(); LegoToGeneAnnotationTranslator translator = new LegoToGeneAnnotationTranslator(g.getSourceOntology(), curieHandler, mapper); GroupingTranslator groupingTranslator = new GroupingTranslator(translator, lookup, taxonGroups, defaultTaxonGroup, addLegoModelId); final OWLOntologyManager m = g.getManager(); if (singleFile != null) { File file = new File(singleFile).getCanonicalFile(); OWLOntology model = m.loadOntology(IRI.create(file)); groupingTranslator.translate(model); } else if (inputFolder != null) { final String fileSuffixFinal = fileSuffix; File inputFile = new File(inputFolder).getCanonicalFile(); if (inputFile.isDirectory()) { File[] files = inputFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (fileSuffixFinal != null && fileSuffixFinal.length() > 0) return name.endsWith("."+fileSuffixFinal); else return StringUtils.isAlphanumeric(name); } }); for (File file : files) { OWLOntology model = m.loadOntology(IRI.create(file)); groupingTranslator.translate(model); } } } // by state for(String modelState : groupingTranslator.getModelStates()) { GafDocument annotations = groupingTranslator.getAnnotationsByState(modelState); sortAnnotations(annotations); if (annotations != null) { if (gpadOutputFolder != null) { writeGpad(annotations, gpadOutputFolder, "all-"+modelState); } if (gafOutputFolder != null) { writeGaf(annotations, gafOutputFolder, "all-"+modelState); } } } // by organism if (taxonGroups != null) { for(String group : groupingTranslator.getTaxonGroups()) { GafDocument filtered = groupingTranslator.getAnnotationsByGroup(group); sortAnnotations(filtered); if (gpadOutputFolder != null) { writeGpad(filtered, gpadOutputFolder, group); } if (gafOutputFolder != null) { writeGaf(filtered, gafOutputFolder, group); } } } // production only by organism if (taxonGroups != null) { for(String group : groupingTranslator.getProductionTaxonGroups()) { GafDocument filtered = groupingTranslator.getProductionAnnotationsByGroup(group); sortAnnotations(filtered); if (gpadOutputFolder != null) { String productionFolder = new File(gpadOutputFolder, "production").getAbsolutePath(); writeGpad(filtered, productionFolder+"", group); } if (gafOutputFolder != null) { String productionFolder = new File(gafOutputFolder, "production").getAbsolutePath(); writeGaf(filtered, productionFolder, group); } } } } static void sortAnnotations(GafDocument annotations) { Collections.sort(annotations.getGeneAnnotations(), new Comparator<GeneAnnotation>() { @Override public int compare(GeneAnnotation a1, GeneAnnotation a2) { return a1.toString().compareTo(a2.toString()); } }); } private void writeGaf(GafDocument annotations, String outputFolder, String fileName) { File outputFile = new File(outputFolder, fileName+".gaf"); GafWriter writer = new GafWriter(); try { outputFile.getParentFile().mkdirs(); writer.setStream(outputFile); writer.write(annotations); } finally { IOUtils.closeQuietly(writer); } } private void writeGpad(GafDocument annotations, String outputFolder, String fileName) throws FileNotFoundException { PrintWriter fileWriter = null; File outputFile = new File(outputFolder, fileName+".gpad"); try { outputFile.getParentFile().mkdirs(); fileWriter = new PrintWriter(outputFile); GpadWriter writer = new GpadWriter(fileWriter, 1.2d); writer.write(annotations); } finally { IOUtils.closeQuietly(fileWriter); } } }
minerva-cli/src/main/java/org/geneontology/minerva/cli/MinervaCommandRunner.java
package org.geneontology.minerva.cli; import com.bigdata.journal.Options; import com.bigdata.rdf.sail.BigdataSail; import com.bigdata.rdf.sail.BigdataSailRepository; import com.bigdata.rdf.sail.BigdataSailRepositoryConnection; import com.google.common.base.Optional; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.geneontology.minerva.BlazegraphMolecularModelManager; import org.geneontology.minerva.GafToLegoIndividualTranslator; import org.geneontology.minerva.curie.CurieHandler; import org.geneontology.minerva.curie.CurieMappings; import org.geneontology.minerva.curie.DefaultCurieHandler; import org.geneontology.minerva.curie.MappedCurieHandler; import org.geneontology.minerva.json.InferenceProvider; import org.geneontology.minerva.json.JsonModel; import org.geneontology.minerva.json.MolecularModelJsonRenderer; import org.geneontology.minerva.legacy.GroupingTranslator; import org.geneontology.minerva.legacy.LegoToGeneAnnotationTranslator; import org.geneontology.minerva.legacy.sparql.GPADSPARQLExport; import org.geneontology.minerva.lookup.ExternalLookupService; import org.geneontology.minerva.util.BlazegraphMutationCounter; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.UpdateExecutionException; import org.openrdf.repository.RepositoryException; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.formats.FunctionalSyntaxDocumentFormat; import org.semanticweb.owlapi.formats.ManchesterSyntaxDocumentFormat; import org.semanticweb.owlapi.formats.RDFXMLDocumentFormat; import org.semanticweb.owlapi.formats.TurtleDocumentFormat; import org.semanticweb.owlapi.model.*; import org.semanticweb.owlapi.reasoner.InconsistentOntologyException; import owltools.cli.JsCommandRunner; import owltools.cli.Opts; import owltools.cli.tools.CLIMethod; import owltools.gaf.GafDocument; import owltools.gaf.GeneAnnotation; import owltools.gaf.eco.EcoMapperFactory; import owltools.gaf.eco.SimpleEcoMapper; import owltools.gaf.io.GafWriter; import owltools.gaf.io.GpadWriter; import owltools.graph.OWLGraphWrapper; import uk.ac.manchester.cs.owlapi.modularity.ModuleType; import uk.ac.manchester.cs.owlapi.modularity.SyntacticLocalityModuleExtractor; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.*; public class MinervaCommandRunner extends JsCommandRunner { private static final Logger LOGGER = Logger.getLogger(MinervaCommandRunner.class); @CLIMethod("--dump-owl-models") public void modelsToOWL(Opts opts) throws Exception { opts.info("[-j|--journal JOURNALFILE] [-f|--folder OWLFILESFOLDER] [-p|--prefix MODELIDPREFIX]", "dumps all LEGO models to OWL Turtle files"); // parameters String journalFilePath = null; String outputFolder = null; String modelIdPrefix = "http://model.geneontology.org/"; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-j|--journal")) { opts.info("journal file", "Sets the Blazegraph journal file for the database"); journalFilePath = opts.nextOpt(); } else if (opts.nextEq("-f|--folder")) { opts.info("OWL folder", "Sets the output folder the LEGO model files"); outputFolder = opts.nextOpt(); } else if (opts.nextEq("-p|--prefix")) { opts.info("model ID prefix", "Sets the URI prefix for model IDs"); modelIdPrefix = opts.nextOpt(); } else { break; } } // minimal inputs if (journalFilePath == null) { System.err.println("No journal file was configured."); exit(-1); return; } if (outputFolder == null) { System.err.println("No output folder was configured."); exit(-1); return; } OWLOntology dummy = OWLManager.createOWLOntologyManager().createOntology(IRI.create("http://example.org/dummy")); CurieHandler curieHandler = new MappedCurieHandler(); BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(dummy, curieHandler, modelIdPrefix, journalFilePath, outputFolder); m3.dumpAllStoredModels(); m3.dispose(); } @CLIMethod("--import-owl-models") public void importOWLModels(Opts opts) throws Exception { opts.info("[-j|--journal JOURNALFILE] [-f|--folder OWLFILESFOLDER]", "import all files in folder to database"); // parameters String journalFilePath = null; String inputFolder = null; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-j|--journal")) { opts.info("journal file", "Sets the Blazegraph journal file for the database"); journalFilePath = opts.nextOpt(); } else if (opts.nextEq("-f|--folder")) { opts.info("OWL folder", "Sets the folder containing the LEGO model files"); inputFolder = opts.nextOpt(); } else { break; } } // minimal inputs if (journalFilePath == null) { System.err.println("No journal file was configured."); exit(-1); return; } if (inputFolder == null) { System.err.println("No input folder was configured."); exit(-1); return; } OWLOntology dummy = OWLManager.createOWLOntologyManager().createOntology(IRI.create("http://example.org/dummy")); String modelIdPrefix = "http://model.geneontology.org/"; // this will not be used for anything CurieHandler curieHandler = new MappedCurieHandler(); BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(dummy, curieHandler, modelIdPrefix, journalFilePath, null); for (File file : FileUtils.listFiles(new File(inputFolder), null, true)) { LOGGER.info("Loading " + file); m3.importModelToDatabase(file, true); } m3.dispose(); } @CLIMethod("--sparql-update") public void sparqlUpdate(Opts opts) throws OWLOntologyCreationException, IOException, RepositoryException, MalformedQueryException, UpdateExecutionException { opts.info("[-j|--journal JOURNALFILE] [-f|--file SPARQL UPDATE FILE]", "apply SPARQL update to database"); String journalFilePath = null; String updateFile = null; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-j|--journal")) { opts.info("journal file", "Sets the Blazegraph journal file for the database"); journalFilePath = opts.nextOpt(); } else if (opts.nextEq("-f|--file")) { opts.info("OWL folder", "Sets the file containing a SPARQL update"); updateFile = opts.nextOpt(); } else { break; } } // minimal inputs if (journalFilePath == null) { System.err.println("No journal file was configured."); exit(-1); return; } if (updateFile == null) { System.err.println("No update file was configured."); exit(-1); return; } String update = FileUtils.readFileToString(new File(updateFile), StandardCharsets.UTF_8); Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/org/geneontology/minerva/blazegraph.properties")); properties.setProperty(Options.FILE, journalFilePath); BigdataSail sail = new BigdataSail(properties); BigdataSailRepository repository = new BigdataSailRepository(sail); repository.initialize(); BigdataSailRepositoryConnection conn = repository.getUnisolatedConnection(); BlazegraphMutationCounter counter = new BlazegraphMutationCounter(); conn.addChangeLog(counter); conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); int changes = counter.mutationCount(); conn.removeChangeLog(counter); System.out.println("\nApplied " + changes + " changes"); conn.close(); } @CLIMethod("--owl-lego-to-json") public void owl2LegoJson(Opts opts) throws Exception { opts.info("[-o JSONFILE] [-i OWLFILE] [--pretty-json] [--compact-json]", "converts the LEGO subset of OWL to Minerva-JSON"); // parameters String input = null; String output = null; boolean usePretty = true; // parse opts while (opts.hasOpts()) { if (opts.nextEq("-o|--output")) { opts.info("output", "Sets the output file for the json"); output = opts.nextOpt(); } else if (opts.nextEq("-i|--input")) { opts.info("input", "Sets the input file for the model"); input = opts.nextOpt(); } else if (opts.nextEq("--pretty-json")) { opts.info("", "pretty print the output json"); usePretty = true; } else if (opts.nextEq("--compact-json")) { opts.info("", "compact print the output json"); usePretty = false; } else { break; } } // minimal inputs if (input == null) { System.err.println("No input model was configured."); exit(-1); return; } if (output == null) { System.err.println("No output file was configured."); exit(-1); return; } // configuration CurieHandler curieHandler = DefaultCurieHandler.getDefaultHandler(); GsonBuilder gsonBuilder = new GsonBuilder(); if (usePretty) { gsonBuilder.setPrettyPrinting(); } Gson gson = gsonBuilder.create(); // process each model if (LOGGER.isInfoEnabled()) { LOGGER.info("Loading model from file: "+input); } OWLOntology model = null; final JsonModel jsonModel; try { // load model model = pw.parseOWL(IRI.create(new File(input).getCanonicalFile())); InferenceProvider inferenceProvider = null; // TODO decide if we need reasoning String modelId = null; Optional<IRI> ontologyIRI = model.getOntologyID().getOntologyIRI(); if (ontologyIRI.isPresent()) { modelId = curieHandler.getCuri(ontologyIRI.get()); } // render json final MolecularModelJsonRenderer renderer = new MolecularModelJsonRenderer(modelId, model, inferenceProvider, curieHandler); jsonModel = renderer.renderModel(); } finally { if (model != null) { pw.getManager().removeOntology(model); model = null; } } // save as json string final String json = gson.toJson(jsonModel); final File outputFile = new File(output).getCanonicalFile(); try (OutputStream outputStream = new FileOutputStream(outputFile)) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Saving json to file: "+outputFile); } IOUtils.write(json, outputStream); } } /** * Translate the GeneAnnotations into a lego all individual OWL representation. * * Will merge the source ontology into the graph by default * * @param opts * @throws Exception */ @CLIMethod("--gaf-lego-individuals") public void gaf2LegoIndivduals(Opts opts) throws Exception { boolean addLineNumber = false; boolean merge = true; boolean minimize = false; String output = null; CurieHandler curieHandler = DefaultCurieHandler.getDefaultHandler(); OWLDocumentFormat format = new RDFXMLDocumentFormat(); while (opts.hasOpts()) { if (opts.nextEq("-o|--output")) { output = opts.nextOpt(); } else if (opts.nextEq("--format")) { String formatString = opts.nextOpt(); if ("manchester".equalsIgnoreCase(formatString)) { format = new ManchesterSyntaxDocumentFormat(); } else if ("turtle".equalsIgnoreCase(formatString)) { format = new TurtleDocumentFormat(); } else if ("functional".equalsIgnoreCase(formatString)) { format = new FunctionalSyntaxDocumentFormat(); } } else if (opts.nextEq("--add-line-number")) { addLineNumber = true; } else if (opts.nextEq("--skip-merge")) { merge = false; } else if (opts.nextEq("-m|--minimize")) { opts.info("", "use module extraction to include module of ontology"); minimize = true; } else { break; } } if (g != null && gafdoc != null && output != null) { GafToLegoIndividualTranslator tr = new GafToLegoIndividualTranslator(g, curieHandler, addLineNumber); OWLOntology lego = tr.translate(gafdoc); if (merge) { new OWLGraphWrapper(lego).mergeImportClosure(true); } if (minimize) { final OWLOntologyManager m = lego.getOWLOntologyManager(); SyntacticLocalityModuleExtractor sme = new SyntacticLocalityModuleExtractor(m, lego, ModuleType.BOT); Set<OWLEntity> sig = new HashSet<OWLEntity>(lego.getIndividualsInSignature()); Set<OWLAxiom> moduleAxioms = sme.extract(sig); OWLOntology module = m.createOntology(IRI.generateDocumentIRI()); m.addAxioms(module, moduleAxioms); lego = module; } OWLOntologyManager manager = lego.getOWLOntologyManager(); OutputStream outputStream = null; try { outputStream = new FileOutputStream(output); manager.saveOntology(lego, format, outputStream); } finally { IOUtils.closeQuietly(outputStream); } } else { if (output == null) { System.err.println("No output file was specified."); } if (g == null) { System.err.println("No graph available for gaf-run-check."); } if (gafdoc == null) { System.err.println("No loaded gaf available for gaf-run-check."); } exit(-1); return; } } /** * Output GPAD files via inference+SPARQL, for testing only * @param opts * @throws Exception */ @CLIMethod("--lego-to-gpad-sparql") public void legoToAnnotationsSPARQL(Opts opts) throws Exception { String modelIdPrefix = "http://model.geneontology.org/"; String modelIdcurie = "gomodel"; String inputDB = "blazegraph.jnl"; String gpadOutputFolder = null; String ontologyIRI = "http://purl.obolibrary.org/obo/go/extensions/go-lego.owl"; while (opts.hasOpts()) { if (opts.nextEq("-i|--input")) { inputDB = opts.nextOpt(); } else if (opts.nextEq("--gpad-output")) { gpadOutputFolder = opts.nextOpt(); } else if (opts.nextEq("--model-id-prefix")) { modelIdPrefix = opts.nextOpt(); } else if (opts.nextEq("--model-id-curie")) { modelIdcurie = opts.nextOpt(); } else if (opts.nextEq("--ontology")) { ontologyIRI = opts.nextOpt(); } else { break; } } OWLOntology ontology = OWLManager.createOWLOntologyManager().loadOntology(IRI.create(ontologyIRI)); CurieMappings localMappings = new CurieMappings.SimpleCurieMappings(Collections.singletonMap(modelIdcurie, modelIdPrefix)); CurieHandler curieHandler = new MappedCurieHandler(DefaultCurieHandler.loadDefaultMappings(), localMappings); BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(ontology, curieHandler, modelIdPrefix, inputDB, null); for (IRI modelIRI : m3.getAvailableModelIds()) { try { String gpad = new GPADSPARQLExport(curieHandler, m3.getLegacyRelationShorthandIndex(), m3.getTboxShorthandIndex(), m3.getDoNotAnnotateSubset()).exportGPAD(m3.createInferredModel(modelIRI)); String fileName = StringUtils.replaceOnce(modelIRI.toString(), modelIdPrefix, "") + ".gpad"; Writer writer = new OutputStreamWriter(new FileOutputStream(Paths.get(gpadOutputFolder, fileName).toFile()), StandardCharsets.UTF_8); writer.write(gpad); writer.close(); } catch (InconsistentOntologyException e) { LOGGER.error("Inconsistent ontology: " + modelIRI); } } m3.dispose(); } @CLIMethod("--lego-to-gpad") public void legoToAnnotations(Opts opts) throws Exception { String modelIdPrefix = "http://model.geneontology.org/"; String modelIdcurie = "gomodel"; String inputFolder = null; String singleFile = null; String gpadOutputFolder = null; String gafOutputFolder = null; Map<String, String> taxonGroups = null; String defaultTaxonGroup = "other"; boolean addLegoModelId = true; String fileSuffix = "ttl"; while (opts.hasOpts()) { if (opts.nextEq("-i|--input")) { inputFolder = opts.nextOpt(); } else if (opts.nextEq("--input-single-file")) { singleFile = opts.nextOpt(); } else if (opts.nextEq("--gpad-output")) { gpadOutputFolder = opts.nextOpt(); } else if (opts.nextEq("--gaf-output")) { gafOutputFolder = opts.nextOpt(); } else if (opts.nextEq("--remove-lego-model-ids")) { addLegoModelId = false; } else if (opts.nextEq("--model-id-prefix")) { modelIdPrefix = opts.nextOpt(); } else if (opts.nextEq("-s|--input-file-suffix")) { opts.info("SUFFIX", "if a directory is specified, use only files with this suffix. Default is 'ttl'"); fileSuffix = opts.nextOpt(); } else if (opts.nextEq("--model-id-curie")) { modelIdcurie = opts.nextOpt(); } else if (opts.nextEq("--group-by-model-organisms")) { if (taxonGroups == null) { taxonGroups = new HashMap<>(); } // get the pre-defined groups from the model-organism-groups.tsv resource List<String> lines = IOUtils.readLines(MinervaCommandRunner.class.getResourceAsStream("/model-organism-groups.tsv")); for (String line : lines) { line = StringUtils.trimToEmpty(line); if (line.isEmpty() == false && line.charAt(0) != '#') { String[] split = StringUtils.splitByWholeSeparator(line, "\t"); if (split.length > 1) { String group = split[0]; Set<String> taxonIds = new HashSet<>(); for (int i = 1; i < split.length; i++) { taxonIds.add(split[i]); } for(String taxonId : taxonIds) { taxonGroups.put(taxonId, group); } } } } } else if (opts.nextEq("--add-model-organism-group")) { if (taxonGroups == null) { taxonGroups = new HashMap<>(); } String group = opts.nextOpt(); String taxon = opts.nextOpt(); taxonGroups.put(taxon, group); } else if (opts.nextEq("--set-default-model-group")) { defaultTaxonGroup = opts.nextOpt(); } else { break; } } // create curie handler CurieMappings localMappings = new CurieMappings.SimpleCurieMappings(Collections.singletonMap(modelIdcurie, modelIdPrefix)); CurieHandler curieHandler = new MappedCurieHandler(DefaultCurieHandler.loadDefaultMappings(), localMappings); ExternalLookupService lookup= null; SimpleEcoMapper mapper = EcoMapperFactory.createSimple(); LegoToGeneAnnotationTranslator translator = new LegoToGeneAnnotationTranslator(g.getSourceOntology(), curieHandler, mapper); GroupingTranslator groupingTranslator = new GroupingTranslator(translator, lookup, taxonGroups, defaultTaxonGroup, addLegoModelId); final OWLOntologyManager m = g.getManager(); if (singleFile != null) { File file = new File(singleFile).getCanonicalFile(); OWLOntology model = m.loadOntology(IRI.create(file)); groupingTranslator.translate(model); } else if (inputFolder != null) { final String fileSuffixFinal = fileSuffix; File inputFile = new File(inputFolder).getCanonicalFile(); if (inputFile.isDirectory()) { File[] files = inputFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (fileSuffixFinal != null && fileSuffixFinal.length() > 0) return name.endsWith("."+fileSuffixFinal); else return StringUtils.isAlphanumeric(name); } }); for (File file : files) { OWLOntology model = m.loadOntology(IRI.create(file)); groupingTranslator.translate(model); } } } // by state for(String modelState : groupingTranslator.getModelStates()) { GafDocument annotations = groupingTranslator.getAnnotationsByState(modelState); sortAnnotations(annotations); if (annotations != null) { if (gpadOutputFolder != null) { writeGpad(annotations, gpadOutputFolder, "all-"+modelState); } if (gafOutputFolder != null) { writeGaf(annotations, gafOutputFolder, "all-"+modelState); } } } // by organism if (taxonGroups != null) { for(String group : groupingTranslator.getTaxonGroups()) { GafDocument filtered = groupingTranslator.getAnnotationsByGroup(group); sortAnnotations(filtered); if (gpadOutputFolder != null) { writeGpad(filtered, gpadOutputFolder, group); } if (gafOutputFolder != null) { writeGaf(filtered, gafOutputFolder, group); } } } // production only by organism if (taxonGroups != null) { for(String group : groupingTranslator.getProductionTaxonGroups()) { GafDocument filtered = groupingTranslator.getProductionAnnotationsByGroup(group); sortAnnotations(filtered); if (gpadOutputFolder != null) { String productionFolder = new File(gpadOutputFolder, "production").getAbsolutePath(); writeGpad(filtered, productionFolder+"", group); } if (gafOutputFolder != null) { String productionFolder = new File(gafOutputFolder, "production").getAbsolutePath(); writeGaf(filtered, productionFolder, group); } } } } static void sortAnnotations(GafDocument annotations) { Collections.sort(annotations.getGeneAnnotations(), new Comparator<GeneAnnotation>() { @Override public int compare(GeneAnnotation a1, GeneAnnotation a2) { return a1.toString().compareTo(a2.toString()); } }); } private void writeGaf(GafDocument annotations, String outputFolder, String fileName) { File outputFile = new File(outputFolder, fileName+".gaf"); GafWriter writer = new GafWriter(); try { outputFile.getParentFile().mkdirs(); writer.setStream(outputFile); writer.write(annotations); } finally { IOUtils.closeQuietly(writer); } } private void writeGpad(GafDocument annotations, String outputFolder, String fileName) throws FileNotFoundException { PrintWriter fileWriter = null; File outputFile = new File(outputFolder, fileName+".gpad"); try { outputFile.getParentFile().mkdirs(); fileWriter = new PrintWriter(outputFile); GpadWriter writer = new GpadWriter(fileWriter, 1.2d); writer.write(annotations); } finally { IOUtils.closeQuietly(fileWriter); } } }
Run command-line GPAD export in parallel.
minerva-cli/src/main/java/org/geneontology/minerva/cli/MinervaCommandRunner.java
Run command-line GPAD export in parallel.
<ide><path>inerva-cli/src/main/java/org/geneontology/minerva/cli/MinervaCommandRunner.java <ide> CurieMappings localMappings = new CurieMappings.SimpleCurieMappings(Collections.singletonMap(modelIdcurie, modelIdPrefix)); <ide> CurieHandler curieHandler = new MappedCurieHandler(DefaultCurieHandler.loadDefaultMappings(), localMappings); <ide> BlazegraphMolecularModelManager<Void> m3 = new BlazegraphMolecularModelManager<>(ontology, curieHandler, modelIdPrefix, inputDB, null); <del> for (IRI modelIRI : m3.getAvailableModelIds()) { <add> final String immutableModelIdPrefix = modelIdPrefix; <add> final String immutableGpadOutputFolder = gpadOutputFolder; <add> m3.getAvailableModelIds().stream().parallel().forEach(modelIRI -> { <ide> try { <ide> String gpad = new GPADSPARQLExport(curieHandler, m3.getLegacyRelationShorthandIndex(), m3.getTboxShorthandIndex(), m3.getDoNotAnnotateSubset()).exportGPAD(m3.createInferredModel(modelIRI)); <del> String fileName = StringUtils.replaceOnce(modelIRI.toString(), modelIdPrefix, "") + ".gpad"; <del> Writer writer = new OutputStreamWriter(new FileOutputStream(Paths.get(gpadOutputFolder, fileName).toFile()), StandardCharsets.UTF_8); <add> String fileName = StringUtils.replaceOnce(modelIRI.toString(), immutableModelIdPrefix, "") + ".gpad"; <add> Writer writer = new OutputStreamWriter(new FileOutputStream(Paths.get(immutableGpadOutputFolder, fileName).toFile()), StandardCharsets.UTF_8); <ide> writer.write(gpad); <del> writer.close(); <add> writer.close(); <ide> } catch (InconsistentOntologyException e) { <ide> LOGGER.error("Inconsistent ontology: " + modelIRI); <del> } <del> } <add> } catch (IOException e) { <add> LOGGER.error("Couldn't export GPAD for: " + modelIRI, e); <add> } <add> }); <ide> m3.dispose(); <ide> } <ide>
Java
apache-2.0
9be8a8a969be1c6a54e63a6dd6012a603b774da0
0
zml2008/configurate,zml2008/configurate
/** * Configurate * Copyright (C) zml and Configurate contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ninja.leaping.configurate.hocon; import com.google.common.io.Files; import com.google.common.io.Resources; import ninja.leaping.configurate.ConfigurationOptions; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.net.URL; import static org.junit.Assert.*; import static ninja.leaping.configurate.loader.AbstractConfigurationLoader.UTF8_CHARSET; /** * Basic sanity checks for the loader */ public class HoconConfigurationLoaderTest { @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void testSimpleLoading() throws IOException { URL url = getClass().getResource("/example.conf"); final File saveTest = folder.newFile(); HoconConfigurationLoader loader = HoconConfigurationLoader.builder() .setSource(Resources.asCharSource(url, UTF8_CHARSET)) .setSink(Files.asCharSink(saveTest, UTF8_CHARSET)).build(); CommentedConfigurationNode node = loader.load(); assertEquals("unicorn", node.getNode("test", "op-level").getValue()); assertEquals("dragon", node.getNode("other", "op-level").getValue()); CommentedConfigurationNode testNode = node.getNode("test"); assertEquals(" Test node", testNode.getComment().orNull()); assertEquals("dog park", node.getNode("other", "location").getValue()); loader.save(node); assertEquals(Resources.toString(getClass().getResource("/roundtrip-test.conf"), UTF8_CHARSET), Files .toString(saveTest, UTF8_CHARSET)); } @Test public void testHeaderSaved() { } @Test public void testBooleansNotShared() throws IOException { URL url = getClass().getResource("/comments-test.conf"); final File saveTo = folder.newFile(); HoconConfigurationLoader loader = HoconConfigurationLoader.builder() .setFile(saveTo).setURL(url).build(); CommentedConfigurationNode node = loader.createEmptyNode(ConfigurationOptions.defaults()); node.getNode("test", "third").setValue(false).setComment("really?"); node.getNode("test", "apple").setComment("fruit").setValue(false); node.getNode("test", "donut").setValue(true).setComment("tasty"); node.getNode("test", "guacamole").setValue(true).setComment("and chips?"); loader.save(node); assertEquals(Resources.toString(url, UTF8_CHARSET), Files.toString(saveTo, UTF8_CHARSET)); } }
configurate-hocon/src/test/java/ninja/leaping/configurate/hocon/HoconConfigurationLoaderTest.java
/** * Configurate * Copyright (C) zml and Configurate contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ninja.leaping.configurate.hocon; import com.google.common.io.Files; import com.google.common.io.Resources; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.net.URL; import static org.junit.Assert.*; import static ninja.leaping.configurate.loader.AbstractConfigurationLoader.UTF8_CHARSET; /** * Basic sanity checks for the loader */ public class HoconConfigurationLoaderTest { @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void testSimpleLoading() throws IOException { URL url = getClass().getResource("/example.conf"); final File saveTest = folder.newFile(); HoconConfigurationLoader loader = HoconConfigurationLoader.builder() .setSource(Resources.asCharSource(url, UTF8_CHARSET)) .setSink(Files.asCharSink(saveTest, UTF8_CHARSET)).build(); CommentedConfigurationNode node = loader.load(); assertEquals("unicorn", node.getNode("test", "op-level").getValue()); assertEquals("dragon", node.getNode("other", "op-level").getValue()); CommentedConfigurationNode testNode = node.getNode("test"); assertEquals(" Test node", testNode.getComment().orNull()); assertEquals("dog park", node.getNode("other", "location").getValue()); loader.save(node); assertEquals(Resources.toString(getClass().getResource("/roundtrip-test.conf"), UTF8_CHARSET), Files .toString(saveTest, UTF8_CHARSET)); } @Test public void testHeaderSaved() { } @Test public void testBooleansNotShared() throws IOException { URL url = getClass().getResource("/comments-test.conf"); final File saveTo = folder.newFile(); HoconConfigurationLoader loader = HoconConfigurationLoader.builder() .setFile(saveTo).setURL(url).build(); CommentedConfigurationNode node = loader.createEmptyNode(); node.getNode("test", "third").setValue(false).setComment("really?"); node.getNode("test", "apple").setComment("fruit").setValue(false); node.getNode("test", "donut").setValue(true).setComment("tasty"); node.getNode("test", "guacamole").setValue(true).setComment("and chips?"); loader.save(node); assertEquals(Resources.toString(url, UTF8_CHARSET), Files.toString(saveTo, UTF8_CHARSET)); } }
Look at me, breaking the build
configurate-hocon/src/test/java/ninja/leaping/configurate/hocon/HoconConfigurationLoaderTest.java
Look at me, breaking the build
<ide><path>onfigurate-hocon/src/test/java/ninja/leaping/configurate/hocon/HoconConfigurationLoaderTest.java <ide> <ide> import com.google.common.io.Files; <ide> import com.google.common.io.Resources; <add>import ninja.leaping.configurate.ConfigurationOptions; <ide> import ninja.leaping.configurate.commented.CommentedConfigurationNode; <ide> import org.junit.Rule; <ide> import org.junit.Test; <ide> HoconConfigurationLoader loader = HoconConfigurationLoader.builder() <ide> .setFile(saveTo).setURL(url).build(); <ide> <del> CommentedConfigurationNode node = loader.createEmptyNode(); <add> CommentedConfigurationNode node = loader.createEmptyNode(ConfigurationOptions.defaults()); <ide> node.getNode("test", "third").setValue(false).setComment("really?"); <ide> node.getNode("test", "apple").setComment("fruit").setValue(false); <ide> node.getNode("test", "donut").setValue(true).setComment("tasty");
Java
apache-2.0
6bc9d4fb1e89b71efd911b5e184a8981e7492293
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.psi.impl; import com.intellij.codeInsight.completion.CompletionUtilCoreImpl; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveResult; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.jetbrains.python.PyNames; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.resolve.*; import com.jetbrains.python.psi.types.*; import com.jetbrains.python.pyi.PyiUtil; import com.jetbrains.python.toolbox.Maybe; import one.util.streamex.StreamEx; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Functions common to different implementors of PyCallExpression, with different base classes. * User: dcheryasov */ public final class PyCallExpressionHelper { private PyCallExpressionHelper() { } /** * Tries to interpret a call as a call to built-in {@code classmethod} or {@code staticmethod}. * * @param redefiningCall the possible call, generally a result of chasing a chain of assignments * @return a pair of wrapper name and wrapped function; for {@code staticmethod(foo)} it would be ("staticmethod", foo). */ @Nullable public static Pair<String, PyFunction> interpretAsModifierWrappingCall(PyCallExpression redefiningCall) { PyExpression redefining_callee = redefiningCall.getCallee(); if (redefiningCall.isCalleeText(PyNames.CLASSMETHOD, PyNames.STATICMETHOD)) { final PyReferenceExpression referenceExpr = (PyReferenceExpression)redefining_callee; if (referenceExpr != null) { final String refName = referenceExpr.getReferencedName(); if ((PyNames.CLASSMETHOD.equals(refName) || PyNames.STATICMETHOD.equals(refName)) && PyBuiltinCache.isInBuiltins(referenceExpr)) { // yes, really a case of "foo = classmethod(foo)" PyArgumentList argumentList = redefiningCall.getArgumentList(); if (argumentList != null) { // really can't be any other way PyExpression[] args = argumentList.getArguments(); if (args.length == 1) { PyExpression possible_original_ref = args[0]; if (possible_original_ref instanceof PyReferenceExpression) { PsiElement original = ((PyReferenceExpression)possible_original_ref).getReference().resolve(); if (original instanceof PyFunction) { // pinned down the original; replace our resolved callee with it and add flags. return Pair.create(refName, (PyFunction)original); } } } } } } } return null; } @Nullable public static PyClass resolveCalleeClass(PyCallExpression us) { PyExpression callee = us.getCallee(); PsiElement resolved; QualifiedResolveResult resolveResult; if (callee instanceof PyReferenceExpression) { // dereference PyReferenceExpression ref = (PyReferenceExpression)callee; resolveResult = ref.followAssignmentsChain(PyResolveContext.defaultContext()); resolved = resolveResult.getElement(); } else { resolved = callee; } // analyze if (resolved instanceof PyClass) { return (PyClass)resolved; } else if (resolved instanceof PyFunction) { final PyFunction pyFunction = (PyFunction)resolved; return pyFunction.getContainingClass(); } return null; } /** * This method should not be called directly, * please obtain its result via {@link TypeEvalContext#getType} with {@code call.getCallee()} as an argument. */ static @Nullable PyType getCalleeType(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext, @SuppressWarnings("unused") @NotNull TypeEvalContext.Key key) { final List<PyType> callableTypes = new ArrayList<>(); final TypeEvalContext context = resolveContext.getTypeEvalContext(); final List<QualifiedRatedResolveResult> results = PyUtil.filterTopPriorityResults( forEveryScopeTakeOverloadsOtherwiseImplementations( multiResolveCallee(call.getCallee(), resolveContext), RatedResolveResult::getElement, context ) ); for (QualifiedRatedResolveResult resolveResult : results) { final PsiElement element = resolveResult.getElement(); if (element != null) { final PyType typeFromProviders = Ref.deref(PyReferenceExpressionImpl.getReferenceTypeFromProviders(element, resolveContext.getTypeEvalContext(), call)); if (typeFromProviders instanceof PyCallableType) { callableTypes.add(typeFromProviders); continue; } } for (ClarifiedResolveResult clarifiedResolveResult : clarifyResolveResult(resolveResult, resolveContext)) { ContainerUtil.addIfNotNull(callableTypes, toCallableType(call, clarifiedResolveResult, context)); } } return PyUnionType.union(callableTypes); } @Nullable public static PyExpression getReceiver(@NotNull PyCallExpression call, @Nullable PyCallable resolvedCallee) { if (resolvedCallee instanceof PyFunction) { final PyFunction function = (PyFunction)resolvedCallee; if (!PyNames.NEW.equals(function.getName()) && function.getModifier() == PyFunction.Modifier.STATICMETHOD) { return null; } } final PyExpression callee = call.getCallee(); if (callee != null && isImplicitlyInvokedMethod(resolvedCallee) && !Objects.equals(resolvedCallee.getName(), callee.getName())) { return callee; } if (callee instanceof PyQualifiedExpression) { return ((PyQualifiedExpression)callee).getQualifier(); } return null; } @Contract("null -> false") private static boolean isImplicitlyInvokedMethod(@Nullable PyCallable resolvedCallee) { if (PyUtil.isInitOrNewMethod(resolvedCallee)) return true; if (resolvedCallee instanceof PyFunction) { final PyFunction function = (PyFunction)resolvedCallee; return PyNames.CALL.equals(function.getName()) && function.getContainingClass() != null; } return false; } /** * It is not the same as {@link PyCallExpressionHelper#getCalleeType} since * this method returns callable types that would be actually called, the mentioned method returns type of underlying callee. * Compare: * <pre> * {@code * class A: * pass * a = A() * b = a() # callee type is A, resolved callee is A.__call__ * } * </pre> */ @NotNull static List<@NotNull PyCallableType> multiResolveCallee(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext) { return PyUtil.getParameterizedCachedValue( call, resolveContext, it -> ContainerUtil.concat(getExplicitResolveResults(call, it), getImplicitResolveResults(call, it)) ); } private static @NotNull List<@NotNull PyCallableType> multiResolveCallee(@NotNull PySubscriptionExpression subscription, @NotNull PyResolveContext resolveContext) { final TypeEvalContext context = resolveContext.getTypeEvalContext(); final List<ResolveResult> results = PyUtil.filterTopPriorityResults( forEveryScopeTakeOverloadsOtherwiseImplementations( Arrays.asList(subscription.getReference(resolveContext).multiResolve(false)), ResolveResult::getElement, context ) ); return selectCallableTypes(ResolveResultList.getElements(results), context); } @NotNull private static List<@NotNull PyCallableType> getExplicitResolveResults(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext) { final var callee = call.getCallee(); if (callee == null) return Collections.emptyList(); final TypeEvalContext context = resolveContext.getTypeEvalContext(); final var calleeType = context.getType(callee); final var provided = StreamEx .of(PyTypeProvider.EP_NAME.getExtensionList()) .map(e -> e.prepareCalleeTypeForCall(calleeType, call, context)) .nonNull() .toList(); if (!provided.isEmpty()) return ContainerUtil.mapNotNull(provided, Ref::deref); final List<PyCallableType> result = new ArrayList<>(); for (PyType type : PyTypeUtil.toStream(calleeType)) { if (type instanceof PyClassType) { final var classType = (PyClassType)type; final var implicitlyInvokedMethods = forEveryScopeTakeOverloadsOtherwiseImplementations( resolveImplicitlyInvokedMethods(classType, call, resolveContext), Function.identity(), context ); if (implicitlyInvokedMethods.isEmpty()) { result.add(classType); } else { result.addAll(changeToImplicitlyInvokedMethods(classType, implicitlyInvokedMethods, call, context)); } } else if (type instanceof PyCallableType) { result.add((PyCallableType)type); } } return result; } @NotNull private static List<@NotNull PyCallableType> getImplicitResolveResults(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext) { if (!resolveContext.allowImplicits()) return Collections.emptyList(); final PyExpression callee = call.getCallee(); final TypeEvalContext context = resolveContext.getTypeEvalContext(); if (callee instanceof PyQualifiedExpression) { final PyQualifiedExpression qualifiedCallee = (PyQualifiedExpression)callee; final String referencedName = qualifiedCallee.getReferencedName(); if (referencedName == null) return Collections.emptyList(); final PyExpression qualifier = qualifiedCallee.getQualifier(); if (qualifier == null || !canQualifyAnImplicitName(qualifier)) return Collections.emptyList(); final PyType qualifierType = context.getType(qualifier); if (PyTypeChecker.isUnknown(qualifierType, context) || qualifierType instanceof PyStructuralType && ((PyStructuralType)qualifierType).isInferredFromUsages()) { final ResolveResultList resolveResults = new ResolveResultList(); PyResolveUtil.addImplicitResolveResults(referencedName, resolveResults, qualifiedCallee); return selectCallableTypes( forEveryScopeTakeOverloadsOtherwiseImplementations(ResolveResultList.getElements(resolveResults), Function.identity(), context), context ); } } return Collections.emptyList(); } @NotNull private static List<@NotNull PyCallableType> selectCallableTypes(@NotNull List<PsiElement> resolveResults, @NotNull TypeEvalContext context) { return StreamEx .of(resolveResults) .select(PyTypedElement.class) .map(context::getType) .flatMap(PyTypeUtil::toStream) .select(PyCallableType.class) .toList(); } @NotNull private static List<QualifiedRatedResolveResult> multiResolveCallee(@Nullable PyExpression callee, @NotNull PyResolveContext resolveContext) { if (callee instanceof PyReferenceExpression) { return ((PyReferenceExpression)callee).multiFollowAssignmentsChain(resolveContext); } else if (callee instanceof PyLambdaExpression) { return Collections.singletonList( new QualifiedRatedResolveResult(callee, Collections.emptyList(), RatedResolveResult.RATE_NORMAL, false) ); } return Collections.emptyList(); } @NotNull private static List<ClarifiedResolveResult> clarifyResolveResult(@NotNull QualifiedRatedResolveResult resolveResult, @NotNull PyResolveContext resolveContext) { final PsiElement resolved = resolveResult.getElement(); if (resolved instanceof PyCallExpression) { // foo = classmethod(foo) final PyCallExpression resolvedCall = (PyCallExpression)resolved; final Pair<String, PyFunction> wrapperInfo = interpretAsModifierWrappingCall(resolvedCall); if (wrapperInfo != null) { final String wrapperName = wrapperInfo.getFirst(); final PyFunction.Modifier wrappedModifier = PyNames.CLASSMETHOD.equals(wrapperName) ? PyFunction.Modifier.CLASSMETHOD : PyNames.STATICMETHOD.equals(wrapperName) ? PyFunction.Modifier.STATICMETHOD : null; final ClarifiedResolveResult result = new ClarifiedResolveResult(resolveResult, wrapperInfo.getSecond(), wrappedModifier, false); return Collections.singletonList(result); } } else if (resolved instanceof PyFunction) { final PyFunction function = (PyFunction)resolved; final TypeEvalContext context = resolveContext.getTypeEvalContext(); if (function.getProperty() != null && isQualifiedByInstance(function, resolveResult.getQualifiers(), context)) { final PyType type = context.getReturnType(function); return type instanceof PyFunctionType ? Collections.singletonList(new ClarifiedResolveResult(resolveResult, ((PyFunctionType)type).getCallable(), null, false)) : Collections.emptyList(); } } return resolved != null ? Collections.singletonList(new ClarifiedResolveResult(resolveResult, resolved, null, resolved instanceof PyClass)) : Collections.emptyList(); } private static @Nullable PyCallableType toCallableType(@NotNull PyCallSiteExpression callSite, @NotNull ClarifiedResolveResult resolveResult, @NotNull TypeEvalContext context) { final PsiElement clarifiedResolved = resolveResult.myClarifiedResolved; if (!(clarifiedResolved instanceof PyTypedElement)) return null; final PyCallableType callableType = PyUtil.as(context.getType((PyTypedElement)clarifiedResolved), PyCallableType.class); if (callableType == null) return null; if (clarifiedResolved instanceof PyCallable) { final PyCallable callable = (PyCallable)clarifiedResolved; final PyFunction.Modifier originalModifier = callable instanceof PyFunction ? ((PyFunction)callable).getModifier() : null; final PyFunction.Modifier resolvedModifier = ObjectUtils.chooseNotNull(originalModifier, resolveResult.myWrappedModifier); final boolean isConstructorCall = resolveResult.myIsConstructor; final List<PyExpression> qualifiers = resolveResult.myOriginalResolveResult.getQualifiers(); final boolean isByInstance = isConstructorCall || isQualifiedByInstance(callable, qualifiers, context) || callable instanceof PyBoundFunction; final PyExpression lastQualifier = ContainerUtil.getLastItem(qualifiers); final boolean isByClass = lastQualifier != null && isQualifiedByClass(callable, lastQualifier, context); final int resolvedImplicitOffset = getImplicitArgumentCount(callable, resolvedModifier, isConstructorCall, isByInstance, isByClass); final PyType clarifiedConstructorCallType = PyUtil.isInitOrNewMethod(clarifiedResolved) ? clarifyConstructorCallType(resolveResult, callSite, context) : null; if (callableType.getModifier() == resolvedModifier && callableType.getImplicitOffset() == resolvedImplicitOffset && clarifiedConstructorCallType == null) { return callableType; } return new PyCallableTypeImpl( callableType.getParameters(context), ObjectUtils.chooseNotNull(clarifiedConstructorCallType, callableType.getCallType(context, callSite)), callable, resolvedModifier, Math.max(0, resolvedImplicitOffset)); // wrong source can trigger strange behaviour } return callableType; } /** * Calls the {@link #getImplicitArgumentCount(PyCallable, PyFunction.Modifier, boolean, boolean, boolean)} full version} * with null flags and with isByInstance inferred directly from call site (won't work with reassigned bound methods). * * @param callReference the call site, where arguments are given. * @param function resolved method which is being called; plain functions are OK but make little sense. * @return a non-negative number of parameters that are implicit to this call. */ public static int getImplicitArgumentCount(@NotNull final PyReferenceExpression callReference, @NotNull PyFunction function, @NotNull PyResolveContext resolveContext) { QualifiedResolveResult followed = callReference.followAssignmentsChain(resolveContext); final List<PyExpression> qualifiers = followed.getQualifiers(); final PyExpression firstQualifier = ContainerUtil.getFirstItem(qualifiers); boolean isByInstance = isQualifiedByInstance(function, qualifiers, resolveContext.getTypeEvalContext()); String name = callReference.getName(); final boolean isConstructorCall = PyUtil.isInitOrNewMethod(function) && (!callReference.isQualified() || !PyNames.INIT.equals(name) && !PyNames.NEW.equals(name)); boolean isByClass = firstQualifier != null && isQualifiedByClass(function, firstQualifier, resolveContext.getTypeEvalContext()); return getImplicitArgumentCount(function, function.getModifier(), isConstructorCall, isByInstance, isByClass); } /** * Finds how many arguments are implicit in a given call. * * @param callable resolved method which is being called; non-methods immediately return 0. * @param isByInstance true if the call is known to be by instance (not by class). * @return a non-negative number of parameters that are implicit to this call. E.g. for a typical method call 1 is returned * because one parameter ('self') is implicit. */ private static int getImplicitArgumentCount( PyCallable callable, PyFunction.Modifier modifier, boolean isConstructorCall, boolean isByInstance, boolean isByClass ) { int implicit_offset = 0; boolean firstIsArgsOrKwargs = false; final PyParameter[] parameters = callable.getParameterList().getParameters(); if (parameters.length > 0) { final PyParameter first = parameters[0]; final PyNamedParameter named = first.getAsNamed(); if (named != null && (named.isPositionalContainer() || named.isKeywordContainer())) { firstIsArgsOrKwargs = true; } } if (!firstIsArgsOrKwargs && (isByInstance || isConstructorCall)) { implicit_offset += 1; } PyFunction method = callable.asMethod(); if (method == null) return implicit_offset; if (PyUtil.isNewMethod(method)) { return isConstructorCall ? 1 : 0; } if (!isByInstance && !isByClass && PyUtil.isInitMethod(method)) { return 1; } // decorators? if (modifier == PyFunction.Modifier.STATICMETHOD) { if (isByInstance && implicit_offset > 0) implicit_offset -= 1; // might have marked it as implicit 'self' } else if (modifier == PyFunction.Modifier.CLASSMETHOD) { if (!isByInstance) implicit_offset += 1; // Both Foo.method() and foo.method() have implicit the first arg } return implicit_offset; } private static boolean isQualifiedByInstance(@Nullable PyCallable resolved, @NotNull List<PyExpression> qualifiers, @NotNull TypeEvalContext context) { PyDocStringOwner owner = PsiTreeUtil.getStubOrPsiParentOfType(resolved, PyDocStringOwner.class); if (!(owner instanceof PyClass)) { return false; } // true = call by instance if (qualifiers.isEmpty()) { return true; // unqualified + method = implicit constructor call } for (PyExpression qualifier : qualifiers) { if (qualifier != null && isQualifiedByInstance(resolved, qualifier, context)) { return true; } } return false; } private static boolean isQualifiedByInstance(@Nullable PyCallable resolved, @NotNull PyExpression qualifier, @NotNull TypeEvalContext context) { if (isQualifiedByClass(resolved, qualifier, context)) { return false; } final PyType qualifierType = context.getType(qualifier); if (qualifierType != null) { // TODO: handle UnionType if (qualifierType instanceof PyModuleType) return false; // qualified by module, not instance. } return true; // NOTE. best guess: unknown qualifier is more probably an instance. } private static boolean isQualifiedByClass(@Nullable PyCallable resolved, @NotNull PyExpression qualifier, @NotNull TypeEvalContext context) { final PyType qualifierType = context.getType(qualifier); if (qualifierType instanceof PyClassType) { final PyClassType qualifierClassType = (PyClassType)qualifierType; return qualifierClassType.isDefinition() && belongsToSpecifiedClassHierarchy(resolved, qualifierClassType.getPyClass(), context); } else if (qualifierType instanceof PyClassLikeType) { return ((PyClassLikeType)qualifierType).isDefinition(); // Any definition means callable is classmethod } else if (qualifierType instanceof PyUnionType) { final Collection<PyType> members = ((PyUnionType)qualifierType).getMembers(); if (ContainerUtil.all(members, type -> type == null || type instanceof PyNoneType || type instanceof PyClassType)) { return StreamEx .of(members) .select(PyClassType.class) .filter(type -> belongsToSpecifiedClassHierarchy(resolved, type.getPyClass(), context)) .allMatch(PyClassType::isDefinition); } } return false; } private static boolean belongsToSpecifiedClassHierarchy(@Nullable PsiElement element, @NotNull PyClass cls, @NotNull TypeEvalContext context) { final PyClass parent = PsiTreeUtil.getStubOrPsiParentOfType(element, PyClass.class); return parent != null && (cls.isSubclass(parent, context) || parent.isSubclass(cls, context)); } /** * This method should not be called directly, * please obtain its result via {@link TypeEvalContext#getType} with {@code call} as an argument. */ static @Nullable PyType getCallType(@NotNull PyCallExpression call, @NotNull TypeEvalContext context, @SuppressWarnings("unused") @NotNull TypeEvalContext.Key key) { PyExpression callee = call.getCallee(); if (callee instanceof PyReferenceExpression) { // hardwired special cases if (PyNames.SUPER.equals(callee.getText())) { final Maybe<PyType> superCallType = getSuperCallType(call, context); if (superCallType.isDefined()) { return superCallType.value(); } } if ("type".equals(callee.getText())) { final PyExpression[] args = call.getArguments(); if (args.length == 1) { final PyExpression arg = args[0]; final PyType argType = context.getType(arg); if (argType instanceof PyClassType) { final PyClassType classType = (PyClassType)argType; if (!classType.isDefinition()) { final PyClass cls = classType.getPyClass(); return context.getType(cls); } } else { return null; } } } } final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); return getCallType(multiResolveCallee(call, resolveContext), call, context); } /** * This method should not be called directly, * please obtain its result via {@link TypeEvalContext#getType} with {@code subscription} as an argument. */ static @Nullable PyType getCallType(@NotNull PySubscriptionExpression subscription, @NotNull TypeEvalContext context, @SuppressWarnings("unused") @NotNull TypeEvalContext.Key key) { final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); return getCallType(multiResolveCallee(subscription, resolveContext), subscription, context); } private static @Nullable PyType getCallType(@NotNull List<@NotNull PyCallableType> callableTypes, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { return PyUnionType.union( ContainerUtil.map( dropNotMatchedOverloadsOrLeaveAsIs( ContainerUtil.filter(callableTypes, PyCallableType::isCallable), PyCallableType::getCallable, callSite, context ), it -> it.getCallType(context, callSite) ) ); } private static @Nullable PyType clarifyConstructorCallType(@NotNull ClarifiedResolveResult initOrNew, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { final PyFunction initOrNewMethod = (PyFunction)initOrNew.myClarifiedResolved; final PyClass initOrNewClass = initOrNewMethod.getContainingClass(); final PyClass receiverClass = ObjectUtils.notNull( PyUtil.as(initOrNew.myOriginalResolveResult.getElement(), PyClass.class), Objects.requireNonNull(initOrNewClass) ); final PyType initOrNewCallType = initOrNewMethod.getCallType(context, callSite); if (receiverClass != initOrNewClass) { if (initOrNewCallType instanceof PyTupleType) { final PyTupleType tupleType = (PyTupleType)initOrNewCallType; return new PyTupleType(receiverClass, tupleType.getElementTypes(), tupleType.isHomogeneous()); } if (initOrNewCallType instanceof PyCollectionType) { final List<PyType> elementTypes = ((PyCollectionType)initOrNewCallType).getElementTypes(); return new PyCollectionTypeImpl(receiverClass, false, elementTypes); } return new PyClassTypeImpl(receiverClass, false); } if (initOrNewCallType == null) { return PyUnionType.createWeakType(new PyClassTypeImpl(receiverClass, false)); } return null; } @NotNull private static Maybe<PyType> getSuperCallType(@NotNull PyCallExpression call, @NotNull TypeEvalContext context) { final PyExpression callee = call.getCallee(); if (callee instanceof PyReferenceExpression) { PsiElement must_be_super = ((PyReferenceExpression)callee).getReference().resolve(); if (must_be_super == PyBuiltinCache.getInstance(call).getClass(PyNames.SUPER)) { final PyArgumentList argumentList = call.getArgumentList(); if (argumentList != null) { final PyClass containingClass = PsiTreeUtil.getParentOfType(call, PyClass.class); PyExpression[] args = argumentList.getArguments(); if (containingClass != null && args.length > 1) { PyExpression first_arg = args[0]; if (first_arg instanceof PyReferenceExpression) { final PyReferenceExpression firstArgRef = (PyReferenceExpression)first_arg; final PyExpression qualifier = firstArgRef.getQualifier(); if (qualifier != null && PyNames.__CLASS__.equals(firstArgRef.getReferencedName())) { final PsiReference qRef = qualifier.getReference(); final PsiElement element = qRef == null ? null : qRef.resolve(); if (element instanceof PyParameter) { final PyParameterList parameterList = PsiTreeUtil.getParentOfType(element, PyParameterList.class); if (parameterList != null && element == parameterList.getParameters()[0]) { return new Maybe<>(getSuperCallTypeForArguments(context, containingClass, args[1])); } } } PsiElement possible_class = firstArgRef.getReference().resolve(); if (possible_class instanceof PyClass && ((PyClass)possible_class).isNewStyleClass(context)) { final PyClass first_class = (PyClass)possible_class; return new Maybe<>(getSuperCallTypeForArguments(context, first_class, args[1])); } } } else if ((call.getContainingFile() instanceof PyFile) && ((PyFile)call.getContainingFile()).getLanguageLevel().isPy3K() && (containingClass != null)) { return new Maybe<>(getSuperClassUnionType(containingClass, context)); } } } } return new Maybe<>(); } @Nullable private static PyType getSuperCallTypeForArguments(@NotNull TypeEvalContext context, @NotNull PyClass firstClass, @Nullable PyExpression second_arg) { // check 2nd argument, too; it should be an instance if (second_arg != null) { PyType second_type = context.getType(second_arg); if (second_type instanceof PyClassType) { // imitate isinstance(second_arg, possible_class) PyClass secondClass = ((PyClassType)second_type).getPyClass(); if (CompletionUtilCoreImpl.getOriginalOrSelf(firstClass) == secondClass) { return getSuperClassUnionType(firstClass, context); } if (secondClass.isSubclass(firstClass, context)) { final PyClass nextAfterFirstInMro = StreamEx .of(secondClass.getAncestorClasses(context)) .dropWhile(it -> it != firstClass) .skip(1) .findFirst() .orElse(null); if (nextAfterFirstInMro != null) { return new PyClassTypeImpl(nextAfterFirstInMro, false); } } } } return null; } @Nullable private static PyType getSuperClassUnionType(@NotNull PyClass pyClass, TypeEvalContext context) { // TODO: this is closer to being correct than simply taking first superclass type but still not entirely correct; // super can also delegate to sibling types // TODO handle __mro__ here final PyClass[] supers = pyClass.getSuperClasses(context); if (supers.length > 0) { if (supers.length == 1) { return new PyClassTypeImpl(supers[0], false); } List<PyType> superTypes = new ArrayList<>(); for (PyClass aSuper : supers) { superTypes.add(new PyClassTypeImpl(aSuper, false)); } return PyUnionType.union(superTypes); } return null; } /** * Gets implicit offset from the {@code callableType}, * should be used with the methods below since they specify correct offset value. * * @see PyCallExpression#multiResolveCalleeFunction(PyResolveContext) * @see PyCallExpression#multiResolveCallee(PyResolveContext) */ @NotNull public static PyCallExpression.PyArgumentsMapping mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull PyCallableType callableType, @NotNull TypeEvalContext context) { return mapArguments(callSite, callSite.getArguments(callableType.getCallable()), callableType, context); } @NotNull private static PyCallExpression.PyArgumentsMapping mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull List<PyExpression> arguments, @NotNull PyCallableType callableType, @NotNull TypeEvalContext context) { final List<PyCallableParameter> parameters = callableType.getParameters(context); if (parameters == null) return PyCallExpression.PyArgumentsMapping.empty(callSite); final int safeImplicitOffset = Math.min(callableType.getImplicitOffset(), parameters.size()); final List<PyCallableParameter> explicitParameters = parameters.subList(safeImplicitOffset, parameters.size()); final List<PyCallableParameter> implicitParameters = parameters.subList(0, safeImplicitOffset); final ArgumentMappingResults mappingResults = analyzeArguments(arguments, explicitParameters); return new PyCallExpression.PyArgumentsMapping(callSite, callableType, implicitParameters, mappingResults.getMappedParameters(), mappingResults.getUnmappedParameters(), mappingResults.getUnmappedArguments(), mappingResults.getParametersMappedToVariadicPositionalArguments(), mappingResults.getParametersMappedToVariadicKeywordArguments(), mappingResults.getMappedTupleParameters()); } @NotNull public static List<PyCallExpression.@NotNull PyArgumentsMapping> mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { final TypeEvalContext context = resolveContext.getTypeEvalContext(); return ContainerUtil.map(multiResolveCalleeFunction(callSite, resolveContext), type -> mapArguments(callSite, type, context)); } @NotNull private static List<@NotNull PyCallableType> multiResolveCalleeFunction(@NotNull PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { if (callSite instanceof PyCallExpression) { return ((PyCallExpression)callSite).multiResolveCallee(resolveContext); } else if (callSite instanceof PySubscriptionExpression) { return multiResolveCallee((PySubscriptionExpression)callSite, resolveContext); } else { final List<PyCallableType> results = new ArrayList<>(); for (PsiElement result : PyUtil.multiResolveTopPriority(callSite, resolveContext)) { if (result instanceof PyTypedElement) { final PyType resultType = resolveContext.getTypeEvalContext().getType((PyTypedElement)result); if (resultType instanceof PyCallableType) { results.add((PyCallableType)resultType); continue; } } return Collections.emptyList(); } return results; } } /** * Tries to infer implicit offset from the {@code callSite} and {@code callable}. * * @see PyCallExpressionHelper#mapArguments(PyCallSiteExpression, PyCallableType, TypeEvalContext) */ @NotNull public static PyCallExpression.PyArgumentsMapping mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull PyCallable callable, @NotNull TypeEvalContext context) { final PyCallableType callableType = PyUtil.as(context.getType(callable), PyCallableType.class); if (callableType == null) return PyCallExpression.PyArgumentsMapping.empty(callSite); final List<PyCallableParameter> parameters = callableType.getParameters(context); if (parameters == null) return PyCallExpression.PyArgumentsMapping.empty(callSite); final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); final List<PyExpression> arguments = callSite.getArguments(callable); final List<PyCallableParameter> explicitParameters = filterExplicitParameters(parameters, callable, callSite, resolveContext); final List<PyCallableParameter> implicitParameters = parameters.subList(0, parameters.size() - explicitParameters.size()); final ArgumentMappingResults mappingResults = analyzeArguments(arguments, explicitParameters); return new PyCallExpression.PyArgumentsMapping(callSite, callableType, implicitParameters, mappingResults.getMappedParameters(), mappingResults.getUnmappedParameters(), mappingResults.getUnmappedArguments(), mappingResults.getParametersMappedToVariadicPositionalArguments(), mappingResults.getParametersMappedToVariadicKeywordArguments(), mappingResults.getMappedTupleParameters()); } @NotNull public static List<PyExpression> getArgumentsMappedToPositionalContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return StreamEx.ofKeys(mapping, PyCallableParameter::isPositionalContainer).toList(); } @NotNull public static List<PyExpression> getArgumentsMappedToKeywordContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return StreamEx.ofKeys(mapping, PyCallableParameter::isKeywordContainer).toList(); } @NotNull public static Map<PyExpression, PyCallableParameter> getRegularMappedParameters(@NotNull Map<PyExpression, PyCallableParameter> mapping) { final Map<PyExpression, PyCallableParameter> result = new LinkedHashMap<>(); for (Map.Entry<PyExpression, PyCallableParameter> entry : mapping.entrySet()) { final PyExpression argument = entry.getKey(); final PyCallableParameter parameter = entry.getValue(); if (!parameter.isPositionalContainer() && !parameter.isKeywordContainer()) { result.put(argument, parameter); } } return result; } @Nullable public static PyCallableParameter getMappedPositionalContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return ContainerUtil.find(mapping.values(), p -> p.isPositionalContainer()); } @Nullable public static PyCallableParameter getMappedKeywordContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return ContainerUtil.find(mapping.values(), p -> p.isKeywordContainer()); } public static @NotNull List<PsiElement> resolveImplicitlyInvokedMethods(@NotNull PyClassType type, @Nullable PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { return type.isDefinition() ? resolveConstructors(type, callSite, resolveContext) : resolveDunderCall(type, callSite, resolveContext); } private static @NotNull List<@NotNull PyCallableType> changeToImplicitlyInvokedMethods(@NotNull PyClassType classType, @NotNull List<PsiElement> implicitlyInvokedMethods, @NotNull PyCallExpression call, @NotNull TypeEvalContext context) { final var cls = classType.getPyClass(); return StreamEx .of(implicitlyInvokedMethods) .map( it -> new ClarifiedResolveResult( new QualifiedRatedResolveResult(cls, Collections.emptyList(), RatedResolveResult.RATE_NORMAL, false), it, null, PyUtil.isInitOrNewMethod(it) ) ) .map(it -> toCallableType(call, it, context)) .nonNull() .toList(); } @NotNull private static List<PsiElement> resolveConstructors(@NotNull PyClassType type, @Nullable PyExpression location, @NotNull PyResolveContext resolveContext) { final var metaclassDunderCall = resolveMetaclassDunderCall(type, location, resolveContext); if (!metaclassDunderCall.isEmpty()) { return metaclassDunderCall; } final var initAndNew = type.getPyClass().multiFindInitOrNew(true, resolveContext.getTypeEvalContext()); return new SmartList<>(preferInitOverNew(initAndNew)); } @NotNull private static Collection<? extends PyFunction> preferInitOverNew(@NotNull List<PyFunction> initAndNew) { final MultiMap<String, PyFunction> functions = ContainerUtil.groupBy(initAndNew, PyFunction::getName); return functions.containsKey(PyNames.INIT) ? functions.get(PyNames.INIT) : functions.values(); } @NotNull private static List<PsiElement> resolveMetaclassDunderCall(@NotNull PyClassType type, @Nullable PyExpression location, @NotNull PyResolveContext resolveContext) { final var context = resolveContext.getTypeEvalContext(); final PyClassLikeType metaClassType = type.getMetaClassType(context, true); if (metaClassType == null) return Collections.emptyList(); final PyClassType typeType = PyBuiltinCache.getInstance(type.getPyClass()).getTypeType(); if (metaClassType == typeType) return Collections.emptyList(); final var results = resolveDunderCall(metaClassType, location, resolveContext); if (results.isEmpty()) return Collections.emptyList(); final Set<PsiElement> typeDunderCall = typeType == null ? Collections.emptySet() : new HashSet<>(resolveDunderCall(typeType, null, resolveContext)); return ContainerUtil.filter(results, it -> !typeDunderCall.contains(it) && !ParamHelper.isSelfArgsKwargsCallable(it, context)); } @NotNull private static List<PsiElement> resolveDunderCall(@NotNull PyClassLikeType type, @Nullable PyExpression location, @NotNull PyResolveContext resolveContext) { final var resolved = ContainerUtil.notNullize(type.resolveMember(PyNames.CALL, location, AccessDirection.READ, resolveContext)); return ResolveResultList.getElements(PyUtil.filterTopPriorityResults(resolved)); } @NotNull private static ArgumentMappingResults analyzeArguments(@NotNull List<PyExpression> arguments, @NotNull List<PyCallableParameter> parameters) { boolean positionalOnlyMode = ContainerUtil.exists(parameters, p -> p.getParameter() instanceof PySlashParameter); boolean seenSingleStar = false; boolean mappedVariadicArgumentsToParameters = false; final Map<PyExpression, PyCallableParameter> mappedParameters = new LinkedHashMap<>(); final List<PyCallableParameter> unmappedParameters = new ArrayList<>(); final List<PyExpression> unmappedArguments = new ArrayList<>(); final List<PyCallableParameter> parametersMappedToVariadicKeywordArguments = new ArrayList<>(); final List<PyCallableParameter> parametersMappedToVariadicPositionalArguments = new ArrayList<>(); final Map<PyExpression, PyCallableParameter> tupleMappedParameters = new LinkedHashMap<>(); final PositionalArgumentsAnalysisResults positionalResults = filterPositionalAndVariadicArguments(arguments); final List<PyKeywordArgument> keywordArguments = filterKeywordArguments(arguments); final List<PyExpression> variadicPositionalArguments = positionalResults.variadicPositionalArguments; final Set<PyExpression> positionalComponentsOfVariadicArguments = new LinkedHashSet<>(positionalResults.componentsOfVariadicPositionalArguments); final List<PyExpression> variadicKeywordArguments = filterVariadicKeywordArguments(arguments); final List<PyExpression> allPositionalArguments = positionalResults.allPositionalArguments; for (PyCallableParameter parameter : parameters) { final PyParameter psi = parameter.getParameter(); if (psi instanceof PyNamedParameter || psi == null) { final String parameterName = parameter.getName(); if (parameter.isPositionalContainer()) { for (PyExpression argument : allPositionalArguments) { if (argument != null) { mappedParameters.put(argument, parameter); } } if (variadicPositionalArguments.size() == 1) { mappedParameters.put(variadicPositionalArguments.get(0), parameter); } allPositionalArguments.clear(); variadicPositionalArguments.clear(); } else if (parameter.isKeywordContainer()) { for (PyKeywordArgument argument : keywordArguments) { mappedParameters.put(argument, parameter); } for (PyExpression variadicKeywordArg : variadicKeywordArguments) { mappedParameters.put(variadicKeywordArg, parameter); } keywordArguments.clear(); variadicKeywordArguments.clear(); } else if (seenSingleStar) { final PyExpression keywordArgument = removeKeywordArgument(keywordArguments, parameterName); if (keywordArgument != null) { mappedParameters.put(keywordArgument, parameter); } else if (variadicKeywordArguments.isEmpty()) { if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } else { parametersMappedToVariadicKeywordArguments.add(parameter); mappedVariadicArgumentsToParameters = true; } } else { if (positionalOnlyMode) { final PyExpression positionalArgument = next(allPositionalArguments); if (positionalArgument != null) { mappedParameters.put(positionalArgument, parameter); } else if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } else if (allPositionalArguments.isEmpty()) { final PyKeywordArgument keywordArgument = removeKeywordArgument(keywordArguments, parameterName); if (keywordArgument != null) { mappedParameters.put(keywordArgument, parameter); } else if (variadicPositionalArguments.isEmpty() && variadicKeywordArguments.isEmpty() && !parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } else { if (!variadicPositionalArguments.isEmpty()) { parametersMappedToVariadicPositionalArguments.add(parameter); } if (!variadicKeywordArguments.isEmpty()) { parametersMappedToVariadicKeywordArguments.add(parameter); } mappedVariadicArgumentsToParameters = true; } } else { final PyExpression positionalArgument = next(allPositionalArguments); if (positionalArgument != null) { mappedParameters.put(positionalArgument, parameter); if (positionalComponentsOfVariadicArguments.contains(positionalArgument)) { parametersMappedToVariadicPositionalArguments.add(parameter); } } else if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } } } else if (psi instanceof PyTupleParameter) { final PyExpression positionalArgument = next(allPositionalArguments); if (positionalArgument != null) { tupleMappedParameters.put(positionalArgument, parameter); final TupleMappingResults tupleMappingResults = mapComponentsOfTupleParameter(positionalArgument, (PyTupleParameter)psi); mappedParameters.putAll(tupleMappingResults.getParameters()); unmappedParameters.addAll(tupleMappingResults.getUnmappedParameters()); unmappedArguments.addAll(tupleMappingResults.getUnmappedArguments()); } else if (variadicPositionalArguments.isEmpty()) { if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } else { mappedVariadicArgumentsToParameters = true; } } else if (psi instanceof PySlashParameter) { positionalOnlyMode = false; } else if (psi instanceof PySingleStarParameter) { seenSingleStar = true; } else if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } if (mappedVariadicArgumentsToParameters) { variadicPositionalArguments.clear(); variadicKeywordArguments.clear(); } unmappedArguments.addAll(allPositionalArguments); unmappedArguments.addAll(keywordArguments); unmappedArguments.addAll(variadicPositionalArguments); unmappedArguments.addAll(variadicKeywordArguments); return new ArgumentMappingResults(mappedParameters, unmappedParameters, unmappedArguments, parametersMappedToVariadicPositionalArguments, parametersMappedToVariadicKeywordArguments, tupleMappedParameters); } @NotNull private static <E> List<E> forEveryScopeTakeOverloadsOtherwiseImplementations(@NotNull List<E> elements, @NotNull Function<? super E, PsiElement> mapper, @NotNull TypeEvalContext context) { if (!containsOverloadsAndImplementations(elements, mapper, context)) { return elements; } return StreamEx .of(elements) .groupingBy(element -> Optional.ofNullable(ScopeUtil.getScopeOwner(mapper.apply(element))), LinkedHashMap::new, Collectors.toList()) .values() .stream() .flatMap(oneScopeElements -> takeOverloadsOtherwiseImplementations(oneScopeElements, mapper, context)) .collect(Collectors.toList()); } private static <E> boolean containsOverloadsAndImplementations(@NotNull Collection<E> elements, @NotNull Function<? super E, PsiElement> mapper, @NotNull TypeEvalContext context) { boolean containsOverloads = false; boolean containsImplementations = false; for (E element : elements) { final PsiElement mapped = mapper.apply(element); if (mapped == null) continue; final boolean overload = PyiUtil.isOverload(mapped, context); containsOverloads |= overload; containsImplementations |= !overload; if (containsOverloads && containsImplementations) return true; } return false; } @NotNull private static <E> Stream<E> takeOverloadsOtherwiseImplementations(@NotNull List<E> elements, @NotNull Function<? super E, PsiElement> mapper, @NotNull TypeEvalContext context) { if (!containsOverloadsAndImplementations(elements, mapper, context)) { return elements.stream(); } return elements .stream() .filter( element -> { final PsiElement mapped = mapper.apply(element); return mapped != null && PyiUtil.isOverload(mapped, context); } ); } private static @NotNull <E> List<@NotNull E> dropNotMatchedOverloadsOrLeaveAsIs(@NotNull List<@NotNull E> elements, @NotNull Function<@NotNull ? super E, @Nullable PsiElement> mapper, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { final List<E> filtered = ContainerUtil.filter(elements, it -> !notMatchedOverload(mapper.apply(it), callSite, context)); return filtered.isEmpty() ? elements : filtered; } private static boolean notMatchedOverload(@Nullable PsiElement element, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { if (element == null || !PyiUtil.isOverload(element, context)) return false; final PyFunction overload = (PyFunction)element; final PyCallExpression.PyArgumentsMapping fullMapping = mapArguments(callSite, overload, context); if (!fullMapping.getUnmappedArguments().isEmpty() || !fullMapping.getUnmappedParameters().isEmpty()) { return true; } final PyExpression receiver = callSite.getReceiver(overload); final Map<PyExpression, PyCallableParameter> mappedExplicitParameters = fullMapping.getMappedParameters(); final Map<PyExpression, PyCallableParameter> allMappedParameters = new LinkedHashMap<>(); final PyCallableParameter firstImplicit = ContainerUtil.getFirstItem(fullMapping.getImplicitParameters()); if (receiver != null && firstImplicit != null) { allMappedParameters.put(receiver, firstImplicit); } allMappedParameters.putAll(mappedExplicitParameters); return PyTypeChecker.unifyGenericCall(receiver, allMappedParameters, context) == null; } private static class ArgumentMappingResults { @NotNull private final Map<PyExpression, PyCallableParameter> myMappedParameters; @NotNull private final List<PyCallableParameter> myUnmappedParameters; @NotNull private final List<PyExpression> myUnmappedArguments; @NotNull private final List<PyCallableParameter> myParametersMappedToVariadicPositionalArguments; @NotNull private final List<PyCallableParameter> myParametersMappedToVariadicKeywordArguments; @NotNull private final Map<PyExpression, PyCallableParameter> myMappedTupleParameters; ArgumentMappingResults(@NotNull Map<PyExpression, PyCallableParameter> mappedParameters, @NotNull List<PyCallableParameter> unmappedParameters, @NotNull List<PyExpression> unmappedArguments, @NotNull List<PyCallableParameter> parametersMappedToVariadicPositionalArguments, @NotNull List<PyCallableParameter> parametersMappedToVariadicKeywordArguments, @NotNull Map<PyExpression, PyCallableParameter> mappedTupleParameters) { myMappedParameters = mappedParameters; myUnmappedParameters = unmappedParameters; myUnmappedArguments = unmappedArguments; myParametersMappedToVariadicPositionalArguments = parametersMappedToVariadicPositionalArguments; myParametersMappedToVariadicKeywordArguments = parametersMappedToVariadicKeywordArguments; myMappedTupleParameters = mappedTupleParameters; } @NotNull public Map<PyExpression, PyCallableParameter> getMappedParameters() { return myMappedParameters; } @NotNull public List<PyCallableParameter> getUnmappedParameters() { return myUnmappedParameters; } @NotNull public List<PyExpression> getUnmappedArguments() { return myUnmappedArguments; } @NotNull public List<PyCallableParameter> getParametersMappedToVariadicPositionalArguments() { return myParametersMappedToVariadicPositionalArguments; } @NotNull public List<PyCallableParameter> getParametersMappedToVariadicKeywordArguments() { return myParametersMappedToVariadicKeywordArguments; } @NotNull public Map<PyExpression, PyCallableParameter> getMappedTupleParameters() { return myMappedTupleParameters; } } private static class TupleMappingResults { @NotNull private final Map<PyExpression, PyCallableParameter> myParameters; @NotNull private final List<PyCallableParameter> myUnmappedParameters; @NotNull private final List<PyExpression> myUnmappedArguments; TupleMappingResults(@NotNull Map<PyExpression, PyCallableParameter> mappedParameters, @NotNull List<PyCallableParameter> unmappedParameters, @NotNull List<PyExpression> unmappedArguments) { myParameters = mappedParameters; myUnmappedParameters = unmappedParameters; myUnmappedArguments = unmappedArguments; } @NotNull public Map<PyExpression, PyCallableParameter> getParameters() { return myParameters; } @NotNull public List<PyCallableParameter> getUnmappedParameters() { return myUnmappedParameters; } @NotNull public List<PyExpression> getUnmappedArguments() { return myUnmappedArguments; } } @NotNull private static TupleMappingResults mapComponentsOfTupleParameter(@Nullable PyExpression argument, @NotNull PyTupleParameter parameter) { final List<PyCallableParameter> unmappedParameters = new ArrayList<>(); final List<PyExpression> unmappedArguments = new ArrayList<>(); final Map<PyExpression, PyCallableParameter> mappedParameters = new LinkedHashMap<>(); argument = PyPsiUtils.flattenParens(argument); if (argument instanceof PySequenceExpression) { final PySequenceExpression sequenceExpr = (PySequenceExpression)argument; final PyExpression[] argumentComponents = sequenceExpr.getElements(); final PyParameter[] parameterComponents = parameter.getContents(); for (int i = 0; i < parameterComponents.length; i++) { final PyParameter param = parameterComponents[i]; if (i < argumentComponents.length) { final PyExpression arg = argumentComponents[i]; if (arg != null) { if (param instanceof PyNamedParameter) { mappedParameters.put(arg, PyCallableParameterImpl.psi(param)); } else if (param instanceof PyTupleParameter) { final TupleMappingResults nestedResults = mapComponentsOfTupleParameter(arg, (PyTupleParameter)param); mappedParameters.putAll(nestedResults.getParameters()); unmappedParameters.addAll(nestedResults.getUnmappedParameters()); unmappedArguments.addAll(nestedResults.getUnmappedArguments()); } else { unmappedArguments.add(arg); } } else { unmappedParameters.add(PyCallableParameterImpl.psi(param)); } } else { unmappedParameters.add(PyCallableParameterImpl.psi(param)); } } if (argumentComponents.length > parameterComponents.length) { for (int i = parameterComponents.length; i < argumentComponents.length; i++) { final PyExpression arg = argumentComponents[i]; if (arg != null) { unmappedArguments.add(arg); } } } } return new TupleMappingResults(mappedParameters, unmappedParameters, unmappedArguments); } @Nullable private static PyKeywordArgument removeKeywordArgument(@NotNull List<PyKeywordArgument> arguments, @Nullable String name) { PyKeywordArgument result = null; for (PyKeywordArgument argument : arguments) { final String keyword = argument.getKeyword(); if (keyword != null && keyword.equals(name)) { result = argument; break; } } if (result != null) { arguments.remove(result); } return result; } @NotNull private static List<PyKeywordArgument> filterKeywordArguments(@NotNull List<PyExpression> arguments) { final List<PyKeywordArgument> results = new ArrayList<>(); for (PyExpression argument : arguments) { if (argument instanceof PyKeywordArgument) { results.add((PyKeywordArgument)argument); } } return results; } private static class PositionalArgumentsAnalysisResults { @NotNull private final List<PyExpression> allPositionalArguments; @NotNull private final List<PyExpression> componentsOfVariadicPositionalArguments; @NotNull private final List<PyExpression> variadicPositionalArguments; PositionalArgumentsAnalysisResults(@NotNull List<PyExpression> allPositionalArguments, @NotNull List<PyExpression> componentsOfVariadicPositionalArguments, @NotNull List<PyExpression> variadicPositionalArguments) { this.allPositionalArguments = allPositionalArguments; this.componentsOfVariadicPositionalArguments = componentsOfVariadicPositionalArguments; this.variadicPositionalArguments = variadicPositionalArguments; } } @NotNull private static PositionalArgumentsAnalysisResults filterPositionalAndVariadicArguments(@NotNull List<PyExpression> arguments) { final List<PyExpression> variadicArguments = new ArrayList<>(); final List<PyExpression> allPositionalArguments = new ArrayList<>(); final List<PyExpression> componentsOfVariadicPositionalArguments = new ArrayList<>(); boolean seenVariadicPositionalArgument = false; boolean seenVariadicKeywordArgument = false; boolean seenKeywordArgument = false; for (PyExpression argument : arguments) { if (argument instanceof PyStarArgument) { if (((PyStarArgument)argument).isKeyword()) { seenVariadicKeywordArgument = true; } else { seenVariadicPositionalArgument = true; final PsiElement expr = PyPsiUtils.flattenParens(PsiTreeUtil.getChildOfType(argument, PyExpression.class)); if (expr instanceof PySequenceExpression) { final PySequenceExpression sequenceExpr = (PySequenceExpression)expr; final List<PyExpression> elements = Arrays.asList(sequenceExpr.getElements()); allPositionalArguments.addAll(elements); componentsOfVariadicPositionalArguments.addAll(elements); } else { variadicArguments.add(argument); } } } else if (argument instanceof PyKeywordArgument) { seenKeywordArgument = true; } else { if (seenKeywordArgument || seenVariadicKeywordArgument || seenVariadicPositionalArgument && LanguageLevel.forElement(argument).isOlderThan(LanguageLevel.PYTHON35)) { continue; } allPositionalArguments.add(argument); } } return new PositionalArgumentsAnalysisResults(allPositionalArguments, componentsOfVariadicPositionalArguments, variadicArguments); } @NotNull private static List<PyExpression> filterVariadicKeywordArguments(@NotNull List<PyExpression> arguments) { final List<PyExpression> results = new ArrayList<>(); for (PyExpression argument : arguments) { if (argument != null && isVariadicKeywordArgument(argument)) { results.add(argument); } } return results; } public static boolean isVariadicKeywordArgument(@NotNull PyExpression argument) { return argument instanceof PyStarArgument && ((PyStarArgument)argument).isKeyword(); } public static boolean isVariadicPositionalArgument(@NotNull PyExpression argument) { return argument instanceof PyStarArgument && !((PyStarArgument)argument).isKeyword(); } @Nullable private static <T> T next(@NotNull List<T> list) { return list.isEmpty() ? null : list.remove(0); } @NotNull private static List<PyCallableParameter> filterExplicitParameters(@NotNull List<PyCallableParameter> parameters, @Nullable PyCallable callable, @NotNull PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { final int implicitOffset; if (callSite instanceof PyCallExpression) { final PyCallExpression callExpr = (PyCallExpression)callSite; final PyExpression callee = callExpr.getCallee(); if (callee instanceof PyReferenceExpression && callable instanceof PyFunction) { implicitOffset = getImplicitArgumentCount((PyReferenceExpression)callee, (PyFunction)callable, resolveContext); } else { implicitOffset = 0; } } else { implicitOffset = 1; } return parameters.subList(Math.min(implicitOffset, parameters.size()), parameters.size()); } public static boolean canQualifyAnImplicitName(@NotNull PyExpression qualifier) { if (qualifier instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)qualifier).getCallee(); if (callee instanceof PyReferenceExpression && PyNames.SUPER.equals(callee.getName())) { final PsiElement target = ((PyReferenceExpression)callee).getReference().resolve(); if (target != null && PyBuiltinCache.getInstance(qualifier).isBuiltin(target)) return false; // super() of unresolved type } } return true; } private static class ClarifiedResolveResult { @NotNull private final QualifiedRatedResolveResult myOriginalResolveResult; @NotNull private final PsiElement myClarifiedResolved; @Nullable private final PyFunction.Modifier myWrappedModifier; private final boolean myIsConstructor; ClarifiedResolveResult(@NotNull QualifiedRatedResolveResult originalResolveResult, @NotNull PsiElement clarifiedResolved, @Nullable PyFunction.Modifier wrappedModifier, boolean isConstructor) { myOriginalResolveResult = originalResolveResult; myClarifiedResolved = clarifiedResolved; myWrappedModifier = wrappedModifier; myIsConstructor = isConstructor; } } }
python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.psi.impl; import com.intellij.codeInsight.completion.CompletionUtilCoreImpl; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveResult; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.jetbrains.python.PyNames; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.resolve.*; import com.jetbrains.python.psi.types.*; import com.jetbrains.python.pyi.PyiUtil; import com.jetbrains.python.toolbox.Maybe; import one.util.streamex.StreamEx; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Functions common to different implementors of PyCallExpression, with different base classes. * User: dcheryasov */ public final class PyCallExpressionHelper { private PyCallExpressionHelper() { } /** * Tries to interpret a call as a call to built-in {@code classmethod} or {@code staticmethod}. * * @param redefiningCall the possible call, generally a result of chasing a chain of assignments * @return a pair of wrapper name and wrapped function; for {@code staticmethod(foo)} it would be ("staticmethod", foo). */ @Nullable public static Pair<String, PyFunction> interpretAsModifierWrappingCall(PyCallExpression redefiningCall) { PyExpression redefining_callee = redefiningCall.getCallee(); if (redefiningCall.isCalleeText(PyNames.CLASSMETHOD, PyNames.STATICMETHOD)) { final PyReferenceExpression referenceExpr = (PyReferenceExpression)redefining_callee; if (referenceExpr != null) { final String refName = referenceExpr.getReferencedName(); if ((PyNames.CLASSMETHOD.equals(refName) || PyNames.STATICMETHOD.equals(refName)) && PyBuiltinCache.isInBuiltins(referenceExpr)) { // yes, really a case of "foo = classmethod(foo)" PyArgumentList argumentList = redefiningCall.getArgumentList(); if (argumentList != null) { // really can't be any other way PyExpression[] args = argumentList.getArguments(); if (args.length == 1) { PyExpression possible_original_ref = args[0]; if (possible_original_ref instanceof PyReferenceExpression) { PsiElement original = ((PyReferenceExpression)possible_original_ref).getReference().resolve(); if (original instanceof PyFunction) { // pinned down the original; replace our resolved callee with it and add flags. return Pair.create(refName, (PyFunction)original); } } } } } } } return null; } @Nullable public static PyClass resolveCalleeClass(PyCallExpression us) { PyExpression callee = us.getCallee(); PsiElement resolved; QualifiedResolveResult resolveResult; if (callee instanceof PyReferenceExpression) { // dereference PyReferenceExpression ref = (PyReferenceExpression)callee; resolveResult = ref.followAssignmentsChain(PyResolveContext.defaultContext()); resolved = resolveResult.getElement(); } else { resolved = callee; } // analyze if (resolved instanceof PyClass) { return (PyClass)resolved; } else if (resolved instanceof PyFunction) { final PyFunction pyFunction = (PyFunction)resolved; return pyFunction.getContainingClass(); } return null; } /** * This method should not be called directly, * please obtain its result via {@link TypeEvalContext#getType} with {@code call.getCallee()} as an argument. */ static @Nullable PyType getCalleeType(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext, @SuppressWarnings("unused") @NotNull TypeEvalContext.Key key) { final List<PyType> callableTypes = new ArrayList<>(); final TypeEvalContext context = resolveContext.getTypeEvalContext(); final List<QualifiedRatedResolveResult> results = PyUtil.filterTopPriorityResults( forEveryScopeTakeOverloadsOtherwiseImplementations( multiResolveCallee(call.getCallee(), resolveContext), RatedResolveResult::getElement, context ).collect(Collectors.toList()) ); for (QualifiedRatedResolveResult resolveResult : results) { final PsiElement element = resolveResult.getElement(); if (element != null) { final PyType typeFromProviders = Ref.deref(PyReferenceExpressionImpl.getReferenceTypeFromProviders(element, resolveContext.getTypeEvalContext(), call)); if (typeFromProviders instanceof PyCallableType) { callableTypes.add(typeFromProviders); continue; } } for (ClarifiedResolveResult clarifiedResolveResult : clarifyResolveResult(call, resolveResult, resolveContext)) { ContainerUtil.addIfNotNull(callableTypes, toCallableType(call, clarifiedResolveResult, context)); } } return PyUnionType.union(callableTypes); } @Nullable public static PyExpression getReceiver(@NotNull PyCallExpression call, @Nullable PyCallable resolvedCallee) { if (resolvedCallee instanceof PyFunction) { final PyFunction function = (PyFunction)resolvedCallee; if (!PyNames.NEW.equals(function.getName()) && function.getModifier() == PyFunction.Modifier.STATICMETHOD) { return null; } } final PyExpression callee = call.getCallee(); if (callee != null && isImplicitlyInvokedMethod(resolvedCallee) && !Objects.equals(resolvedCallee.getName(), callee.getName())) { return callee; } if (callee instanceof PyQualifiedExpression) { return ((PyQualifiedExpression)callee).getQualifier(); } return null; } @Contract("null -> false") private static boolean isImplicitlyInvokedMethod(@Nullable PyCallable resolvedCallee) { if (PyUtil.isInitOrNewMethod(resolvedCallee)) return true; if (resolvedCallee instanceof PyFunction) { final PyFunction function = (PyFunction)resolvedCallee; return PyNames.CALL.equals(function.getName()) && function.getContainingClass() != null; } return false; } /** * It is not the same as {@link PyCallExpressionHelper#getCalleeType} since * this method returns callable types that would be actually called, the mentioned method returns type of underlying callee. * Compare: * <pre> * {@code * class A: * pass * a = A() * b = a() # callee type is A, resolved callee is A.__call__ * } * </pre> */ @NotNull static List<@NotNull PyCallableType> multiResolveCallee(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext) { return PyUtil.getParameterizedCachedValue( call, resolveContext, it -> ContainerUtil.concat(getExplicitResolveResults(call, it), getImplicitResolveResults(call, it)) ); } private static @NotNull List<@NotNull PyCallableType> multiResolveCallee(@NotNull PySubscriptionExpression subscription, @NotNull PyResolveContext resolveContext) { final TypeEvalContext context = resolveContext.getTypeEvalContext(); final List<ResolveResult> results = PyUtil.filterTopPriorityResults( forEveryScopeTakeOverloadsOtherwiseImplementations( Arrays.asList(subscription.getReference(resolveContext).multiResolve(false)), ResolveResult::getElement, context ).collect(Collectors.toList()) ); return selectCallableTypes(ResolveResultList.getElements(results), context); } @NotNull private static List<@NotNull PyCallableType> getExplicitResolveResults(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext) { final var callee = call.getCallee(); if (callee == null) return Collections.emptyList(); final TypeEvalContext context = resolveContext.getTypeEvalContext(); final var calleeType = context.getType(callee); final var provided = StreamEx .of(PyTypeProvider.EP_NAME.getExtensionList()) .map(e -> e.prepareCalleeTypeForCall(calleeType, call, context)) .nonNull() .toList(); if (!provided.isEmpty()) return ContainerUtil.mapNotNull(provided, Ref::deref); final List<PyCallableType> result = new ArrayList<>(); for (PyType type : PyTypeUtil.toStream(calleeType)) { if (type instanceof PyClassType) { final var classType = (PyClassType)type; final var implicitlyInvokedMethods = resolveImplicitlyInvokedMethods(classType, call, resolveContext); if (implicitlyInvokedMethods.isEmpty()) { result.add(classType); } else { result.addAll(changeToImplicitlyInvokedMethods(classType, implicitlyInvokedMethods, call, context)); } } else if (type instanceof PyCallableType) { result.add((PyCallableType)type); } } return result; } @NotNull private static List<@NotNull PyCallableType> getImplicitResolveResults(@NotNull PyCallExpression call, @NotNull PyResolveContext resolveContext) { if (!resolveContext.allowImplicits()) return Collections.emptyList(); final PyExpression callee = call.getCallee(); final TypeEvalContext context = resolveContext.getTypeEvalContext(); if (callee instanceof PyQualifiedExpression) { final PyQualifiedExpression qualifiedCallee = (PyQualifiedExpression)callee; final String referencedName = qualifiedCallee.getReferencedName(); if (referencedName == null) return Collections.emptyList(); final PyExpression qualifier = qualifiedCallee.getQualifier(); if (qualifier == null || !canQualifyAnImplicitName(qualifier)) return Collections.emptyList(); final PyType qualifierType = context.getType(qualifier); if (PyTypeChecker.isUnknown(qualifierType, context) || qualifierType instanceof PyStructuralType && ((PyStructuralType)qualifierType).isInferredFromUsages()) { final ResolveResultList resolveResults = new ResolveResultList(); PyResolveUtil.addImplicitResolveResults(referencedName, resolveResults, qualifiedCallee); return selectCallableTypes(ResolveResultList.getElements(resolveResults), context); } } return Collections.emptyList(); } @NotNull private static List<@NotNull PyCallableType> selectCallableTypes(@NotNull List<PsiElement> resolveResults, @NotNull TypeEvalContext context) { return StreamEx .of(resolveResults) .select(PyTypedElement.class) .map(context::getType) .flatMap(PyTypeUtil::toStream) .select(PyCallableType.class) .toList(); } @NotNull private static List<QualifiedRatedResolveResult> multiResolveCallee(@Nullable PyExpression callee, @NotNull PyResolveContext resolveContext) { if (callee instanceof PyReferenceExpression) { return ((PyReferenceExpression)callee).multiFollowAssignmentsChain(resolveContext); } else if (callee instanceof PyLambdaExpression) { return Collections.singletonList( new QualifiedRatedResolveResult(callee, Collections.emptyList(), RatedResolveResult.RATE_NORMAL, false) ); } return Collections.emptyList(); } @NotNull private static List<ClarifiedResolveResult> clarifyResolveResult(@NotNull PyCallExpression call, @NotNull QualifiedRatedResolveResult resolveResult, @NotNull PyResolveContext resolveContext) { final PsiElement resolved = resolveResult.getElement(); if (resolved instanceof PyCallExpression) { // foo = classmethod(foo) final PyCallExpression resolvedCall = (PyCallExpression)resolved; final Pair<String, PyFunction> wrapperInfo = interpretAsModifierWrappingCall(resolvedCall); if (wrapperInfo != null) { final String wrapperName = wrapperInfo.getFirst(); final PyFunction.Modifier wrappedModifier = PyNames.CLASSMETHOD.equals(wrapperName) ? PyFunction.Modifier.CLASSMETHOD : PyNames.STATICMETHOD.equals(wrapperName) ? PyFunction.Modifier.STATICMETHOD : null; final ClarifiedResolveResult result = new ClarifiedResolveResult(resolveResult, wrapperInfo.getSecond(), wrappedModifier, false); return Collections.singletonList(result); } } else if (resolved instanceof PyFunction) { final PyFunction function = (PyFunction)resolved; final TypeEvalContext context = resolveContext.getTypeEvalContext(); if (function.getProperty() != null && isQualifiedByInstance(function, resolveResult.getQualifiers(), context)) { final PyType type = context.getReturnType(function); return type instanceof PyFunctionType ? Collections.singletonList(new ClarifiedResolveResult(resolveResult, ((PyFunctionType)type).getCallable(), null, false)) : Collections.emptyList(); } } return resolved != null ? Collections.singletonList(new ClarifiedResolveResult(resolveResult, resolved, null, resolved instanceof PyClass)) : Collections.emptyList(); } private static @Nullable PyCallableType toCallableType(@NotNull PyCallSiteExpression callSite, @NotNull ClarifiedResolveResult resolveResult, @NotNull TypeEvalContext context) { final PsiElement clarifiedResolved = resolveResult.myClarifiedResolved; if (!(clarifiedResolved instanceof PyTypedElement)) return null; final PyCallableType callableType = PyUtil.as(context.getType((PyTypedElement)clarifiedResolved), PyCallableType.class); if (callableType == null) return null; if (clarifiedResolved instanceof PyCallable) { final PyCallable callable = (PyCallable)clarifiedResolved; final PyFunction.Modifier originalModifier = callable instanceof PyFunction ? ((PyFunction)callable).getModifier() : null; final PyFunction.Modifier resolvedModifier = ObjectUtils.chooseNotNull(originalModifier, resolveResult.myWrappedModifier); final boolean isConstructorCall = resolveResult.myIsConstructor; final List<PyExpression> qualifiers = resolveResult.myOriginalResolveResult.getQualifiers(); final boolean isByInstance = isConstructorCall || isQualifiedByInstance(callable, qualifiers, context) || callable instanceof PyBoundFunction; final PyExpression lastQualifier = ContainerUtil.getLastItem(qualifiers); final boolean isByClass = lastQualifier != null && isQualifiedByClass(callable, lastQualifier, context); final int resolvedImplicitOffset = getImplicitArgumentCount(callable, resolvedModifier, isConstructorCall, isByInstance, isByClass); final PyType clarifiedConstructorCallType = PyUtil.isInitOrNewMethod(clarifiedResolved) ? clarifyConstructorCallType(resolveResult, callSite, context) : null; if (callableType.getModifier() == resolvedModifier && callableType.getImplicitOffset() == resolvedImplicitOffset && clarifiedConstructorCallType == null) { return callableType; } return new PyCallableTypeImpl( callableType.getParameters(context), ObjectUtils.chooseNotNull(clarifiedConstructorCallType, callableType.getCallType(context, callSite)), callable, resolvedModifier, Math.max(0, resolvedImplicitOffset)); // wrong source can trigger strange behaviour } return callableType; } /** * Calls the {@link #getImplicitArgumentCount(PyCallable, PyFunction.Modifier, boolean, boolean, boolean)} full version} * with null flags and with isByInstance inferred directly from call site (won't work with reassigned bound methods). * * @param callReference the call site, where arguments are given. * @param function resolved method which is being called; plain functions are OK but make little sense. * @return a non-negative number of parameters that are implicit to this call. */ public static int getImplicitArgumentCount(@NotNull final PyReferenceExpression callReference, @NotNull PyFunction function, @NotNull PyResolveContext resolveContext) { QualifiedResolveResult followed = callReference.followAssignmentsChain(resolveContext); final List<PyExpression> qualifiers = followed.getQualifiers(); final PyExpression firstQualifier = ContainerUtil.getFirstItem(qualifiers); boolean isByInstance = isQualifiedByInstance(function, qualifiers, resolveContext.getTypeEvalContext()); String name = callReference.getName(); final boolean isConstructorCall = PyUtil.isInitOrNewMethod(function) && (!callReference.isQualified() || !PyNames.INIT.equals(name) && !PyNames.NEW.equals(name)); boolean isByClass = firstQualifier != null && isQualifiedByClass(function, firstQualifier, resolveContext.getTypeEvalContext()); return getImplicitArgumentCount(function, function.getModifier(), isConstructorCall, isByInstance, isByClass); } /** * Finds how many arguments are implicit in a given call. * * @param callable resolved method which is being called; non-methods immediately return 0. * @param isByInstance true if the call is known to be by instance (not by class). * @return a non-negative number of parameters that are implicit to this call. E.g. for a typical method call 1 is returned * because one parameter ('self') is implicit. */ private static int getImplicitArgumentCount( PyCallable callable, PyFunction.Modifier modifier, boolean isConstructorCall, boolean isByInstance, boolean isByClass ) { int implicit_offset = 0; boolean firstIsArgsOrKwargs = false; final PyParameter[] parameters = callable.getParameterList().getParameters(); if (parameters.length > 0) { final PyParameter first = parameters[0]; final PyNamedParameter named = first.getAsNamed(); if (named != null && (named.isPositionalContainer() || named.isKeywordContainer())) { firstIsArgsOrKwargs = true; } } if (!firstIsArgsOrKwargs && (isByInstance || isConstructorCall)) { implicit_offset += 1; } PyFunction method = callable.asMethod(); if (method == null) return implicit_offset; if (PyUtil.isNewMethod(method)) { return isConstructorCall ? 1 : 0; } if (!isByInstance && !isByClass && PyUtil.isInitMethod(method)) { return 1; } // decorators? if (modifier == PyFunction.Modifier.STATICMETHOD) { if (isByInstance && implicit_offset > 0) implicit_offset -= 1; // might have marked it as implicit 'self' } else if (modifier == PyFunction.Modifier.CLASSMETHOD) { if (!isByInstance) implicit_offset += 1; // Both Foo.method() and foo.method() have implicit the first arg } return implicit_offset; } private static boolean isQualifiedByInstance(@Nullable PyCallable resolved, @NotNull List<PyExpression> qualifiers, @NotNull TypeEvalContext context) { PyDocStringOwner owner = PsiTreeUtil.getStubOrPsiParentOfType(resolved, PyDocStringOwner.class); if (!(owner instanceof PyClass)) { return false; } // true = call by instance if (qualifiers.isEmpty()) { return true; // unqualified + method = implicit constructor call } for (PyExpression qualifier : qualifiers) { if (qualifier != null && isQualifiedByInstance(resolved, qualifier, context)) { return true; } } return false; } private static boolean isQualifiedByInstance(@Nullable PyCallable resolved, @NotNull PyExpression qualifier, @NotNull TypeEvalContext context) { if (isQualifiedByClass(resolved, qualifier, context)) { return false; } final PyType qualifierType = context.getType(qualifier); if (qualifierType != null) { // TODO: handle UnionType if (qualifierType instanceof PyModuleType) return false; // qualified by module, not instance. } return true; // NOTE. best guess: unknown qualifier is more probably an instance. } private static boolean isQualifiedByClass(@Nullable PyCallable resolved, @NotNull PyExpression qualifier, @NotNull TypeEvalContext context) { final PyType qualifierType = context.getType(qualifier); if (qualifierType instanceof PyClassType) { final PyClassType qualifierClassType = (PyClassType)qualifierType; return qualifierClassType.isDefinition() && belongsToSpecifiedClassHierarchy(resolved, qualifierClassType.getPyClass(), context); } else if (qualifierType instanceof PyClassLikeType) { return ((PyClassLikeType)qualifierType).isDefinition(); // Any definition means callable is classmethod } else if (qualifierType instanceof PyUnionType) { final Collection<PyType> members = ((PyUnionType)qualifierType).getMembers(); if (ContainerUtil.all(members, type -> type == null || type instanceof PyNoneType || type instanceof PyClassType)) { return StreamEx .of(members) .select(PyClassType.class) .filter(type -> belongsToSpecifiedClassHierarchy(resolved, type.getPyClass(), context)) .allMatch(PyClassType::isDefinition); } } return false; } private static boolean belongsToSpecifiedClassHierarchy(@Nullable PsiElement element, @NotNull PyClass cls, @NotNull TypeEvalContext context) { final PyClass parent = PsiTreeUtil.getStubOrPsiParentOfType(element, PyClass.class); return parent != null && (cls.isSubclass(parent, context) || parent.isSubclass(cls, context)); } /** * This method should not be called directly, * please obtain its result via {@link TypeEvalContext#getType} with {@code call} as an argument. */ static @Nullable PyType getCallType(@NotNull PyCallExpression call, @NotNull TypeEvalContext context, @SuppressWarnings("unused") @NotNull TypeEvalContext.Key key) { PyExpression callee = call.getCallee(); if (callee instanceof PyReferenceExpression) { // hardwired special cases if (PyNames.SUPER.equals(callee.getText())) { final Maybe<PyType> superCallType = getSuperCallType(call, context); if (superCallType.isDefined()) { return superCallType.value(); } } if ("type".equals(callee.getText())) { final PyExpression[] args = call.getArguments(); if (args.length == 1) { final PyExpression arg = args[0]; final PyType argType = context.getType(arg); if (argType instanceof PyClassType) { final PyClassType classType = (PyClassType)argType; if (!classType.isDefinition()) { final PyClass cls = classType.getPyClass(); return context.getType(cls); } } else { return null; } } } } final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); return getCallType(multiResolveCallee(call, resolveContext), call, context); } /** * This method should not be called directly, * please obtain its result via {@link TypeEvalContext#getType} with {@code subscription} as an argument. */ static @Nullable PyType getCallType(@NotNull PySubscriptionExpression subscription, @NotNull TypeEvalContext context, @SuppressWarnings("unused") @NotNull TypeEvalContext.Key key) { final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); return getCallType(multiResolveCallee(subscription, resolveContext), subscription, context); } private static @Nullable PyType getCallType(@NotNull List<@NotNull PyCallableType> callableTypes, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { return PyUnionType.union( ContainerUtil.map( dropNotMatchedOverloadsOrLeaveAsIs( ContainerUtil.filter(callableTypes, PyCallableType::isCallable), PyCallableType::getCallable, callSite, context ), it -> it.getCallType(context, callSite) ) ); } private static @Nullable PyType clarifyConstructorCallType(@NotNull ClarifiedResolveResult initOrNew, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { final PyFunction initOrNewMethod = (PyFunction)initOrNew.myClarifiedResolved; final PyClass initOrNewClass = initOrNewMethod.getContainingClass(); final PyClass receiverClass = ObjectUtils.notNull( PyUtil.as(initOrNew.myOriginalResolveResult.getElement(), PyClass.class), Objects.requireNonNull(initOrNewClass) ); final PyType initOrNewCallType = initOrNewMethod.getCallType(context, callSite); if (receiverClass != initOrNewClass) { if (initOrNewCallType instanceof PyTupleType) { final PyTupleType tupleType = (PyTupleType)initOrNewCallType; return new PyTupleType(receiverClass, tupleType.getElementTypes(), tupleType.isHomogeneous()); } if (initOrNewCallType instanceof PyCollectionType) { final List<PyType> elementTypes = ((PyCollectionType)initOrNewCallType).getElementTypes(); return new PyCollectionTypeImpl(receiverClass, false, elementTypes); } return new PyClassTypeImpl(receiverClass, false); } if (initOrNewCallType == null) { return PyUnionType.createWeakType(new PyClassTypeImpl(receiverClass, false)); } return null; } @NotNull private static Maybe<PyType> getSuperCallType(@NotNull PyCallExpression call, @NotNull TypeEvalContext context) { final PyExpression callee = call.getCallee(); if (callee instanceof PyReferenceExpression) { PsiElement must_be_super = ((PyReferenceExpression)callee).getReference().resolve(); if (must_be_super == PyBuiltinCache.getInstance(call).getClass(PyNames.SUPER)) { final PyArgumentList argumentList = call.getArgumentList(); if (argumentList != null) { final PyClass containingClass = PsiTreeUtil.getParentOfType(call, PyClass.class); PyExpression[] args = argumentList.getArguments(); if (containingClass != null && args.length > 1) { PyExpression first_arg = args[0]; if (first_arg instanceof PyReferenceExpression) { final PyReferenceExpression firstArgRef = (PyReferenceExpression)first_arg; final PyExpression qualifier = firstArgRef.getQualifier(); if (qualifier != null && PyNames.__CLASS__.equals(firstArgRef.getReferencedName())) { final PsiReference qRef = qualifier.getReference(); final PsiElement element = qRef == null ? null : qRef.resolve(); if (element instanceof PyParameter) { final PyParameterList parameterList = PsiTreeUtil.getParentOfType(element, PyParameterList.class); if (parameterList != null && element == parameterList.getParameters()[0]) { return new Maybe<>(getSuperCallTypeForArguments(context, containingClass, args[1])); } } } PsiElement possible_class = firstArgRef.getReference().resolve(); if (possible_class instanceof PyClass && ((PyClass)possible_class).isNewStyleClass(context)) { final PyClass first_class = (PyClass)possible_class; return new Maybe<>(getSuperCallTypeForArguments(context, first_class, args[1])); } } } else if ((call.getContainingFile() instanceof PyFile) && ((PyFile)call.getContainingFile()).getLanguageLevel().isPy3K() && (containingClass != null)) { return new Maybe<>(getSuperClassUnionType(containingClass, context)); } } } } return new Maybe<>(); } @Nullable private static PyType getSuperCallTypeForArguments(@NotNull TypeEvalContext context, @NotNull PyClass firstClass, @Nullable PyExpression second_arg) { // check 2nd argument, too; it should be an instance if (second_arg != null) { PyType second_type = context.getType(second_arg); if (second_type instanceof PyClassType) { // imitate isinstance(second_arg, possible_class) PyClass secondClass = ((PyClassType)second_type).getPyClass(); if (CompletionUtilCoreImpl.getOriginalOrSelf(firstClass) == secondClass) { return getSuperClassUnionType(firstClass, context); } if (secondClass.isSubclass(firstClass, context)) { final PyClass nextAfterFirstInMro = StreamEx .of(secondClass.getAncestorClasses(context)) .dropWhile(it -> it != firstClass) .skip(1) .findFirst() .orElse(null); if (nextAfterFirstInMro != null) { return new PyClassTypeImpl(nextAfterFirstInMro, false); } } } } return null; } @Nullable private static PyType getSuperClassUnionType(@NotNull PyClass pyClass, TypeEvalContext context) { // TODO: this is closer to being correct than simply taking first superclass type but still not entirely correct; // super can also delegate to sibling types // TODO handle __mro__ here final PyClass[] supers = pyClass.getSuperClasses(context); if (supers.length > 0) { if (supers.length == 1) { return new PyClassTypeImpl(supers[0], false); } List<PyType> superTypes = new ArrayList<>(); for (PyClass aSuper : supers) { superTypes.add(new PyClassTypeImpl(aSuper, false)); } return PyUnionType.union(superTypes); } return null; } /** * Gets implicit offset from the {@code callableType}, * should be used with the methods below since they specify correct offset value. * * @see PyCallExpression#multiResolveCalleeFunction(PyResolveContext) * @see PyCallExpression#multiResolveCallee(PyResolveContext) */ @NotNull public static PyCallExpression.PyArgumentsMapping mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull PyCallableType callableType, @NotNull TypeEvalContext context) { return mapArguments(callSite, callSite.getArguments(callableType.getCallable()), callableType, context); } @NotNull private static PyCallExpression.PyArgumentsMapping mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull List<PyExpression> arguments, @NotNull PyCallableType callableType, @NotNull TypeEvalContext context) { final List<PyCallableParameter> parameters = callableType.getParameters(context); if (parameters == null) return PyCallExpression.PyArgumentsMapping.empty(callSite); final int safeImplicitOffset = Math.min(callableType.getImplicitOffset(), parameters.size()); final List<PyCallableParameter> explicitParameters = parameters.subList(safeImplicitOffset, parameters.size()); final List<PyCallableParameter> implicitParameters = parameters.subList(0, safeImplicitOffset); final ArgumentMappingResults mappingResults = analyzeArguments(arguments, explicitParameters); return new PyCallExpression.PyArgumentsMapping(callSite, callableType, implicitParameters, mappingResults.getMappedParameters(), mappingResults.getUnmappedParameters(), mappingResults.getUnmappedArguments(), mappingResults.getParametersMappedToVariadicPositionalArguments(), mappingResults.getParametersMappedToVariadicKeywordArguments(), mappingResults.getMappedTupleParameters()); } @NotNull public static List<PyCallExpression.@NotNull PyArgumentsMapping> mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { final TypeEvalContext context = resolveContext.getTypeEvalContext(); return ContainerUtil.map(multiResolveCalleeFunction(callSite, resolveContext), type -> mapArguments(callSite, type, context)); } @NotNull private static List<@NotNull PyCallableType> multiResolveCalleeFunction(@NotNull PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { if (callSite instanceof PyCallExpression) { return ((PyCallExpression)callSite).multiResolveCallee(resolveContext); } else if (callSite instanceof PySubscriptionExpression) { return multiResolveCallee((PySubscriptionExpression)callSite, resolveContext); } else { final List<PyCallableType> results = new ArrayList<>(); for (PsiElement result : PyUtil.multiResolveTopPriority(callSite, resolveContext)) { if (result instanceof PyTypedElement) { final PyType resultType = resolveContext.getTypeEvalContext().getType((PyTypedElement)result); if (resultType instanceof PyCallableType) { results.add((PyCallableType)resultType); continue; } } return Collections.emptyList(); } return results; } } /** * Tries to infer implicit offset from the {@code callSite} and {@code callable}. * * @see PyCallExpressionHelper#mapArguments(PyCallSiteExpression, PyCallableType, TypeEvalContext) */ @NotNull public static PyCallExpression.PyArgumentsMapping mapArguments(@NotNull PyCallSiteExpression callSite, @NotNull PyCallable callable, @NotNull TypeEvalContext context) { final PyCallableType callableType = PyUtil.as(context.getType(callable), PyCallableType.class); if (callableType == null) return PyCallExpression.PyArgumentsMapping.empty(callSite); final List<PyCallableParameter> parameters = callableType.getParameters(context); if (parameters == null) return PyCallExpression.PyArgumentsMapping.empty(callSite); final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context); final List<PyExpression> arguments = callSite.getArguments(callable); final List<PyCallableParameter> explicitParameters = filterExplicitParameters(parameters, callable, callSite, resolveContext); final List<PyCallableParameter> implicitParameters = parameters.subList(0, parameters.size() - explicitParameters.size()); final ArgumentMappingResults mappingResults = analyzeArguments(arguments, explicitParameters); return new PyCallExpression.PyArgumentsMapping(callSite, callableType, implicitParameters, mappingResults.getMappedParameters(), mappingResults.getUnmappedParameters(), mappingResults.getUnmappedArguments(), mappingResults.getParametersMappedToVariadicPositionalArguments(), mappingResults.getParametersMappedToVariadicKeywordArguments(), mappingResults.getMappedTupleParameters()); } @NotNull public static List<PyExpression> getArgumentsMappedToPositionalContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return StreamEx.ofKeys(mapping, PyCallableParameter::isPositionalContainer).toList(); } @NotNull public static List<PyExpression> getArgumentsMappedToKeywordContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return StreamEx.ofKeys(mapping, PyCallableParameter::isKeywordContainer).toList(); } @NotNull public static Map<PyExpression, PyCallableParameter> getRegularMappedParameters(@NotNull Map<PyExpression, PyCallableParameter> mapping) { final Map<PyExpression, PyCallableParameter> result = new LinkedHashMap<>(); for (Map.Entry<PyExpression, PyCallableParameter> entry : mapping.entrySet()) { final PyExpression argument = entry.getKey(); final PyCallableParameter parameter = entry.getValue(); if (!parameter.isPositionalContainer() && !parameter.isKeywordContainer()) { result.put(argument, parameter); } } return result; } @Nullable public static PyCallableParameter getMappedPositionalContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return ContainerUtil.find(mapping.values(), p -> p.isPositionalContainer()); } @Nullable public static PyCallableParameter getMappedKeywordContainer(@NotNull Map<PyExpression, PyCallableParameter> mapping) { return ContainerUtil.find(mapping.values(), p -> p.isKeywordContainer()); } public static @NotNull List<PsiElement> resolveImplicitlyInvokedMethods(@NotNull PyClassType type, @Nullable PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { return type.isDefinition() ? resolveConstructors(type, callSite, resolveContext) : resolveDunderCall(type, callSite, resolveContext); } private static @NotNull List<@NotNull PyCallableType> changeToImplicitlyInvokedMethods(@NotNull PyClassType classType, @NotNull List<PsiElement> implicitlyInvokedMethods, @NotNull PyCallExpression call, @NotNull TypeEvalContext context) { final var cls = classType.getPyClass(); return StreamEx .of(implicitlyInvokedMethods) .map( it -> new ClarifiedResolveResult( new QualifiedRatedResolveResult(cls, Collections.emptyList(), RatedResolveResult.RATE_NORMAL, false), it, null, PyUtil.isInitOrNewMethod(it) ) ) .map(it -> toCallableType(call, it, context)) .nonNull() .toList(); } @NotNull private static List<PsiElement> resolveConstructors(@NotNull PyClassType type, @Nullable PyExpression location, @NotNull PyResolveContext resolveContext) { final var metaclassDunderCall = resolveMetaclassDunderCall(type, location, resolveContext); if (!metaclassDunderCall.isEmpty()) { return metaclassDunderCall; } final var initAndNew = type.getPyClass().multiFindInitOrNew(true, resolveContext.getTypeEvalContext()); return new SmartList<>(preferInitOverNew(initAndNew)); } @NotNull private static Collection<? extends PyFunction> preferInitOverNew(@NotNull List<PyFunction> initAndNew) { final MultiMap<String, PyFunction> functions = ContainerUtil.groupBy(initAndNew, PyFunction::getName); return functions.containsKey(PyNames.INIT) ? functions.get(PyNames.INIT) : functions.values(); } @NotNull private static List<PsiElement> resolveMetaclassDunderCall(@NotNull PyClassType type, @Nullable PyExpression location, @NotNull PyResolveContext resolveContext) { final var context = resolveContext.getTypeEvalContext(); final PyClassLikeType metaClassType = type.getMetaClassType(context, true); if (metaClassType == null) return Collections.emptyList(); final PyClassType typeType = PyBuiltinCache.getInstance(type.getPyClass()).getTypeType(); if (metaClassType == typeType) return Collections.emptyList(); final var results = resolveDunderCall(metaClassType, location, resolveContext); if (results.isEmpty()) return Collections.emptyList(); final Set<PsiElement> typeDunderCall = typeType == null ? Collections.emptySet() : new HashSet<>(resolveDunderCall(typeType, null, resolveContext)); return ContainerUtil.filter(results, it -> !typeDunderCall.contains(it) && !ParamHelper.isSelfArgsKwargsCallable(it, context)); } @NotNull private static List<PsiElement> resolveDunderCall(@NotNull PyClassLikeType type, @Nullable PyExpression location, @NotNull PyResolveContext resolveContext) { final var resolved = ContainerUtil.notNullize(type.resolveMember(PyNames.CALL, location, AccessDirection.READ, resolveContext)); return ResolveResultList.getElements(PyUtil.filterTopPriorityResults(resolved)); } @NotNull private static ArgumentMappingResults analyzeArguments(@NotNull List<PyExpression> arguments, @NotNull List<PyCallableParameter> parameters) { boolean positionalOnlyMode = ContainerUtil.exists(parameters, p -> p.getParameter() instanceof PySlashParameter); boolean seenSingleStar = false; boolean mappedVariadicArgumentsToParameters = false; final Map<PyExpression, PyCallableParameter> mappedParameters = new LinkedHashMap<>(); final List<PyCallableParameter> unmappedParameters = new ArrayList<>(); final List<PyExpression> unmappedArguments = new ArrayList<>(); final List<PyCallableParameter> parametersMappedToVariadicKeywordArguments = new ArrayList<>(); final List<PyCallableParameter> parametersMappedToVariadicPositionalArguments = new ArrayList<>(); final Map<PyExpression, PyCallableParameter> tupleMappedParameters = new LinkedHashMap<>(); final PositionalArgumentsAnalysisResults positionalResults = filterPositionalAndVariadicArguments(arguments); final List<PyKeywordArgument> keywordArguments = filterKeywordArguments(arguments); final List<PyExpression> variadicPositionalArguments = positionalResults.variadicPositionalArguments; final Set<PyExpression> positionalComponentsOfVariadicArguments = new LinkedHashSet<>(positionalResults.componentsOfVariadicPositionalArguments); final List<PyExpression> variadicKeywordArguments = filterVariadicKeywordArguments(arguments); final List<PyExpression> allPositionalArguments = positionalResults.allPositionalArguments; for (PyCallableParameter parameter : parameters) { final PyParameter psi = parameter.getParameter(); if (psi instanceof PyNamedParameter || psi == null) { final String parameterName = parameter.getName(); if (parameter.isPositionalContainer()) { for (PyExpression argument : allPositionalArguments) { if (argument != null) { mappedParameters.put(argument, parameter); } } if (variadicPositionalArguments.size() == 1) { mappedParameters.put(variadicPositionalArguments.get(0), parameter); } allPositionalArguments.clear(); variadicPositionalArguments.clear(); } else if (parameter.isKeywordContainer()) { for (PyKeywordArgument argument : keywordArguments) { mappedParameters.put(argument, parameter); } for (PyExpression variadicKeywordArg : variadicKeywordArguments) { mappedParameters.put(variadicKeywordArg, parameter); } keywordArguments.clear(); variadicKeywordArguments.clear(); } else if (seenSingleStar) { final PyExpression keywordArgument = removeKeywordArgument(keywordArguments, parameterName); if (keywordArgument != null) { mappedParameters.put(keywordArgument, parameter); } else if (variadicKeywordArguments.isEmpty()) { if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } else { parametersMappedToVariadicKeywordArguments.add(parameter); mappedVariadicArgumentsToParameters = true; } } else { if (positionalOnlyMode) { final PyExpression positionalArgument = next(allPositionalArguments); if (positionalArgument != null) { mappedParameters.put(positionalArgument, parameter); } else if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } else if (allPositionalArguments.isEmpty()) { final PyKeywordArgument keywordArgument = removeKeywordArgument(keywordArguments, parameterName); if (keywordArgument != null) { mappedParameters.put(keywordArgument, parameter); } else if (variadicPositionalArguments.isEmpty() && variadicKeywordArguments.isEmpty() && !parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } else { if (!variadicPositionalArguments.isEmpty()) { parametersMappedToVariadicPositionalArguments.add(parameter); } if (!variadicKeywordArguments.isEmpty()) { parametersMappedToVariadicKeywordArguments.add(parameter); } mappedVariadicArgumentsToParameters = true; } } else { final PyExpression positionalArgument = next(allPositionalArguments); if (positionalArgument != null) { mappedParameters.put(positionalArgument, parameter); if (positionalComponentsOfVariadicArguments.contains(positionalArgument)) { parametersMappedToVariadicPositionalArguments.add(parameter); } } else if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } } } else if (psi instanceof PyTupleParameter) { final PyExpression positionalArgument = next(allPositionalArguments); if (positionalArgument != null) { tupleMappedParameters.put(positionalArgument, parameter); final TupleMappingResults tupleMappingResults = mapComponentsOfTupleParameter(positionalArgument, (PyTupleParameter)psi); mappedParameters.putAll(tupleMappingResults.getParameters()); unmappedParameters.addAll(tupleMappingResults.getUnmappedParameters()); unmappedArguments.addAll(tupleMappingResults.getUnmappedArguments()); } else if (variadicPositionalArguments.isEmpty()) { if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } else { mappedVariadicArgumentsToParameters = true; } } else if (psi instanceof PySlashParameter) { positionalOnlyMode = false; } else if (psi instanceof PySingleStarParameter) { seenSingleStar = true; } else if (!parameter.hasDefaultValue()) { unmappedParameters.add(parameter); } } if (mappedVariadicArgumentsToParameters) { variadicPositionalArguments.clear(); variadicKeywordArguments.clear(); } unmappedArguments.addAll(allPositionalArguments); unmappedArguments.addAll(keywordArguments); unmappedArguments.addAll(variadicPositionalArguments); unmappedArguments.addAll(variadicKeywordArguments); return new ArgumentMappingResults(mappedParameters, unmappedParameters, unmappedArguments, parametersMappedToVariadicPositionalArguments, parametersMappedToVariadicKeywordArguments, tupleMappedParameters); } @NotNull private static <E> Stream<E> forEveryScopeTakeOverloadsOtherwiseImplementations(@NotNull Collection<E> elements, @NotNull Function<? super E, PsiElement> mapper, @NotNull TypeEvalContext context) { if (!containsOverloadsAndImplementations(elements, mapper, context)) { return elements.stream(); } return StreamEx .of(elements) .groupingBy(element -> Optional.ofNullable(ScopeUtil.getScopeOwner(mapper.apply(element))), LinkedHashMap::new, Collectors.toList()) .values() .stream() .flatMap(oneScopeElements -> takeOverloadsOtherwiseImplementations(oneScopeElements, mapper, context)); } private static <E> boolean containsOverloadsAndImplementations(@NotNull Collection<E> elements, @NotNull Function<? super E, PsiElement> mapper, @NotNull TypeEvalContext context) { boolean containsOverloads = false; boolean containsImplementations = false; for (E element : elements) { final PsiElement mapped = mapper.apply(element); if (mapped == null) continue; final boolean overload = PyiUtil.isOverload(mapped, context); containsOverloads |= overload; containsImplementations |= !overload; if (containsOverloads && containsImplementations) return true; } return false; } @NotNull private static <E> Stream<E> takeOverloadsOtherwiseImplementations(@NotNull List<E> elements, @NotNull Function<? super E, PsiElement> mapper, @NotNull TypeEvalContext context) { if (!containsOverloadsAndImplementations(elements, mapper, context)) { return elements.stream(); } return elements .stream() .filter( element -> { final PsiElement mapped = mapper.apply(element); return mapped != null && PyiUtil.isOverload(mapped, context); } ); } private static @NotNull <E> List<@NotNull E> dropNotMatchedOverloadsOrLeaveAsIs(@NotNull List<@NotNull E> elements, @NotNull Function<@NotNull ? super E, @Nullable PsiElement> mapper, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { final List<E> filtered = ContainerUtil.filter(elements, it -> !notMatchedOverload(mapper.apply(it), callSite, context)); return filtered.isEmpty() ? elements : filtered; } private static boolean notMatchedOverload(@Nullable PsiElement element, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { if (element == null || !PyiUtil.isOverload(element, context)) return false; final PyFunction overload = (PyFunction)element; final PyCallExpression.PyArgumentsMapping fullMapping = mapArguments(callSite, overload, context); if (!fullMapping.getUnmappedArguments().isEmpty() || !fullMapping.getUnmappedParameters().isEmpty()) { return true; } final PyExpression receiver = callSite.getReceiver(overload); final Map<PyExpression, PyCallableParameter> mappedExplicitParameters = fullMapping.getMappedParameters(); final Map<PyExpression, PyCallableParameter> allMappedParameters = new LinkedHashMap<>(); final PyCallableParameter firstImplicit = ContainerUtil.getFirstItem(fullMapping.getImplicitParameters()); if (receiver != null && firstImplicit != null) { allMappedParameters.put(receiver, firstImplicit); } allMappedParameters.putAll(mappedExplicitParameters); return PyTypeChecker.unifyGenericCall(receiver, allMappedParameters, context) == null; } private static class ArgumentMappingResults { @NotNull private final Map<PyExpression, PyCallableParameter> myMappedParameters; @NotNull private final List<PyCallableParameter> myUnmappedParameters; @NotNull private final List<PyExpression> myUnmappedArguments; @NotNull private final List<PyCallableParameter> myParametersMappedToVariadicPositionalArguments; @NotNull private final List<PyCallableParameter> myParametersMappedToVariadicKeywordArguments; @NotNull private final Map<PyExpression, PyCallableParameter> myMappedTupleParameters; ArgumentMappingResults(@NotNull Map<PyExpression, PyCallableParameter> mappedParameters, @NotNull List<PyCallableParameter> unmappedParameters, @NotNull List<PyExpression> unmappedArguments, @NotNull List<PyCallableParameter> parametersMappedToVariadicPositionalArguments, @NotNull List<PyCallableParameter> parametersMappedToVariadicKeywordArguments, @NotNull Map<PyExpression, PyCallableParameter> mappedTupleParameters) { myMappedParameters = mappedParameters; myUnmappedParameters = unmappedParameters; myUnmappedArguments = unmappedArguments; myParametersMappedToVariadicPositionalArguments = parametersMappedToVariadicPositionalArguments; myParametersMappedToVariadicKeywordArguments = parametersMappedToVariadicKeywordArguments; myMappedTupleParameters = mappedTupleParameters; } @NotNull public Map<PyExpression, PyCallableParameter> getMappedParameters() { return myMappedParameters; } @NotNull public List<PyCallableParameter> getUnmappedParameters() { return myUnmappedParameters; } @NotNull public List<PyExpression> getUnmappedArguments() { return myUnmappedArguments; } @NotNull public List<PyCallableParameter> getParametersMappedToVariadicPositionalArguments() { return myParametersMappedToVariadicPositionalArguments; } @NotNull public List<PyCallableParameter> getParametersMappedToVariadicKeywordArguments() { return myParametersMappedToVariadicKeywordArguments; } @NotNull public Map<PyExpression, PyCallableParameter> getMappedTupleParameters() { return myMappedTupleParameters; } } private static class TupleMappingResults { @NotNull private final Map<PyExpression, PyCallableParameter> myParameters; @NotNull private final List<PyCallableParameter> myUnmappedParameters; @NotNull private final List<PyExpression> myUnmappedArguments; TupleMappingResults(@NotNull Map<PyExpression, PyCallableParameter> mappedParameters, @NotNull List<PyCallableParameter> unmappedParameters, @NotNull List<PyExpression> unmappedArguments) { myParameters = mappedParameters; myUnmappedParameters = unmappedParameters; myUnmappedArguments = unmappedArguments; } @NotNull public Map<PyExpression, PyCallableParameter> getParameters() { return myParameters; } @NotNull public List<PyCallableParameter> getUnmappedParameters() { return myUnmappedParameters; } @NotNull public List<PyExpression> getUnmappedArguments() { return myUnmappedArguments; } } @NotNull private static TupleMappingResults mapComponentsOfTupleParameter(@Nullable PyExpression argument, @NotNull PyTupleParameter parameter) { final List<PyCallableParameter> unmappedParameters = new ArrayList<>(); final List<PyExpression> unmappedArguments = new ArrayList<>(); final Map<PyExpression, PyCallableParameter> mappedParameters = new LinkedHashMap<>(); argument = PyPsiUtils.flattenParens(argument); if (argument instanceof PySequenceExpression) { final PySequenceExpression sequenceExpr = (PySequenceExpression)argument; final PyExpression[] argumentComponents = sequenceExpr.getElements(); final PyParameter[] parameterComponents = parameter.getContents(); for (int i = 0; i < parameterComponents.length; i++) { final PyParameter param = parameterComponents[i]; if (i < argumentComponents.length) { final PyExpression arg = argumentComponents[i]; if (arg != null) { if (param instanceof PyNamedParameter) { mappedParameters.put(arg, PyCallableParameterImpl.psi(param)); } else if (param instanceof PyTupleParameter) { final TupleMappingResults nestedResults = mapComponentsOfTupleParameter(arg, (PyTupleParameter)param); mappedParameters.putAll(nestedResults.getParameters()); unmappedParameters.addAll(nestedResults.getUnmappedParameters()); unmappedArguments.addAll(nestedResults.getUnmappedArguments()); } else { unmappedArguments.add(arg); } } else { unmappedParameters.add(PyCallableParameterImpl.psi(param)); } } else { unmappedParameters.add(PyCallableParameterImpl.psi(param)); } } if (argumentComponents.length > parameterComponents.length) { for (int i = parameterComponents.length; i < argumentComponents.length; i++) { final PyExpression arg = argumentComponents[i]; if (arg != null) { unmappedArguments.add(arg); } } } } return new TupleMappingResults(mappedParameters, unmappedParameters, unmappedArguments); } @Nullable private static PyKeywordArgument removeKeywordArgument(@NotNull List<PyKeywordArgument> arguments, @Nullable String name) { PyKeywordArgument result = null; for (PyKeywordArgument argument : arguments) { final String keyword = argument.getKeyword(); if (keyword != null && keyword.equals(name)) { result = argument; break; } } if (result != null) { arguments.remove(result); } return result; } @NotNull private static List<PyKeywordArgument> filterKeywordArguments(@NotNull List<PyExpression> arguments) { final List<PyKeywordArgument> results = new ArrayList<>(); for (PyExpression argument : arguments) { if (argument instanceof PyKeywordArgument) { results.add((PyKeywordArgument)argument); } } return results; } private static class PositionalArgumentsAnalysisResults { @NotNull private final List<PyExpression> allPositionalArguments; @NotNull private final List<PyExpression> componentsOfVariadicPositionalArguments; @NotNull private final List<PyExpression> variadicPositionalArguments; PositionalArgumentsAnalysisResults(@NotNull List<PyExpression> allPositionalArguments, @NotNull List<PyExpression> componentsOfVariadicPositionalArguments, @NotNull List<PyExpression> variadicPositionalArguments) { this.allPositionalArguments = allPositionalArguments; this.componentsOfVariadicPositionalArguments = componentsOfVariadicPositionalArguments; this.variadicPositionalArguments = variadicPositionalArguments; } } @NotNull private static PositionalArgumentsAnalysisResults filterPositionalAndVariadicArguments(@NotNull List<PyExpression> arguments) { final List<PyExpression> variadicArguments = new ArrayList<>(); final List<PyExpression> allPositionalArguments = new ArrayList<>(); final List<PyExpression> componentsOfVariadicPositionalArguments = new ArrayList<>(); boolean seenVariadicPositionalArgument = false; boolean seenVariadicKeywordArgument = false; boolean seenKeywordArgument = false; for (PyExpression argument : arguments) { if (argument instanceof PyStarArgument) { if (((PyStarArgument)argument).isKeyword()) { seenVariadicKeywordArgument = true; } else { seenVariadicPositionalArgument = true; final PsiElement expr = PyPsiUtils.flattenParens(PsiTreeUtil.getChildOfType(argument, PyExpression.class)); if (expr instanceof PySequenceExpression) { final PySequenceExpression sequenceExpr = (PySequenceExpression)expr; final List<PyExpression> elements = Arrays.asList(sequenceExpr.getElements()); allPositionalArguments.addAll(elements); componentsOfVariadicPositionalArguments.addAll(elements); } else { variadicArguments.add(argument); } } } else if (argument instanceof PyKeywordArgument) { seenKeywordArgument = true; } else { if (seenKeywordArgument || seenVariadicKeywordArgument || seenVariadicPositionalArgument && LanguageLevel.forElement(argument).isOlderThan(LanguageLevel.PYTHON35)) { continue; } allPositionalArguments.add(argument); } } return new PositionalArgumentsAnalysisResults(allPositionalArguments, componentsOfVariadicPositionalArguments, variadicArguments); } @NotNull private static List<PyExpression> filterVariadicKeywordArguments(@NotNull List<PyExpression> arguments) { final List<PyExpression> results = new ArrayList<>(); for (PyExpression argument : arguments) { if (argument != null && isVariadicKeywordArgument(argument)) { results.add(argument); } } return results; } public static boolean isVariadicKeywordArgument(@NotNull PyExpression argument) { return argument instanceof PyStarArgument && ((PyStarArgument)argument).isKeyword(); } public static boolean isVariadicPositionalArgument(@NotNull PyExpression argument) { return argument instanceof PyStarArgument && !((PyStarArgument)argument).isKeyword(); } @Nullable private static <T> T next(@NotNull List<T> list) { return list.isEmpty() ? null : list.remove(0); } @NotNull private static List<PyCallableParameter> filterExplicitParameters(@NotNull List<PyCallableParameter> parameters, @Nullable PyCallable callable, @NotNull PyCallSiteExpression callSite, @NotNull PyResolveContext resolveContext) { final int implicitOffset; if (callSite instanceof PyCallExpression) { final PyCallExpression callExpr = (PyCallExpression)callSite; final PyExpression callee = callExpr.getCallee(); if (callee instanceof PyReferenceExpression && callable instanceof PyFunction) { implicitOffset = getImplicitArgumentCount((PyReferenceExpression)callee, (PyFunction)callable, resolveContext); } else { implicitOffset = 0; } } else { implicitOffset = 1; } return parameters.subList(Math.min(implicitOffset, parameters.size()), parameters.size()); } public static boolean canQualifyAnImplicitName(@NotNull PyExpression qualifier) { if (qualifier instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)qualifier).getCallee(); if (callee instanceof PyReferenceExpression && PyNames.SUPER.equals(callee.getName())) { final PsiElement target = ((PyReferenceExpression)callee).getReference().resolve(); if (target != null && PyBuiltinCache.getInstance(qualifier).isBuiltin(target)) return false; // super() of unresolved type } } return true; } private static class ClarifiedResolveResult { @NotNull private final QualifiedRatedResolveResult myOriginalResolveResult; @NotNull private final PsiElement myClarifiedResolved; @Nullable private final PyFunction.Modifier myWrappedModifier; private final boolean myIsConstructor; ClarifiedResolveResult(@NotNull QualifiedRatedResolveResult originalResolveResult, @NotNull PsiElement clarifiedResolved, @Nullable PyFunction.Modifier wrappedModifier, boolean isConstructor) { myOriginalResolveResult = originalResolveResult; myClarifiedResolved = clarifiedResolved; myWrappedModifier = wrappedModifier; myIsConstructor = isConstructor; } } }
Use forEveryScopeTakeOverloadsOtherwiseImplementations in implicitly invoked methods and implicit results processing Return list in forEveryScopeTakeOverloadsOtherwiseImplementations GitOrigin-RevId: c3dddea449c393ce81e7e3e5bf00dc99ba94b443
python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.java
Use forEveryScopeTakeOverloadsOtherwiseImplementations in implicitly invoked methods and implicit results processing
<ide><path>ython/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.java <ide> multiResolveCallee(call.getCallee(), resolveContext), <ide> RatedResolveResult::getElement, <ide> context <del> ).collect(Collectors.toList()) <add> ) <ide> ); <ide> <ide> for (QualifiedRatedResolveResult resolveResult : results) { <ide> } <ide> } <ide> <del> for (ClarifiedResolveResult clarifiedResolveResult : clarifyResolveResult(call, resolveResult, resolveContext)) { <add> for (ClarifiedResolveResult clarifiedResolveResult : clarifyResolveResult(resolveResult, resolveContext)) { <ide> ContainerUtil.addIfNotNull(callableTypes, toCallableType(call, clarifiedResolveResult, context)); <ide> } <ide> } <ide> Arrays.asList(subscription.getReference(resolveContext).multiResolve(false)), <ide> ResolveResult::getElement, <ide> context <del> ).collect(Collectors.toList()) <add> ) <ide> ); <ide> <ide> return selectCallableTypes(ResolveResultList.getElements(results), context); <ide> if (type instanceof PyClassType) { <ide> final var classType = (PyClassType)type; <ide> <del> final var implicitlyInvokedMethods = resolveImplicitlyInvokedMethods(classType, call, resolveContext); <add> final var implicitlyInvokedMethods = forEveryScopeTakeOverloadsOtherwiseImplementations( <add> resolveImplicitlyInvokedMethods(classType, call, resolveContext), <add> Function.identity(), <add> context <add> ); <add> <ide> if (implicitlyInvokedMethods.isEmpty()) { <ide> result.add(classType); <ide> } <ide> final ResolveResultList resolveResults = new ResolveResultList(); <ide> PyResolveUtil.addImplicitResolveResults(referencedName, resolveResults, qualifiedCallee); <ide> <del> return selectCallableTypes(ResolveResultList.getElements(resolveResults), context); <add> return selectCallableTypes( <add> forEveryScopeTakeOverloadsOtherwiseImplementations(ResolveResultList.getElements(resolveResults), Function.identity(), context), <add> context <add> ); <ide> } <ide> } <ide> <ide> } <ide> <ide> @NotNull <del> private static List<ClarifiedResolveResult> clarifyResolveResult(@NotNull PyCallExpression call, <del> @NotNull QualifiedRatedResolveResult resolveResult, <add> private static List<ClarifiedResolveResult> clarifyResolveResult(@NotNull QualifiedRatedResolveResult resolveResult, <ide> @NotNull PyResolveContext resolveContext) { <ide> final PsiElement resolved = resolveResult.getElement(); <ide> <ide> } <ide> <ide> @NotNull <del> private static <E> Stream<E> forEveryScopeTakeOverloadsOtherwiseImplementations(@NotNull Collection<E> elements, <del> @NotNull Function<? super E, PsiElement> mapper, <del> @NotNull TypeEvalContext context) { <add> private static <E> List<E> forEveryScopeTakeOverloadsOtherwiseImplementations(@NotNull List<E> elements, <add> @NotNull Function<? super E, PsiElement> mapper, <add> @NotNull TypeEvalContext context) { <ide> if (!containsOverloadsAndImplementations(elements, mapper, context)) { <del> return elements.stream(); <add> return elements; <ide> } <ide> <ide> return StreamEx <ide> .groupingBy(element -> Optional.ofNullable(ScopeUtil.getScopeOwner(mapper.apply(element))), LinkedHashMap::new, Collectors.toList()) <ide> .values() <ide> .stream() <del> .flatMap(oneScopeElements -> takeOverloadsOtherwiseImplementations(oneScopeElements, mapper, context)); <add> .flatMap(oneScopeElements -> takeOverloadsOtherwiseImplementations(oneScopeElements, mapper, context)) <add> .collect(Collectors.toList()); <ide> } <ide> <ide> private static <E> boolean containsOverloadsAndImplementations(@NotNull Collection<E> elements,
Java
apache-2.0
e612ffc98866a78cd9cb9d1ea61d66f37d5e6ff4
0
hobinyoon/apache-cassandra-3.0.5-src,hobinyoon/apache-cassandra-3.0.5-src,hobinyoon/apache-cassandra-3.0.5-src
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.cql3.statements; import java.nio.ByteBuffer; import java.util.*; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.acorn.AcornAttributes; import org.apache.cassandra.acorn.AttrPopMonitor; import org.apache.cassandra.auth.Permission; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.*; import org.apache.cassandra.cql3.functions.Function; import org.apache.cassandra.cql3.restrictions.StatementRestrictions; import org.apache.cassandra.cql3.selection.RawSelector; import org.apache.cassandra.cql3.selection.Selection; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.*; import org.apache.cassandra.db.marshal.CollectionType; import org.apache.cassandra.db.marshal.CompositeType; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.db.marshal.SetType; import org.apache.cassandra.db.partitions.PartitionIterator; import org.apache.cassandra.db.rows.ComplexColumnData; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.db.rows.RowIterator; import org.apache.cassandra.db.view.View; import org.apache.cassandra.dht.AbstractBounds; import org.apache.cassandra.exceptions.*; import org.apache.cassandra.index.SecondaryIndexManager; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.ClientWarn; import org.apache.cassandra.service.QueryState; import org.apache.cassandra.service.pager.AbstractQueryPager; import org.apache.cassandra.service.pager.PagingState; import org.apache.cassandra.service.pager.QueryPager; import org.apache.cassandra.thrift.ThriftValidation; import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.cassandra.transport.Server; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse; import static org.apache.cassandra.cql3.statements.RequestValidations.checkNotNull; import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue; import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest; import static org.apache.cassandra.utils.ByteBufferUtil.UNSET_BYTE_BUFFER; /** * Encapsulates a completely parsed SELECT query, including the target * column family, expression, result count, and ordering clause. * * A number of public methods here are only used internally. However, * many of these are made accessible for the benefit of custom * QueryHandler implementations, so before reducing their accessibility * due consideration should be given. */ public class SelectStatement implements CQLStatement { private static final Logger logger = LoggerFactory.getLogger(SelectStatement.class); private static final int DEFAULT_COUNT_PAGE_SIZE = 10000; private final int boundTerms; public final CFMetaData cfm; public final Parameters parameters; private final Selection selection; private final Term limit; private final StatementRestrictions restrictions; private final boolean isReversed; /** * The comparator used to orders results when multiple keys are selected (using IN). */ private final Comparator<List<ByteBuffer>> orderingComparator; private final ColumnFilter queriedColumns; // Used by forSelection below private static final Parameters defaultParameters = new Parameters(Collections.<ColumnIdentifier.Raw, Boolean>emptyMap(), false, false, false); public SelectStatement(CFMetaData cfm, int boundTerms, Parameters parameters, Selection selection, StatementRestrictions restrictions, boolean isReversed, Comparator<List<ByteBuffer>> orderingComparator, Term limit) { this.cfm = cfm; this.boundTerms = boundTerms; this.selection = selection; this.restrictions = restrictions; this.isReversed = isReversed; this.orderingComparator = orderingComparator; this.parameters = parameters; this.limit = limit; this.queriedColumns = gatherQueriedColumns(); } public Iterable<Function> getFunctions() { return Iterables.concat(selection.getFunctions(), restrictions.getFunctions(), limit != null ? limit.getFunctions() : Collections.<Function>emptySet()); } // Note that the queried columns internally is different from the one selected by the // user as it also include any column for which we have a restriction on. private ColumnFilter gatherQueriedColumns() { if (selection.isWildcard()) return ColumnFilter.all(cfm); ColumnFilter.Builder builder = ColumnFilter.allColumnsBuilder(cfm); // Adds all selected columns for (ColumnDefinition def : selection.getColumns()) if (!def.isPrimaryKeyColumn()) builder.add(def); // as well as any restricted column (so we can actually apply the restriction) builder.addAll(restrictions.nonPKRestrictedColumns(true)); return builder.build(); } // Creates a simple select based on the given selection. // Note that the results select statement should not be used for actual queries, but only for processing already // queried data through processColumnFamily. static SelectStatement forSelection(CFMetaData cfm, Selection selection) { return new SelectStatement(cfm, 0, defaultParameters, selection, StatementRestrictions.empty(StatementType.SELECT, cfm), false, null, null); } public ResultSet.ResultMetadata getResultMetadata() { return selection.getResultMetadata(parameters.isJson); } public int getBoundTerms() { return boundTerms; } public void checkAccess(ClientState state) throws InvalidRequestException, UnauthorizedException { if (cfm.isView()) { CFMetaData baseTable = View.findBaseTable(keyspace(), columnFamily()); if (baseTable != null) state.hasColumnFamilyAccess(keyspace(), baseTable.cfName, Permission.SELECT); } else { state.hasColumnFamilyAccess(keyspace(), columnFamily(), Permission.SELECT); } for (Function function : getFunctions()) state.ensureHasPermission(Permission.EXECUTE, function); } public void validate(ClientState state) throws InvalidRequestException { // Nothing to do, all validation has been done by RawStatement.prepare() } public ResultMessage.Rows execute(QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException { return execute(false, state, options); } public ResultMessage.Rows execute(boolean acorn_pr, QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException { ConsistencyLevel cl = options.getConsistency(); checkNotNull(cl, "Invalid empty consistency level"); cl.validateForRead(keyspace()); int nowInSec = FBUtilities.nowInSeconds(); int userLimit = getLimit(options); ReadQuery query = getQuery(options, nowInSec, userLimit); int pageSize = getPageSize(options); if (pageSize <= 0 || query.limits().count() <= pageSize) return execute(query, options, state, nowInSec, userLimit); QueryPager pager = query.getPager(options.getPagingState(), options.getProtocolVersion()); return execute(acorn_pr, Pager.forDistributedQuery(pager, cl, state.getClientState()), options, pageSize, nowInSec, userLimit); } private int getPageSize(QueryOptions options) { int pageSize = options.getPageSize(); // An aggregation query will never be paged for the user, but we always page it internally to avoid OOM. // If we user provided a pageSize we'll use that to page internally (because why not), otherwise we use our default // Note that if there are some nodes in the cluster with a version less than 2.0, we can't use paging (CASSANDRA-6707). if (selection.isAggregate() && pageSize <= 0) pageSize = DEFAULT_COUNT_PAGE_SIZE; return pageSize; } public ReadQuery getQuery(QueryOptions options, int nowInSec) throws RequestValidationException { return getQuery(options, nowInSec, getLimit(options)); } public ReadQuery getQuery(QueryOptions options, int nowInSec, int userLimit) throws RequestValidationException { DataLimits limit = getDataLimits(userLimit); if (restrictions.isKeyRange() || restrictions.usesSecondaryIndexing()) return getRangeCommand(options, limit, nowInSec); return getSliceCommands(options, limit, nowInSec); } private ResultMessage.Rows execute(ReadQuery query, QueryOptions options, QueryState state, int nowInSec, int userLimit) throws RequestValidationException, RequestExecutionException { try (PartitionIterator data = query.execute(options.getConsistency(), state.getClientState())) { return processResults(data, options, nowInSec, userLimit); } } // Simple wrapper class to avoid some code duplication private static abstract class Pager { protected QueryPager pager; protected Pager(QueryPager pager) { this.pager = pager; } public static Pager forInternalQuery(QueryPager pager, ReadOrderGroup orderGroup) { return new InternalPager(pager, orderGroup); } public static Pager forDistributedQuery(QueryPager pager, ConsistencyLevel consistency, ClientState clientState) { return new NormalPager(pager, consistency, clientState); } public boolean isExhausted() { return pager.isExhausted(); } public PagingState state() { return pager.state(); } public abstract PartitionIterator fetchPage(int pageSize); public abstract PartitionIterator fetchPage(boolean acorn_pr, int pageSize); public static class NormalPager extends Pager { private final ConsistencyLevel consistency; private final ClientState clientState; private NormalPager(QueryPager pager, ConsistencyLevel consistency, ClientState clientState) { super(pager); this.consistency = consistency; this.clientState = clientState; } public PartitionIterator fetchPage(int pageSize) { return fetchPage(false, pageSize); } public PartitionIterator fetchPage(boolean acorn_pr, int pageSize) { //if (acorn_pr) // logger.warn("Acorn: pager={} {}", pager.getClass().getName()); // org.apache.cassandra.cql3.statements.SelectStatement$Pager$NormalPager.fetchPage(SelectStatement.java:310) // org.apache.cassandra.cql3.statements.SelectStatement.pageAggregateQuery(SelectStatement.java:409) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:355) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:214) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:215) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:255) // org.apache.cassandra.service.StorageProxy.performWrite(StorageProxy.java:1149) // org.apache.cassandra.service.StorageProxy.mutate(StorageProxy.java:646) // org.apache.cassandra.service.StorageProxy.mutateWithTriggers(StorageProxy.java:872) // org.apache.cassandra.cql3.statements.ModificationStatement.executeWithoutCondition(ModificationStatement.java:415) // org.apache.cassandra.cql3.statements.ModificationStatement.execute(ModificationStatement.java:401) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:217) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:255) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:241) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:235) // org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:146) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:507) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:401) // io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) // io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333) // io.netty.channel.AbstractChannelHandlerContext.access$700(AbstractChannelHandlerContext.java:32) // io.netty.channel.AbstractChannelHandlerContext$8.run(AbstractChannelHandlerContext.java:324) // java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) // org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:164) // org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) // java.lang.Thread.run(Thread.java:745) return pager.fetchPage(acorn_pr, pageSize, consistency, clientState); } } public static class InternalPager extends Pager { private final ReadOrderGroup orderGroup; private InternalPager(QueryPager pager, ReadOrderGroup orderGroup) { super(pager); this.orderGroup = orderGroup; } public PartitionIterator fetchPage(int pageSize) { return fetchPage(false, pageSize); } public PartitionIterator fetchPage(boolean acorn_pr, int pageSize) { return pager.fetchPageInternal(pageSize, orderGroup); } } } private ResultMessage.Rows execute(Pager pager, QueryOptions options, int pageSize, int nowInSec, int userLimit) throws RequestValidationException, RequestExecutionException { return execute(false, pager, options, pageSize, nowInSec, userLimit); } private ResultMessage.Rows execute(boolean acorn_pr, Pager pager, QueryOptions options, int pageSize, int nowInSec, int userLimit) throws RequestValidationException, RequestExecutionException { // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:378) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:214) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:215) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:264) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:244) // org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:148) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:507) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:401) // io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) // io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333) // io.netty.channel.AbstractChannelHandlerContext.access$700(AbstractChannelHandlerContext.java:32) // io.netty.channel.AbstractChannelHandlerContext$8.run(AbstractChannelHandlerContext.java:324) // java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) // org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:164) // org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) // java.lang.Thread.run(Thread.java:745) if (selection.isAggregate()) return pageAggregateQuery(acorn_pr, pager, options, pageSize, nowInSec); // We can't properly do post-query ordering if we page (see #6722) checkFalse(needsPostQueryOrdering(), "Cannot page queries with both ORDER BY and a IN restriction on the partition key;" + " you must either remove the ORDER BY or the IN and sort client side, or disable paging for this query"); ResultMessage.Rows msg; try (PartitionIterator page = pager.fetchPage(acorn_pr, pageSize)) { msg = processResults(page, options, nowInSec, userLimit); } // Please note that the isExhausted state of the pager only gets updated when we've closed the page, so this // shouldn't be moved inside the 'try' above. if (!pager.isExhausted()) msg.result.metadata.setHasMorePages(pager.state()); if (acorn_pr) { // If the keyspace is acorn.*_pr, make the attributes popular in // the local datacenter. final String acornKsRegex = String.format("%s.*_pr$", DatabaseDescriptor.getAcornOptions().keyspace_prefix); final String acornKsPrefix = keyspace().substring(0, keyspace().length() - 3); final String localDataCenter = DatabaseDescriptor.getEndpointSnitch().getDatacenter(FBUtilities.getBroadcastAddress()); if (keyspace().matches(acornKsRegex)) { ResultSet rs = msg.result; ResultSet.ResultMetadata rm = rs.metadata; if (rm.names == null) throw new RuntimeException("Unexpected: rs.names == null"); if (rm.flags.contains(ResultSet.Flag.HAS_MORE_PAGES)) throw new RuntimeException("Unexpected"); for (List<ByteBuffer> row : rs.rows) { String user = null; List<String> topics = null; for (int i = 0; i < row.size(); i++) { String colName = rm.names.get(i).name.toString(); ByteBuffer colValue = row.get(i); if (colValue == null) continue; if (colName.equals("user")) { user = rm.names.get(i).type.getString(colValue); } else if (colName.equals("topics")) { // E.g., ["tennis-160516-164741", "uga-160516-164741"] if (! rm.names.get(i).type.getClass().equals(SetType.class)) throw new RuntimeException(String.format("Unexpected: rm.names.get(%d).type.getClass()=%s" , i, rm.names.get(i).type.getClass().getName())); SetType type = (SetType) rm.names.get(i).type; topics = type.toListOfStrings(colValue, Server.CURRENT_VERSION); } // Reading from colValue seems to change the internal pointer colValue.rewind(); } AcornAttributes acornAttrs = new AcornAttributes(user, topics); //logger.warn("Acorn: acornAttrs={}", acornAttrs); AttrPopMonitor.SetPopular(acornAttrs, acornKsPrefix, localDataCenter); } } } return msg; } private ResultMessage.Rows pageAggregateQuery(boolean acorn, Pager pager, QueryOptions options, int pageSize, int nowInSec) throws RequestValidationException, RequestExecutionException { if (!restrictions.hasPartitionKeyRestrictions()) { logger.warn("Aggregation query used without partition key"); ClientWarn.instance.warn("Aggregation query used without partition key"); } else if (restrictions.keyIsInRelation()) { //for (StackTraceElement ste : Thread.currentThread().getStackTrace()) // logger.warn("Acorn: {}", ste); // // Internal queries // org.apache.cassandra.cql3.statements.SelectStatement.pageAggregateQuery(SelectStatement.java:358) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:325) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:209) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:76) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:207) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:238) // // External (client initiated) queries // org.apache.cassandra.cql3.statements.SelectStatement.pageAggregateQuery(SelectStatement.java:408) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:377) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:214) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:195) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:77) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:217) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:255) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:241) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:235) // org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:148) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:507) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:401) // io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) // io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333) // io.netty.channel.AbstractChannelHandlerContext.access$700(AbstractChannelHandlerContext.java:32) // io.netty.channel.AbstractChannelHandlerContext$8.run(AbstractChannelHandlerContext.java:324) // java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) // org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:164) // org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) // java.lang.Thread.run(Thread.java:745) // // Suppress warnings for Acorn queries. Doesn't suppress warns from // "acorn.*_regular" tables, which happens only when testing. if (! acorn) { logger.warn("Aggregation query used on multiple partition keys (IN restriction)"); ClientWarn.instance.warn("Aggregation query used on multiple partition keys (IN restriction)"); } } Selection.ResultSetBuilder result = selection.resultSetBuilder(parameters.isJson); while (!pager.isExhausted()) { if (acorn) { if (! pager.getClass().equals(SelectStatement.Pager.NormalPager.class)) throw new RuntimeException(String.format("Unexpected: pager.getClass()=%s", pager.getClass().getName())); SelectStatement.Pager.NormalPager spn = (SelectStatement.Pager.NormalPager) pager; try (PartitionIterator iter = spn.fetchPage(acorn, pageSize)) { while (iter.hasNext()) { try (RowIterator partition = iter.next()) { processPartition(partition, options, result, nowInSec); } } } } else { try (PartitionIterator iter = pager.fetchPage(pageSize)) { while (iter.hasNext()) { try (RowIterator partition = iter.next()) { processPartition(partition, options, result, nowInSec); } } } } } return new ResultMessage.Rows(result.build(options.getProtocolVersion())); } private ResultMessage.Rows processResults(PartitionIterator partitions, QueryOptions options, int nowInSec, int userLimit) throws RequestValidationException { ResultSet rset = process(partitions, options, nowInSec, userLimit); return new ResultMessage.Rows(rset); } public ResultMessage.Rows executeInternal(QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException { int nowInSec = FBUtilities.nowInSeconds(); int userLimit = getLimit(options); ReadQuery query = getQuery(options, nowInSec, userLimit); int pageSize = getPageSize(options); try (ReadOrderGroup orderGroup = query.startOrderGroup()) { if (pageSize <= 0 || query.limits().count() <= pageSize) { try (PartitionIterator data = query.executeInternal(orderGroup)) { return processResults(data, options, nowInSec, userLimit); } } else { QueryPager pager = query.getPager(options.getPagingState(), options.getProtocolVersion()); return execute(Pager.forInternalQuery(pager, orderGroup), options, pageSize, nowInSec, userLimit); } } } public ResultSet process(PartitionIterator partitions, int nowInSec) throws InvalidRequestException { return process(partitions, QueryOptions.DEFAULT, nowInSec, getLimit(QueryOptions.DEFAULT)); } public String keyspace() { return cfm.ksName; } public String columnFamily() { return cfm.cfName; } /** * May be used by custom QueryHandler implementations */ public Selection getSelection() { return selection; } /** * May be used by custom QueryHandler implementations */ public StatementRestrictions getRestrictions() { return restrictions; } private ReadQuery getSliceCommands(QueryOptions options, DataLimits limit, int nowInSec) throws RequestValidationException { Collection<ByteBuffer> keys = restrictions.getPartitionKeys(options); if (keys.isEmpty()) return ReadQuery.EMPTY; ClusteringIndexFilter filter = makeClusteringIndexFilter(options); if (filter == null) return ReadQuery.EMPTY; RowFilter rowFilter = getRowFilter(options); // Note that we use the total limit for every key, which is potentially inefficient. // However, IN + LIMIT is not a very sensible choice. List<SinglePartitionReadCommand> commands = new ArrayList<>(keys.size()); for (ByteBuffer key : keys) { QueryProcessor.validateKey(key); DecoratedKey dk = cfm.decorateKey(ByteBufferUtil.clone(key)); commands.add(SinglePartitionReadCommand.create(cfm, nowInSec, queriedColumns, rowFilter, limit, dk, filter)); } return new SinglePartitionReadCommand.Group(commands, limit); } /** * Returns a read command that can be used internally to filter individual rows for materialized views. */ public SinglePartitionReadCommand internalReadForView(DecoratedKey key, int nowInSec) { QueryOptions options = QueryOptions.forInternalCalls(Collections.emptyList()); ClusteringIndexFilter filter = makeClusteringIndexFilter(options); RowFilter rowFilter = getRowFilter(options); return SinglePartitionReadCommand.create(cfm, nowInSec, queriedColumns, rowFilter, DataLimits.NONE, key, filter); } private ReadQuery getRangeCommand(QueryOptions options, DataLimits limit, int nowInSec) throws RequestValidationException { ClusteringIndexFilter clusteringIndexFilter = makeClusteringIndexFilter(options); if (clusteringIndexFilter == null) return ReadQuery.EMPTY; RowFilter rowFilter = getRowFilter(options); // The LIMIT provided by the user is the number of CQL row he wants returned. // We want to have getRangeSlice to count the number of columns, not the number of keys. AbstractBounds<PartitionPosition> keyBounds = restrictions.getPartitionKeyBounds(options); if (keyBounds == null) return ReadQuery.EMPTY; PartitionRangeReadCommand command = new PartitionRangeReadCommand(cfm, nowInSec, queriedColumns, rowFilter, limit, new DataRange(keyBounds, clusteringIndexFilter), Optional.empty()); // If there's a secondary index that the command can use, have it validate // the request parameters. Note that as a side effect, if a viable Index is // identified by the CFS's index manager, it will be cached in the command // and serialized during distribution to replicas in order to avoid performing // further lookups. command.maybeValidateIndex(); return command; } private ClusteringIndexFilter makeClusteringIndexFilter(QueryOptions options) throws InvalidRequestException { if (parameters.isDistinct) { // We need to be able to distinguish between partition having live rows and those that don't. But // doing so is not trivial since "having a live row" depends potentially on // 1) when the query is performed, due to TTLs // 2) how thing reconcile together between different nodes // so that it's hard to really optimize properly internally. So to keep it simple, we simply query // for the first row of the partition and hence uses Slices.ALL. We'll limit it to the first live // row however in getLimit(). return new ClusteringIndexSliceFilter(Slices.ALL, false); } if (restrictions.isColumnRange()) { Slices slices = makeSlices(options); if (slices == Slices.NONE && !selection.containsStaticColumns()) return null; return new ClusteringIndexSliceFilter(slices, isReversed); } else { NavigableSet<Clustering> clusterings = getRequestedRows(options); // We can have no clusterings if either we're only selecting the static columns, or if we have // a 'IN ()' for clusterings. In that case, we still want to query if some static columns are // queried. But we're fine otherwise. if (clusterings.isEmpty() && queriedColumns.fetchedColumns().statics.isEmpty()) return null; return new ClusteringIndexNamesFilter(clusterings, isReversed); } } private Slices makeSlices(QueryOptions options) throws InvalidRequestException { SortedSet<Slice.Bound> startBounds = restrictions.getClusteringColumnsBounds(Bound.START, options); SortedSet<Slice.Bound> endBounds = restrictions.getClusteringColumnsBounds(Bound.END, options); assert startBounds.size() == endBounds.size(); // The case where startBounds == 1 is common enough that it's worth optimizing if (startBounds.size() == 1) { Slice.Bound start = startBounds.first(); Slice.Bound end = endBounds.first(); return cfm.comparator.compare(start, end) > 0 ? Slices.NONE : Slices.with(cfm.comparator, Slice.make(start, end)); } Slices.Builder builder = new Slices.Builder(cfm.comparator, startBounds.size()); Iterator<Slice.Bound> startIter = startBounds.iterator(); Iterator<Slice.Bound> endIter = endBounds.iterator(); while (startIter.hasNext() && endIter.hasNext()) { Slice.Bound start = startIter.next(); Slice.Bound end = endIter.next(); // Ignore slices that are nonsensical if (cfm.comparator.compare(start, end) > 0) continue; builder.add(start, end); } return builder.build(); } private DataLimits getDataLimits(int userLimit) { int cqlRowLimit = DataLimits.NO_LIMIT; // If we aggregate, the limit really apply to the number of rows returned to the user, not to what is queried, and // since in practice we currently only aggregate at top level (we have no GROUP BY support yet), we'll only ever // return 1 result and can therefore basically ignore the user LIMIT in this case. // Whenever we support GROUP BY, we'll have to add a new DataLimits kind that knows how things are grouped and is thus // able to apply the user limit properly. // If we do post ordering we need to get all the results sorted before we can trim them. if (!selection.isAggregate() && !needsPostQueryOrdering()) cqlRowLimit = userLimit; if (parameters.isDistinct) return cqlRowLimit == DataLimits.NO_LIMIT ? DataLimits.DISTINCT_NONE : DataLimits.distinctLimits(cqlRowLimit); return cqlRowLimit == DataLimits.NO_LIMIT ? DataLimits.NONE : DataLimits.cqlLimits(cqlRowLimit); } /** * Returns the limit specified by the user. * May be used by custom QueryHandler implementations * * @return the limit specified by the user or <code>DataLimits.NO_LIMIT</code> if no value * as been specified. */ public int getLimit(QueryOptions options) { int userLimit = DataLimits.NO_LIMIT; if (limit != null) { ByteBuffer b = checkNotNull(limit.bindAndGet(options), "Invalid null value of limit"); // treat UNSET limit value as 'unlimited' if (b != UNSET_BYTE_BUFFER) { try { Int32Type.instance.validate(b); userLimit = Int32Type.instance.compose(b); checkTrue(userLimit > 0, "LIMIT must be strictly positive"); } catch (MarshalException e) { throw new InvalidRequestException("Invalid limit value"); } } } return userLimit; } private NavigableSet<Clustering> getRequestedRows(QueryOptions options) throws InvalidRequestException { // Note: getRequestedColumns don't handle static columns, but due to CASSANDRA-5762 // we always do a slice for CQL3 tables, so it's ok to ignore them here assert !restrictions.isColumnRange(); return restrictions.getClusteringColumns(options); } /** * May be used by custom QueryHandler implementations */ public RowFilter getRowFilter(QueryOptions options) throws InvalidRequestException { ColumnFamilyStore cfs = Keyspace.open(keyspace()).getColumnFamilyStore(columnFamily()); SecondaryIndexManager secondaryIndexManager = cfs.indexManager; RowFilter filter = restrictions.getRowFilter(secondaryIndexManager, options); return filter; } private ResultSet process(PartitionIterator partitions, QueryOptions options, int nowInSec, int userLimit) throws InvalidRequestException { Selection.ResultSetBuilder result = selection.resultSetBuilder(parameters.isJson); while (partitions.hasNext()) { try (RowIterator partition = partitions.next()) { processPartition(partition, options, result, nowInSec); } } ResultSet cqlRows = result.build(options.getProtocolVersion()); orderResults(cqlRows); cqlRows.trim(userLimit); return cqlRows; } public static ByteBuffer[] getComponents(CFMetaData cfm, DecoratedKey dk) { ByteBuffer key = dk.getKey(); if (cfm.getKeyValidator() instanceof CompositeType) { return ((CompositeType)cfm.getKeyValidator()).split(key); } else { return new ByteBuffer[]{ key }; } } // Used by ModificationStatement for CAS operations void processPartition(RowIterator partition, QueryOptions options, Selection.ResultSetBuilder result, int nowInSec) throws InvalidRequestException { int protocolVersion = options.getProtocolVersion(); ByteBuffer[] keyComponents = getComponents(cfm, partition.partitionKey()); Row staticRow = partition.staticRow(); // If there is no rows, then provided the select was a full partition selection // (i.e. not a 2ndary index search and there was no condition on clustering columns), // we want to include static columns and we're done. if (!partition.hasNext()) { if (!staticRow.isEmpty() && (!restrictions.usesSecondaryIndexing() || cfm.isStaticCompactTable()) && !restrictions.hasClusteringColumnsRestriction()) { result.newRow(protocolVersion); for (ColumnDefinition def : selection.getColumns()) { switch (def.kind) { case PARTITION_KEY: result.add(keyComponents[def.position()]); break; case STATIC: addValue(result, def, staticRow, nowInSec, protocolVersion); break; default: result.add((ByteBuffer)null); } } } return; } while (partition.hasNext()) { Row row = partition.next(); result.newRow(protocolVersion); // Respect selection order for (ColumnDefinition def : selection.getColumns()) { switch (def.kind) { case PARTITION_KEY: result.add(keyComponents[def.position()]); break; case CLUSTERING: result.add(row.clustering().get(def.position())); break; case REGULAR: addValue(result, def, row, nowInSec, protocolVersion); break; case STATIC: addValue(result, def, staticRow, nowInSec, protocolVersion); break; } } } } private static void addValue(Selection.ResultSetBuilder result, ColumnDefinition def, Row row, int nowInSec, int protocolVersion) { if (def.isComplex()) { // Collections are the only complex types we have so far assert def.type.isCollection() && def.type.isMultiCell(); ComplexColumnData complexData = row.getComplexColumnData(def); if (complexData == null) result.add((ByteBuffer)null); else result.add(((CollectionType)def.type).serializeForNativeProtocol(def, complexData.iterator(), protocolVersion)); } else { result.add(row.getCell(def), nowInSec); } } private boolean needsPostQueryOrdering() { // We need post-query ordering only for queries with IN on the partition key and an ORDER BY. return restrictions.keyIsInRelation() && !parameters.orderings.isEmpty(); } /** * Orders results when multiple keys are selected (using IN) */ private void orderResults(ResultSet cqlRows) { if (cqlRows.size() == 0 || !needsPostQueryOrdering()) return; Collections.sort(cqlRows.rows, orderingComparator); } public static class RawStatement extends CFStatement { public final Parameters parameters; public final List<RawSelector> selectClause; public final WhereClause whereClause; public final Term.Raw limit; public RawStatement(CFName cfName, Parameters parameters, List<RawSelector> selectClause, WhereClause whereClause, Term.Raw limit) { super(cfName); this.parameters = parameters; this.selectClause = selectClause; this.whereClause = whereClause; this.limit = limit; } public ParsedStatement.Prepared prepare() throws InvalidRequestException { return prepare(false); } public ParsedStatement.Prepared prepare(boolean forView) throws InvalidRequestException { CFMetaData cfm = ThriftValidation.validateColumnFamily(keyspace(), columnFamily()); VariableSpecifications boundNames = getBoundVariables(); Selection selection = selectClause.isEmpty() ? Selection.wildcard(cfm) : Selection.fromSelectors(cfm, selectClause); StatementRestrictions restrictions = prepareRestrictions(cfm, boundNames, selection, forView); if (parameters.isDistinct) validateDistinctSelection(cfm, selection, restrictions); Comparator<List<ByteBuffer>> orderingComparator = null; boolean isReversed = false; if (!parameters.orderings.isEmpty()) { assert !forView; verifyOrderingIsAllowed(restrictions); orderingComparator = getOrderingComparator(cfm, selection, restrictions); isReversed = isReversed(cfm); if (isReversed) orderingComparator = Collections.reverseOrder(orderingComparator); } checkNeedsFiltering(restrictions); SelectStatement stmt = new SelectStatement(cfm, boundNames.size(), parameters, selection, restrictions, isReversed, orderingComparator, prepareLimit(boundNames)); return new ParsedStatement.Prepared(stmt, boundNames, boundNames.getPartitionKeyBindIndexes(cfm)); } /** * Prepares the restrictions. * * @param cfm the column family meta data * @param boundNames the variable specifications * @param selection the selection * @return the restrictions * @throws InvalidRequestException if a problem occurs while building the restrictions */ private StatementRestrictions prepareRestrictions(CFMetaData cfm, VariableSpecifications boundNames, Selection selection, boolean forView) throws InvalidRequestException { try { return new StatementRestrictions(StatementType.SELECT, cfm, whereClause, boundNames, selection.containsOnlyStaticColumns(), selection.containsACollection(), parameters.allowFiltering, forView); } catch (UnrecognizedEntityException e) { if (containsAlias(e.entity)) throw invalidRequest("Aliases aren't allowed in the where clause ('%s')", e.relation); throw e; } } /** Returns a Term for the limit or null if no limit is set */ private Term prepareLimit(VariableSpecifications boundNames) throws InvalidRequestException { if (limit == null) return null; Term prepLimit = limit.prepare(keyspace(), limitReceiver()); prepLimit.collectMarkerSpecification(boundNames); return prepLimit; } private static void verifyOrderingIsAllowed(StatementRestrictions restrictions) throws InvalidRequestException { checkFalse(restrictions.usesSecondaryIndexing(), "ORDER BY with 2ndary indexes is not supported."); checkFalse(restrictions.isKeyRange(), "ORDER BY is only supported when the partition key is restricted by an EQ or an IN."); } private static void validateDistinctSelection(CFMetaData cfm, Selection selection, StatementRestrictions restrictions) throws InvalidRequestException { Collection<ColumnDefinition> requestedColumns = selection.getColumns(); for (ColumnDefinition def : requestedColumns) checkFalse(!def.isPartitionKey() && !def.isStatic(), "SELECT DISTINCT queries must only request partition key columns and/or static columns (not %s)", def.name); // If it's a key range, we require that all partition key columns are selected so we don't have to bother // with post-query grouping. if (!restrictions.isKeyRange()) return; for (ColumnDefinition def : cfm.partitionKeyColumns()) checkTrue(requestedColumns.contains(def), "SELECT DISTINCT queries must request all the partition key columns (missing %s)", def.name); } private void handleUnrecognizedOrderingColumn(ColumnIdentifier column) throws InvalidRequestException { checkFalse(containsAlias(column), "Aliases are not allowed in order by clause ('%s')", column); checkFalse(true, "Order by on unknown column %s", column); } private Comparator<List<ByteBuffer>> getOrderingComparator(CFMetaData cfm, Selection selection, StatementRestrictions restrictions) throws InvalidRequestException { if (!restrictions.keyIsInRelation()) return null; Map<ColumnIdentifier, Integer> orderingIndexes = getOrderingIndex(cfm, selection); List<Integer> idToSort = new ArrayList<Integer>(); List<Comparator<ByteBuffer>> sorters = new ArrayList<Comparator<ByteBuffer>>(); for (ColumnIdentifier.Raw raw : parameters.orderings.keySet()) { ColumnIdentifier identifier = raw.prepare(cfm); ColumnDefinition orderingColumn = cfm.getColumnDefinition(identifier); idToSort.add(orderingIndexes.get(orderingColumn.name)); sorters.add(orderingColumn.type); } return idToSort.size() == 1 ? new SingleColumnComparator(idToSort.get(0), sorters.get(0)) : new CompositeComparator(sorters, idToSort); } private Map<ColumnIdentifier, Integer> getOrderingIndex(CFMetaData cfm, Selection selection) throws InvalidRequestException { // If we order post-query (see orderResults), the sorted column needs to be in the ResultSet for sorting, // even if we don't // ultimately ship them to the client (CASSANDRA-4911). Map<ColumnIdentifier, Integer> orderingIndexes = new HashMap<>(); for (ColumnIdentifier.Raw raw : parameters.orderings.keySet()) { ColumnIdentifier column = raw.prepare(cfm); final ColumnDefinition def = cfm.getColumnDefinition(column); if (def == null) handleUnrecognizedOrderingColumn(column); int index = selection.getResultSetIndex(def); if (index < 0) index = selection.addColumnForOrdering(def); orderingIndexes.put(def.name, index); } return orderingIndexes; } private boolean isReversed(CFMetaData cfm) throws InvalidRequestException { Boolean[] reversedMap = new Boolean[cfm.clusteringColumns().size()]; int i = 0; for (Map.Entry<ColumnIdentifier.Raw, Boolean> entry : parameters.orderings.entrySet()) { ColumnIdentifier column = entry.getKey().prepare(cfm); boolean reversed = entry.getValue(); ColumnDefinition def = cfm.getColumnDefinition(column); if (def == null) handleUnrecognizedOrderingColumn(column); checkTrue(def.isClusteringColumn(), "Order by is currently only supported on the clustered columns of the PRIMARY KEY, got %s", column); checkTrue(i++ == def.position(), "Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY"); reversedMap[def.position()] = (reversed != def.isReversedType()); } // Check that all boolean in reversedMap, if set, agrees Boolean isReversed = null; for (Boolean b : reversedMap) { // Column on which order is specified can be in any order if (b == null) continue; if (isReversed == null) { isReversed = b; continue; } checkTrue(isReversed.equals(b), "Unsupported order by relation"); } assert isReversed != null; return isReversed; } /** If ALLOW FILTERING was not specified, this verifies that it is not needed */ private void checkNeedsFiltering(StatementRestrictions restrictions) throws InvalidRequestException { // non-key-range non-indexed queries cannot involve filtering underneath if (!parameters.allowFiltering && (restrictions.isKeyRange() || restrictions.usesSecondaryIndexing())) { // We will potentially filter data if either: // - Have more than one IndexExpression // - Have no index expression and the row filter is not the identity checkFalse(restrictions.needFiltering(), StatementRestrictions.REQUIRES_ALLOW_FILTERING_MESSAGE); } } private boolean containsAlias(final ColumnIdentifier name) { return Iterables.any(selectClause, new Predicate<RawSelector>() { public boolean apply(RawSelector raw) { return name.equals(raw.alias); } }); } private ColumnSpecification limitReceiver() { return new ColumnSpecification(keyspace(), columnFamily(), new ColumnIdentifier("[limit]", true), Int32Type.instance); } @Override public String toString() { return Objects.toStringHelper(this) .add("name", cfName) .add("selectClause", selectClause) .add("whereClause", whereClause) .add("isDistinct", parameters.isDistinct) .toString(); } } public static class Parameters { // Public because CASSANDRA-9858 public final Map<ColumnIdentifier.Raw, Boolean> orderings; public final boolean isDistinct; public final boolean allowFiltering; public final boolean isJson; public Parameters(Map<ColumnIdentifier.Raw, Boolean> orderings, boolean isDistinct, boolean allowFiltering, boolean isJson) { this.orderings = orderings; this.isDistinct = isDistinct; this.allowFiltering = allowFiltering; this.isJson = isJson; } } private static abstract class ColumnComparator<T> implements Comparator<T> { protected final int compare(Comparator<ByteBuffer> comparator, ByteBuffer aValue, ByteBuffer bValue) { if (aValue == null) return bValue == null ? 0 : -1; return bValue == null ? 1 : comparator.compare(aValue, bValue); } } /** * Used in orderResults(...) method when single 'ORDER BY' condition where given */ private static class SingleColumnComparator extends ColumnComparator<List<ByteBuffer>> { private final int index; private final Comparator<ByteBuffer> comparator; public SingleColumnComparator(int columnIndex, Comparator<ByteBuffer> orderer) { index = columnIndex; comparator = orderer; } public int compare(List<ByteBuffer> a, List<ByteBuffer> b) { return compare(comparator, a.get(index), b.get(index)); } } /** * Used in orderResults(...) method when multiple 'ORDER BY' conditions where given */ private static class CompositeComparator extends ColumnComparator<List<ByteBuffer>> { private final List<Comparator<ByteBuffer>> orderTypes; private final List<Integer> positions; private CompositeComparator(List<Comparator<ByteBuffer>> orderTypes, List<Integer> positions) { this.orderTypes = orderTypes; this.positions = positions; } public int compare(List<ByteBuffer> a, List<ByteBuffer> b) { for (int i = 0; i < positions.size(); i++) { Comparator<ByteBuffer> type = orderTypes.get(i); int columnPos = positions.get(i); int comparison = compare(type, a.get(columnPos), b.get(columnPos)); if (comparison != 0) return comparison; } return 0; } } }
src/java/org/apache/cassandra/cql3/statements/SelectStatement.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.cql3.statements; import java.nio.ByteBuffer; import java.util.*; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.acorn.AcornAttributes; import org.apache.cassandra.acorn.AttrPopMonitor; import org.apache.cassandra.auth.Permission; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.*; import org.apache.cassandra.cql3.functions.Function; import org.apache.cassandra.cql3.restrictions.StatementRestrictions; import org.apache.cassandra.cql3.selection.RawSelector; import org.apache.cassandra.cql3.selection.Selection; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.*; import org.apache.cassandra.db.marshal.CollectionType; import org.apache.cassandra.db.marshal.CompositeType; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.db.marshal.SetType; import org.apache.cassandra.db.partitions.PartitionIterator; import org.apache.cassandra.db.rows.ComplexColumnData; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.db.rows.RowIterator; import org.apache.cassandra.db.view.View; import org.apache.cassandra.dht.AbstractBounds; import org.apache.cassandra.exceptions.*; import org.apache.cassandra.index.SecondaryIndexManager; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.ClientWarn; import org.apache.cassandra.service.QueryState; import org.apache.cassandra.service.pager.AbstractQueryPager; import org.apache.cassandra.service.pager.PagingState; import org.apache.cassandra.service.pager.QueryPager; import org.apache.cassandra.thrift.ThriftValidation; import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.cassandra.transport.Server; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse; import static org.apache.cassandra.cql3.statements.RequestValidations.checkNotNull; import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue; import static org.apache.cassandra.cql3.statements.RequestValidations.invalidRequest; import static org.apache.cassandra.utils.ByteBufferUtil.UNSET_BYTE_BUFFER; /** * Encapsulates a completely parsed SELECT query, including the target * column family, expression, result count, and ordering clause. * * A number of public methods here are only used internally. However, * many of these are made accessible for the benefit of custom * QueryHandler implementations, so before reducing their accessibility * due consideration should be given. */ public class SelectStatement implements CQLStatement { private static final Logger logger = LoggerFactory.getLogger(SelectStatement.class); private static final int DEFAULT_COUNT_PAGE_SIZE = 10000; private final int boundTerms; public final CFMetaData cfm; public final Parameters parameters; private final Selection selection; private final Term limit; private final StatementRestrictions restrictions; private final boolean isReversed; /** * The comparator used to orders results when multiple keys are selected (using IN). */ private final Comparator<List<ByteBuffer>> orderingComparator; private final ColumnFilter queriedColumns; // Used by forSelection below private static final Parameters defaultParameters = new Parameters(Collections.<ColumnIdentifier.Raw, Boolean>emptyMap(), false, false, false); public SelectStatement(CFMetaData cfm, int boundTerms, Parameters parameters, Selection selection, StatementRestrictions restrictions, boolean isReversed, Comparator<List<ByteBuffer>> orderingComparator, Term limit) { this.cfm = cfm; this.boundTerms = boundTerms; this.selection = selection; this.restrictions = restrictions; this.isReversed = isReversed; this.orderingComparator = orderingComparator; this.parameters = parameters; this.limit = limit; this.queriedColumns = gatherQueriedColumns(); } public Iterable<Function> getFunctions() { return Iterables.concat(selection.getFunctions(), restrictions.getFunctions(), limit != null ? limit.getFunctions() : Collections.<Function>emptySet()); } // Note that the queried columns internally is different from the one selected by the // user as it also include any column for which we have a restriction on. private ColumnFilter gatherQueriedColumns() { if (selection.isWildcard()) return ColumnFilter.all(cfm); ColumnFilter.Builder builder = ColumnFilter.allColumnsBuilder(cfm); // Adds all selected columns for (ColumnDefinition def : selection.getColumns()) if (!def.isPrimaryKeyColumn()) builder.add(def); // as well as any restricted column (so we can actually apply the restriction) builder.addAll(restrictions.nonPKRestrictedColumns(true)); return builder.build(); } // Creates a simple select based on the given selection. // Note that the results select statement should not be used for actual queries, but only for processing already // queried data through processColumnFamily. static SelectStatement forSelection(CFMetaData cfm, Selection selection) { return new SelectStatement(cfm, 0, defaultParameters, selection, StatementRestrictions.empty(StatementType.SELECT, cfm), false, null, null); } public ResultSet.ResultMetadata getResultMetadata() { return selection.getResultMetadata(parameters.isJson); } public int getBoundTerms() { return boundTerms; } public void checkAccess(ClientState state) throws InvalidRequestException, UnauthorizedException { if (cfm.isView()) { CFMetaData baseTable = View.findBaseTable(keyspace(), columnFamily()); if (baseTable != null) state.hasColumnFamilyAccess(keyspace(), baseTable.cfName, Permission.SELECT); } else { state.hasColumnFamilyAccess(keyspace(), columnFamily(), Permission.SELECT); } for (Function function : getFunctions()) state.ensureHasPermission(Permission.EXECUTE, function); } public void validate(ClientState state) throws InvalidRequestException { // Nothing to do, all validation has been done by RawStatement.prepare() } public ResultMessage.Rows execute(QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException { return execute(false, state, options); } public ResultMessage.Rows execute(boolean acorn_pr, QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException { ConsistencyLevel cl = options.getConsistency(); checkNotNull(cl, "Invalid empty consistency level"); cl.validateForRead(keyspace()); int nowInSec = FBUtilities.nowInSeconds(); int userLimit = getLimit(options); ReadQuery query = getQuery(options, nowInSec, userLimit); int pageSize = getPageSize(options); if (pageSize <= 0 || query.limits().count() <= pageSize) return execute(query, options, state, nowInSec, userLimit); QueryPager pager = query.getPager(options.getPagingState(), options.getProtocolVersion()); return execute(acorn_pr, Pager.forDistributedQuery(pager, cl, state.getClientState()), options, pageSize, nowInSec, userLimit); } private int getPageSize(QueryOptions options) { int pageSize = options.getPageSize(); // An aggregation query will never be paged for the user, but we always page it internally to avoid OOM. // If we user provided a pageSize we'll use that to page internally (because why not), otherwise we use our default // Note that if there are some nodes in the cluster with a version less than 2.0, we can't use paging (CASSANDRA-6707). if (selection.isAggregate() && pageSize <= 0) pageSize = DEFAULT_COUNT_PAGE_SIZE; return pageSize; } public ReadQuery getQuery(QueryOptions options, int nowInSec) throws RequestValidationException { return getQuery(options, nowInSec, getLimit(options)); } public ReadQuery getQuery(QueryOptions options, int nowInSec, int userLimit) throws RequestValidationException { DataLimits limit = getDataLimits(userLimit); if (restrictions.isKeyRange() || restrictions.usesSecondaryIndexing()) return getRangeCommand(options, limit, nowInSec); return getSliceCommands(options, limit, nowInSec); } private ResultMessage.Rows execute(ReadQuery query, QueryOptions options, QueryState state, int nowInSec, int userLimit) throws RequestValidationException, RequestExecutionException { try (PartitionIterator data = query.execute(options.getConsistency(), state.getClientState())) { return processResults(data, options, nowInSec, userLimit); } } // Simple wrapper class to avoid some code duplication private static abstract class Pager { protected QueryPager pager; protected Pager(QueryPager pager) { this.pager = pager; } public static Pager forInternalQuery(QueryPager pager, ReadOrderGroup orderGroup) { return new InternalPager(pager, orderGroup); } public static Pager forDistributedQuery(QueryPager pager, ConsistencyLevel consistency, ClientState clientState) { return new NormalPager(pager, consistency, clientState); } public boolean isExhausted() { return pager.isExhausted(); } public PagingState state() { return pager.state(); } public abstract PartitionIterator fetchPage(int pageSize); public abstract PartitionIterator fetchPage(boolean acorn_pr, int pageSize); public static class NormalPager extends Pager { private final ConsistencyLevel consistency; private final ClientState clientState; private NormalPager(QueryPager pager, ConsistencyLevel consistency, ClientState clientState) { super(pager); this.consistency = consistency; this.clientState = clientState; } public PartitionIterator fetchPage(int pageSize) { return fetchPage(false, pageSize); } public PartitionIterator fetchPage(boolean acorn_pr, int pageSize) { //if (acorn_pr) // logger.warn("Acorn: pager={} {}", pager.getClass().getName()); // org.apache.cassandra.cql3.statements.SelectStatement$Pager$NormalPager.fetchPage(SelectStatement.java:310) // org.apache.cassandra.cql3.statements.SelectStatement.pageAggregateQuery(SelectStatement.java:409) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:355) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:214) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:215) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:255) // org.apache.cassandra.service.StorageProxy.performWrite(StorageProxy.java:1149) // org.apache.cassandra.service.StorageProxy.mutate(StorageProxy.java:646) // org.apache.cassandra.service.StorageProxy.mutateWithTriggers(StorageProxy.java:872) // org.apache.cassandra.cql3.statements.ModificationStatement.executeWithoutCondition(ModificationStatement.java:415) // org.apache.cassandra.cql3.statements.ModificationStatement.execute(ModificationStatement.java:401) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:217) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:255) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:241) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:235) // org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:146) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:507) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:401) // io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) // io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333) // io.netty.channel.AbstractChannelHandlerContext.access$700(AbstractChannelHandlerContext.java:32) // io.netty.channel.AbstractChannelHandlerContext$8.run(AbstractChannelHandlerContext.java:324) // java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) // org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:164) // org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) // java.lang.Thread.run(Thread.java:745) return pager.fetchPage(acorn_pr, pageSize, consistency, clientState); } } public static class InternalPager extends Pager { private final ReadOrderGroup orderGroup; private InternalPager(QueryPager pager, ReadOrderGroup orderGroup) { super(pager); this.orderGroup = orderGroup; } public PartitionIterator fetchPage(int pageSize) { return fetchPage(false, pageSize); } public PartitionIterator fetchPage(boolean acorn_pr, int pageSize) { return pager.fetchPageInternal(pageSize, orderGroup); } } } private ResultMessage.Rows execute(Pager pager, QueryOptions options, int pageSize, int nowInSec, int userLimit) throws RequestValidationException, RequestExecutionException { return execute(false, pager, options, pageSize, nowInSec, userLimit); } private ResultMessage.Rows execute(boolean acorn_pr, Pager pager, QueryOptions options, int pageSize, int nowInSec, int userLimit) throws RequestValidationException, RequestExecutionException { // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:378) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:214) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:215) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:264) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:244) // org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:148) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:507) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:401) // io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) // io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333) // io.netty.channel.AbstractChannelHandlerContext.access$700(AbstractChannelHandlerContext.java:32) // io.netty.channel.AbstractChannelHandlerContext$8.run(AbstractChannelHandlerContext.java:324) // java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) // org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:164) // org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) // java.lang.Thread.run(Thread.java:745) if (selection.isAggregate()) return pageAggregateQuery(acorn_pr, pager, options, pageSize, nowInSec); // We can't properly do post-query ordering if we page (see #6722) checkFalse(needsPostQueryOrdering(), "Cannot page queries with both ORDER BY and a IN restriction on the partition key;" + " you must either remove the ORDER BY or the IN and sort client side, or disable paging for this query"); ResultMessage.Rows msg; try (PartitionIterator page = pager.fetchPage(acorn_pr, pageSize)) { msg = processResults(page, options, nowInSec, userLimit); } // Please note that the isExhausted state of the pager only gets updated when we've closed the page, so this // shouldn't be moved inside the 'try' above. if (!pager.isExhausted()) msg.result.metadata.setHasMorePages(pager.state()); if (acorn_pr) { // If the keyspace is acorn.*_pr, make the attributes popular in // the local datacenter. final String acorn_ks_regex = String.format("%s.*_pr$", DatabaseDescriptor.getAcornOptions().keyspace_prefix); final String acornKsPrefix = keyspace().substring(0, keyspace().length() - 3); final String localDataCenter = DatabaseDescriptor.getEndpointSnitch().getDatacenter(FBUtilities.getBroadcastAddress()); if (keyspace().matches(acorn_ks_regex)) { ResultSet rs = msg.result; ResultSet.ResultMetadata rm = rs.metadata; if (rm.names == null) throw new RuntimeException("Unexpected: rs.names == null"); if (rm.flags.contains(ResultSet.Flag.HAS_MORE_PAGES)) throw new RuntimeException("Unexpected"); for (List<ByteBuffer> row : rs.rows) { String user = null; List<String> topics = null; for (int i = 0; i < row.size(); i++) { String colName = rm.names.get(i).name.toString(); ByteBuffer colValue = row.get(i); if (colValue == null) continue; if (colName.equals("user")) { user = rm.names.get(i).type.getString(colValue); } else if (colName.equals("topics")) { // E.g., ["tennis-160516-164741", "uga-160516-164741"] if (! rm.names.get(i).type.getClass().equals(SetType.class)) throw new RuntimeException(String.format("Unexpected: rm.names.get(%d).type.getClass()=%s" , i, rm.names.get(i).type.getClass().getName())); SetType type = (SetType) rm.names.get(i).type; topics = type.toListOfStrings(colValue, Server.CURRENT_VERSION); } // Reading from colValue seems to change the internal pointer colValue.rewind(); } AcornAttributes acornAttrs = new AcornAttributes(user, topics); //logger.warn("Acorn: acornAttrs={}", acornAttrs); AttrPopMonitor.SetPopular(acornAttrs, acornKsPrefix, localDataCenter); } } } return msg; } private ResultMessage.Rows pageAggregateQuery(boolean acorn, Pager pager, QueryOptions options, int pageSize, int nowInSec) throws RequestValidationException, RequestExecutionException { if (!restrictions.hasPartitionKeyRestrictions()) { logger.warn("Aggregation query used without partition key"); ClientWarn.instance.warn("Aggregation query used without partition key"); } else if (restrictions.keyIsInRelation()) { //for (StackTraceElement ste : Thread.currentThread().getStackTrace()) // logger.warn("Acorn: {}", ste); // // Internal queries // org.apache.cassandra.cql3.statements.SelectStatement.pageAggregateQuery(SelectStatement.java:358) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:325) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:209) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:76) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:207) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:238) // // External (client initiated) queries // org.apache.cassandra.cql3.statements.SelectStatement.pageAggregateQuery(SelectStatement.java:408) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:377) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:214) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:195) // org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:77) // org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:217) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:255) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:241) // org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:235) // org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:148) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:507) // org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:401) // io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) // io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333) // io.netty.channel.AbstractChannelHandlerContext.access$700(AbstractChannelHandlerContext.java:32) // io.netty.channel.AbstractChannelHandlerContext$8.run(AbstractChannelHandlerContext.java:324) // java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) // org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:164) // org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) // java.lang.Thread.run(Thread.java:745) // // Suppress warnings for Acorn queries. Doesn't suppress warns from // "acorn.*_regular" tables, which happens only when testing. if (! acorn) { logger.warn("Aggregation query used on multiple partition keys (IN restriction)"); ClientWarn.instance.warn("Aggregation query used on multiple partition keys (IN restriction)"); } } Selection.ResultSetBuilder result = selection.resultSetBuilder(parameters.isJson); while (!pager.isExhausted()) { if (acorn) { if (! pager.getClass().equals(SelectStatement.Pager.NormalPager.class)) throw new RuntimeException(String.format("Unexpected: pager.getClass()=%s", pager.getClass().getName())); SelectStatement.Pager.NormalPager spn = (SelectStatement.Pager.NormalPager) pager; try (PartitionIterator iter = spn.fetchPage(acorn, pageSize)) { while (iter.hasNext()) { try (RowIterator partition = iter.next()) { processPartition(partition, options, result, nowInSec); } } } } else { try (PartitionIterator iter = pager.fetchPage(pageSize)) { while (iter.hasNext()) { try (RowIterator partition = iter.next()) { processPartition(partition, options, result, nowInSec); } } } } } return new ResultMessage.Rows(result.build(options.getProtocolVersion())); } private ResultMessage.Rows processResults(PartitionIterator partitions, QueryOptions options, int nowInSec, int userLimit) throws RequestValidationException { ResultSet rset = process(partitions, options, nowInSec, userLimit); return new ResultMessage.Rows(rset); } public ResultMessage.Rows executeInternal(QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException { int nowInSec = FBUtilities.nowInSeconds(); int userLimit = getLimit(options); ReadQuery query = getQuery(options, nowInSec, userLimit); int pageSize = getPageSize(options); try (ReadOrderGroup orderGroup = query.startOrderGroup()) { if (pageSize <= 0 || query.limits().count() <= pageSize) { try (PartitionIterator data = query.executeInternal(orderGroup)) { return processResults(data, options, nowInSec, userLimit); } } else { QueryPager pager = query.getPager(options.getPagingState(), options.getProtocolVersion()); return execute(Pager.forInternalQuery(pager, orderGroup), options, pageSize, nowInSec, userLimit); } } } public ResultSet process(PartitionIterator partitions, int nowInSec) throws InvalidRequestException { return process(partitions, QueryOptions.DEFAULT, nowInSec, getLimit(QueryOptions.DEFAULT)); } public String keyspace() { return cfm.ksName; } public String columnFamily() { return cfm.cfName; } /** * May be used by custom QueryHandler implementations */ public Selection getSelection() { return selection; } /** * May be used by custom QueryHandler implementations */ public StatementRestrictions getRestrictions() { return restrictions; } private ReadQuery getSliceCommands(QueryOptions options, DataLimits limit, int nowInSec) throws RequestValidationException { Collection<ByteBuffer> keys = restrictions.getPartitionKeys(options); if (keys.isEmpty()) return ReadQuery.EMPTY; ClusteringIndexFilter filter = makeClusteringIndexFilter(options); if (filter == null) return ReadQuery.EMPTY; RowFilter rowFilter = getRowFilter(options); // Note that we use the total limit for every key, which is potentially inefficient. // However, IN + LIMIT is not a very sensible choice. List<SinglePartitionReadCommand> commands = new ArrayList<>(keys.size()); for (ByteBuffer key : keys) { QueryProcessor.validateKey(key); DecoratedKey dk = cfm.decorateKey(ByteBufferUtil.clone(key)); commands.add(SinglePartitionReadCommand.create(cfm, nowInSec, queriedColumns, rowFilter, limit, dk, filter)); } return new SinglePartitionReadCommand.Group(commands, limit); } /** * Returns a read command that can be used internally to filter individual rows for materialized views. */ public SinglePartitionReadCommand internalReadForView(DecoratedKey key, int nowInSec) { QueryOptions options = QueryOptions.forInternalCalls(Collections.emptyList()); ClusteringIndexFilter filter = makeClusteringIndexFilter(options); RowFilter rowFilter = getRowFilter(options); return SinglePartitionReadCommand.create(cfm, nowInSec, queriedColumns, rowFilter, DataLimits.NONE, key, filter); } private ReadQuery getRangeCommand(QueryOptions options, DataLimits limit, int nowInSec) throws RequestValidationException { ClusteringIndexFilter clusteringIndexFilter = makeClusteringIndexFilter(options); if (clusteringIndexFilter == null) return ReadQuery.EMPTY; RowFilter rowFilter = getRowFilter(options); // The LIMIT provided by the user is the number of CQL row he wants returned. // We want to have getRangeSlice to count the number of columns, not the number of keys. AbstractBounds<PartitionPosition> keyBounds = restrictions.getPartitionKeyBounds(options); if (keyBounds == null) return ReadQuery.EMPTY; PartitionRangeReadCommand command = new PartitionRangeReadCommand(cfm, nowInSec, queriedColumns, rowFilter, limit, new DataRange(keyBounds, clusteringIndexFilter), Optional.empty()); // If there's a secondary index that the command can use, have it validate // the request parameters. Note that as a side effect, if a viable Index is // identified by the CFS's index manager, it will be cached in the command // and serialized during distribution to replicas in order to avoid performing // further lookups. command.maybeValidateIndex(); return command; } private ClusteringIndexFilter makeClusteringIndexFilter(QueryOptions options) throws InvalidRequestException { if (parameters.isDistinct) { // We need to be able to distinguish between partition having live rows and those that don't. But // doing so is not trivial since "having a live row" depends potentially on // 1) when the query is performed, due to TTLs // 2) how thing reconcile together between different nodes // so that it's hard to really optimize properly internally. So to keep it simple, we simply query // for the first row of the partition and hence uses Slices.ALL. We'll limit it to the first live // row however in getLimit(). return new ClusteringIndexSliceFilter(Slices.ALL, false); } if (restrictions.isColumnRange()) { Slices slices = makeSlices(options); if (slices == Slices.NONE && !selection.containsStaticColumns()) return null; return new ClusteringIndexSliceFilter(slices, isReversed); } else { NavigableSet<Clustering> clusterings = getRequestedRows(options); // We can have no clusterings if either we're only selecting the static columns, or if we have // a 'IN ()' for clusterings. In that case, we still want to query if some static columns are // queried. But we're fine otherwise. if (clusterings.isEmpty() && queriedColumns.fetchedColumns().statics.isEmpty()) return null; return new ClusteringIndexNamesFilter(clusterings, isReversed); } } private Slices makeSlices(QueryOptions options) throws InvalidRequestException { SortedSet<Slice.Bound> startBounds = restrictions.getClusteringColumnsBounds(Bound.START, options); SortedSet<Slice.Bound> endBounds = restrictions.getClusteringColumnsBounds(Bound.END, options); assert startBounds.size() == endBounds.size(); // The case where startBounds == 1 is common enough that it's worth optimizing if (startBounds.size() == 1) { Slice.Bound start = startBounds.first(); Slice.Bound end = endBounds.first(); return cfm.comparator.compare(start, end) > 0 ? Slices.NONE : Slices.with(cfm.comparator, Slice.make(start, end)); } Slices.Builder builder = new Slices.Builder(cfm.comparator, startBounds.size()); Iterator<Slice.Bound> startIter = startBounds.iterator(); Iterator<Slice.Bound> endIter = endBounds.iterator(); while (startIter.hasNext() && endIter.hasNext()) { Slice.Bound start = startIter.next(); Slice.Bound end = endIter.next(); // Ignore slices that are nonsensical if (cfm.comparator.compare(start, end) > 0) continue; builder.add(start, end); } return builder.build(); } private DataLimits getDataLimits(int userLimit) { int cqlRowLimit = DataLimits.NO_LIMIT; // If we aggregate, the limit really apply to the number of rows returned to the user, not to what is queried, and // since in practice we currently only aggregate at top level (we have no GROUP BY support yet), we'll only ever // return 1 result and can therefore basically ignore the user LIMIT in this case. // Whenever we support GROUP BY, we'll have to add a new DataLimits kind that knows how things are grouped and is thus // able to apply the user limit properly. // If we do post ordering we need to get all the results sorted before we can trim them. if (!selection.isAggregate() && !needsPostQueryOrdering()) cqlRowLimit = userLimit; if (parameters.isDistinct) return cqlRowLimit == DataLimits.NO_LIMIT ? DataLimits.DISTINCT_NONE : DataLimits.distinctLimits(cqlRowLimit); return cqlRowLimit == DataLimits.NO_LIMIT ? DataLimits.NONE : DataLimits.cqlLimits(cqlRowLimit); } /** * Returns the limit specified by the user. * May be used by custom QueryHandler implementations * * @return the limit specified by the user or <code>DataLimits.NO_LIMIT</code> if no value * as been specified. */ public int getLimit(QueryOptions options) { int userLimit = DataLimits.NO_LIMIT; if (limit != null) { ByteBuffer b = checkNotNull(limit.bindAndGet(options), "Invalid null value of limit"); // treat UNSET limit value as 'unlimited' if (b != UNSET_BYTE_BUFFER) { try { Int32Type.instance.validate(b); userLimit = Int32Type.instance.compose(b); checkTrue(userLimit > 0, "LIMIT must be strictly positive"); } catch (MarshalException e) { throw new InvalidRequestException("Invalid limit value"); } } } return userLimit; } private NavigableSet<Clustering> getRequestedRows(QueryOptions options) throws InvalidRequestException { // Note: getRequestedColumns don't handle static columns, but due to CASSANDRA-5762 // we always do a slice for CQL3 tables, so it's ok to ignore them here assert !restrictions.isColumnRange(); return restrictions.getClusteringColumns(options); } /** * May be used by custom QueryHandler implementations */ public RowFilter getRowFilter(QueryOptions options) throws InvalidRequestException { ColumnFamilyStore cfs = Keyspace.open(keyspace()).getColumnFamilyStore(columnFamily()); SecondaryIndexManager secondaryIndexManager = cfs.indexManager; RowFilter filter = restrictions.getRowFilter(secondaryIndexManager, options); return filter; } private ResultSet process(PartitionIterator partitions, QueryOptions options, int nowInSec, int userLimit) throws InvalidRequestException { Selection.ResultSetBuilder result = selection.resultSetBuilder(parameters.isJson); while (partitions.hasNext()) { try (RowIterator partition = partitions.next()) { processPartition(partition, options, result, nowInSec); } } ResultSet cqlRows = result.build(options.getProtocolVersion()); orderResults(cqlRows); cqlRows.trim(userLimit); return cqlRows; } public static ByteBuffer[] getComponents(CFMetaData cfm, DecoratedKey dk) { ByteBuffer key = dk.getKey(); if (cfm.getKeyValidator() instanceof CompositeType) { return ((CompositeType)cfm.getKeyValidator()).split(key); } else { return new ByteBuffer[]{ key }; } } // Used by ModificationStatement for CAS operations void processPartition(RowIterator partition, QueryOptions options, Selection.ResultSetBuilder result, int nowInSec) throws InvalidRequestException { int protocolVersion = options.getProtocolVersion(); ByteBuffer[] keyComponents = getComponents(cfm, partition.partitionKey()); Row staticRow = partition.staticRow(); // If there is no rows, then provided the select was a full partition selection // (i.e. not a 2ndary index search and there was no condition on clustering columns), // we want to include static columns and we're done. if (!partition.hasNext()) { if (!staticRow.isEmpty() && (!restrictions.usesSecondaryIndexing() || cfm.isStaticCompactTable()) && !restrictions.hasClusteringColumnsRestriction()) { result.newRow(protocolVersion); for (ColumnDefinition def : selection.getColumns()) { switch (def.kind) { case PARTITION_KEY: result.add(keyComponents[def.position()]); break; case STATIC: addValue(result, def, staticRow, nowInSec, protocolVersion); break; default: result.add((ByteBuffer)null); } } } return; } while (partition.hasNext()) { Row row = partition.next(); result.newRow(protocolVersion); // Respect selection order for (ColumnDefinition def : selection.getColumns()) { switch (def.kind) { case PARTITION_KEY: result.add(keyComponents[def.position()]); break; case CLUSTERING: result.add(row.clustering().get(def.position())); break; case REGULAR: addValue(result, def, row, nowInSec, protocolVersion); break; case STATIC: addValue(result, def, staticRow, nowInSec, protocolVersion); break; } } } } private static void addValue(Selection.ResultSetBuilder result, ColumnDefinition def, Row row, int nowInSec, int protocolVersion) { if (def.isComplex()) { // Collections are the only complex types we have so far assert def.type.isCollection() && def.type.isMultiCell(); ComplexColumnData complexData = row.getComplexColumnData(def); if (complexData == null) result.add((ByteBuffer)null); else result.add(((CollectionType)def.type).serializeForNativeProtocol(def, complexData.iterator(), protocolVersion)); } else { result.add(row.getCell(def), nowInSec); } } private boolean needsPostQueryOrdering() { // We need post-query ordering only for queries with IN on the partition key and an ORDER BY. return restrictions.keyIsInRelation() && !parameters.orderings.isEmpty(); } /** * Orders results when multiple keys are selected (using IN) */ private void orderResults(ResultSet cqlRows) { if (cqlRows.size() == 0 || !needsPostQueryOrdering()) return; Collections.sort(cqlRows.rows, orderingComparator); } public static class RawStatement extends CFStatement { public final Parameters parameters; public final List<RawSelector> selectClause; public final WhereClause whereClause; public final Term.Raw limit; public RawStatement(CFName cfName, Parameters parameters, List<RawSelector> selectClause, WhereClause whereClause, Term.Raw limit) { super(cfName); this.parameters = parameters; this.selectClause = selectClause; this.whereClause = whereClause; this.limit = limit; } public ParsedStatement.Prepared prepare() throws InvalidRequestException { return prepare(false); } public ParsedStatement.Prepared prepare(boolean forView) throws InvalidRequestException { CFMetaData cfm = ThriftValidation.validateColumnFamily(keyspace(), columnFamily()); VariableSpecifications boundNames = getBoundVariables(); Selection selection = selectClause.isEmpty() ? Selection.wildcard(cfm) : Selection.fromSelectors(cfm, selectClause); StatementRestrictions restrictions = prepareRestrictions(cfm, boundNames, selection, forView); if (parameters.isDistinct) validateDistinctSelection(cfm, selection, restrictions); Comparator<List<ByteBuffer>> orderingComparator = null; boolean isReversed = false; if (!parameters.orderings.isEmpty()) { assert !forView; verifyOrderingIsAllowed(restrictions); orderingComparator = getOrderingComparator(cfm, selection, restrictions); isReversed = isReversed(cfm); if (isReversed) orderingComparator = Collections.reverseOrder(orderingComparator); } checkNeedsFiltering(restrictions); SelectStatement stmt = new SelectStatement(cfm, boundNames.size(), parameters, selection, restrictions, isReversed, orderingComparator, prepareLimit(boundNames)); return new ParsedStatement.Prepared(stmt, boundNames, boundNames.getPartitionKeyBindIndexes(cfm)); } /** * Prepares the restrictions. * * @param cfm the column family meta data * @param boundNames the variable specifications * @param selection the selection * @return the restrictions * @throws InvalidRequestException if a problem occurs while building the restrictions */ private StatementRestrictions prepareRestrictions(CFMetaData cfm, VariableSpecifications boundNames, Selection selection, boolean forView) throws InvalidRequestException { try { return new StatementRestrictions(StatementType.SELECT, cfm, whereClause, boundNames, selection.containsOnlyStaticColumns(), selection.containsACollection(), parameters.allowFiltering, forView); } catch (UnrecognizedEntityException e) { if (containsAlias(e.entity)) throw invalidRequest("Aliases aren't allowed in the where clause ('%s')", e.relation); throw e; } } /** Returns a Term for the limit or null if no limit is set */ private Term prepareLimit(VariableSpecifications boundNames) throws InvalidRequestException { if (limit == null) return null; Term prepLimit = limit.prepare(keyspace(), limitReceiver()); prepLimit.collectMarkerSpecification(boundNames); return prepLimit; } private static void verifyOrderingIsAllowed(StatementRestrictions restrictions) throws InvalidRequestException { checkFalse(restrictions.usesSecondaryIndexing(), "ORDER BY with 2ndary indexes is not supported."); checkFalse(restrictions.isKeyRange(), "ORDER BY is only supported when the partition key is restricted by an EQ or an IN."); } private static void validateDistinctSelection(CFMetaData cfm, Selection selection, StatementRestrictions restrictions) throws InvalidRequestException { Collection<ColumnDefinition> requestedColumns = selection.getColumns(); for (ColumnDefinition def : requestedColumns) checkFalse(!def.isPartitionKey() && !def.isStatic(), "SELECT DISTINCT queries must only request partition key columns and/or static columns (not %s)", def.name); // If it's a key range, we require that all partition key columns are selected so we don't have to bother // with post-query grouping. if (!restrictions.isKeyRange()) return; for (ColumnDefinition def : cfm.partitionKeyColumns()) checkTrue(requestedColumns.contains(def), "SELECT DISTINCT queries must request all the partition key columns (missing %s)", def.name); } private void handleUnrecognizedOrderingColumn(ColumnIdentifier column) throws InvalidRequestException { checkFalse(containsAlias(column), "Aliases are not allowed in order by clause ('%s')", column); checkFalse(true, "Order by on unknown column %s", column); } private Comparator<List<ByteBuffer>> getOrderingComparator(CFMetaData cfm, Selection selection, StatementRestrictions restrictions) throws InvalidRequestException { if (!restrictions.keyIsInRelation()) return null; Map<ColumnIdentifier, Integer> orderingIndexes = getOrderingIndex(cfm, selection); List<Integer> idToSort = new ArrayList<Integer>(); List<Comparator<ByteBuffer>> sorters = new ArrayList<Comparator<ByteBuffer>>(); for (ColumnIdentifier.Raw raw : parameters.orderings.keySet()) { ColumnIdentifier identifier = raw.prepare(cfm); ColumnDefinition orderingColumn = cfm.getColumnDefinition(identifier); idToSort.add(orderingIndexes.get(orderingColumn.name)); sorters.add(orderingColumn.type); } return idToSort.size() == 1 ? new SingleColumnComparator(idToSort.get(0), sorters.get(0)) : new CompositeComparator(sorters, idToSort); } private Map<ColumnIdentifier, Integer> getOrderingIndex(CFMetaData cfm, Selection selection) throws InvalidRequestException { // If we order post-query (see orderResults), the sorted column needs to be in the ResultSet for sorting, // even if we don't // ultimately ship them to the client (CASSANDRA-4911). Map<ColumnIdentifier, Integer> orderingIndexes = new HashMap<>(); for (ColumnIdentifier.Raw raw : parameters.orderings.keySet()) { ColumnIdentifier column = raw.prepare(cfm); final ColumnDefinition def = cfm.getColumnDefinition(column); if (def == null) handleUnrecognizedOrderingColumn(column); int index = selection.getResultSetIndex(def); if (index < 0) index = selection.addColumnForOrdering(def); orderingIndexes.put(def.name, index); } return orderingIndexes; } private boolean isReversed(CFMetaData cfm) throws InvalidRequestException { Boolean[] reversedMap = new Boolean[cfm.clusteringColumns().size()]; int i = 0; for (Map.Entry<ColumnIdentifier.Raw, Boolean> entry : parameters.orderings.entrySet()) { ColumnIdentifier column = entry.getKey().prepare(cfm); boolean reversed = entry.getValue(); ColumnDefinition def = cfm.getColumnDefinition(column); if (def == null) handleUnrecognizedOrderingColumn(column); checkTrue(def.isClusteringColumn(), "Order by is currently only supported on the clustered columns of the PRIMARY KEY, got %s", column); checkTrue(i++ == def.position(), "Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY"); reversedMap[def.position()] = (reversed != def.isReversedType()); } // Check that all boolean in reversedMap, if set, agrees Boolean isReversed = null; for (Boolean b : reversedMap) { // Column on which order is specified can be in any order if (b == null) continue; if (isReversed == null) { isReversed = b; continue; } checkTrue(isReversed.equals(b), "Unsupported order by relation"); } assert isReversed != null; return isReversed; } /** If ALLOW FILTERING was not specified, this verifies that it is not needed */ private void checkNeedsFiltering(StatementRestrictions restrictions) throws InvalidRequestException { // non-key-range non-indexed queries cannot involve filtering underneath if (!parameters.allowFiltering && (restrictions.isKeyRange() || restrictions.usesSecondaryIndexing())) { // We will potentially filter data if either: // - Have more than one IndexExpression // - Have no index expression and the row filter is not the identity checkFalse(restrictions.needFiltering(), StatementRestrictions.REQUIRES_ALLOW_FILTERING_MESSAGE); } } private boolean containsAlias(final ColumnIdentifier name) { return Iterables.any(selectClause, new Predicate<RawSelector>() { public boolean apply(RawSelector raw) { return name.equals(raw.alias); } }); } private ColumnSpecification limitReceiver() { return new ColumnSpecification(keyspace(), columnFamily(), new ColumnIdentifier("[limit]", true), Int32Type.instance); } @Override public String toString() { return Objects.toStringHelper(this) .add("name", cfName) .add("selectClause", selectClause) .add("whereClause", whereClause) .add("isDistinct", parameters.isDistinct) .toString(); } } public static class Parameters { // Public because CASSANDRA-9858 public final Map<ColumnIdentifier.Raw, Boolean> orderings; public final boolean isDistinct; public final boolean allowFiltering; public final boolean isJson; public Parameters(Map<ColumnIdentifier.Raw, Boolean> orderings, boolean isDistinct, boolean allowFiltering, boolean isJson) { this.orderings = orderings; this.isDistinct = isDistinct; this.allowFiltering = allowFiltering; this.isJson = isJson; } } private static abstract class ColumnComparator<T> implements Comparator<T> { protected final int compare(Comparator<ByteBuffer> comparator, ByteBuffer aValue, ByteBuffer bValue) { if (aValue == null) return bValue == null ? 0 : -1; return bValue == null ? 1 : comparator.compare(aValue, bValue); } } /** * Used in orderResults(...) method when single 'ORDER BY' condition where given */ private static class SingleColumnComparator extends ColumnComparator<List<ByteBuffer>> { private final int index; private final Comparator<ByteBuffer> comparator; public SingleColumnComparator(int columnIndex, Comparator<ByteBuffer> orderer) { index = columnIndex; comparator = orderer; } public int compare(List<ByteBuffer> a, List<ByteBuffer> b) { return compare(comparator, a.get(index), b.get(index)); } } /** * Used in orderResults(...) method when multiple 'ORDER BY' conditions where given */ private static class CompositeComparator extends ColumnComparator<List<ByteBuffer>> { private final List<Comparator<ByteBuffer>> orderTypes; private final List<Integer> positions; private CompositeComparator(List<Comparator<ByteBuffer>> orderTypes, List<Integer> positions) { this.orderTypes = orderTypes; this.positions = positions; } public int compare(List<ByteBuffer> a, List<ByteBuffer> b) { for (int i = 0; i < positions.size(); i++) { Comparator<ByteBuffer> type = orderTypes.get(i); int columnPos = positions.get(i); int comparison = compare(type, a.get(columnPos), b.get(columnPos)); if (comparison != 0) return comparison; } return 0; } } }
clean up
src/java/org/apache/cassandra/cql3/statements/SelectStatement.java
clean up
<ide><path>rc/java/org/apache/cassandra/cql3/statements/SelectStatement.java <ide> if (acorn_pr) { <ide> // If the keyspace is acorn.*_pr, make the attributes popular in <ide> // the local datacenter. <del> final String acorn_ks_regex = String.format("%s.*_pr$", DatabaseDescriptor.getAcornOptions().keyspace_prefix); <add> final String acornKsRegex = String.format("%s.*_pr$", DatabaseDescriptor.getAcornOptions().keyspace_prefix); <ide> final String acornKsPrefix = keyspace().substring(0, keyspace().length() - 3); <ide> final String localDataCenter = DatabaseDescriptor.getEndpointSnitch().getDatacenter(FBUtilities.getBroadcastAddress()); <ide> <del> if (keyspace().matches(acorn_ks_regex)) { <add> if (keyspace().matches(acornKsRegex)) { <ide> ResultSet rs = msg.result; <ide> ResultSet.ResultMetadata rm = rs.metadata; <ide> if (rm.names == null)
Java
apache-2.0
39e655e39e6d0d2faed3b7bd8c6d06969e09f5d7
0
soundvibe/reacto
package net.soundvibe.reacto.client.commands; import com.netflix.hystrix.exception.HystrixRuntimeException; import net.soundvibe.reacto.utils.models.CustomError; import net.soundvibe.reacto.client.errors.CommandNotFound; import net.soundvibe.reacto.server.CommandRegistry; import net.soundvibe.reacto.server.VertxServer; import net.soundvibe.reacto.types.Command; import net.soundvibe.reacto.types.Event; import net.soundvibe.reacto.types.MetaData; import net.soundvibe.reacto.types.Pair; import net.soundvibe.reacto.utils.Factories; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; import io.vertx.ext.web.Router; import net.soundvibe.reacto.client.errors.ConnectionClosedUnexpectedly; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import java.net.ConnectException; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Cipolinas on 2015.12.01. */ public class CommandExecutorTest { private static final String TEST_COMMAND = "test"; private static final String TEST_COMMAND_MANY = "testMany"; private static final String TEST_FAIL_COMMAND = "testFail"; private static final String TEST_FAIL_BUT_FALLBACK_COMMAND = "testFailFallback"; private static final String LONG_TASK = "longTask"; private static final String COMMAND_WITHOUT_ARGS = "argLessCommand"; private static final String COMMAND_CUSTOM_ERROR = "commandCustomError"; private static final String COMMAND_EMIT_AND_FAIL = "emitAndFail"; private static final String MAIN_NODE = "http://localhost:8282/dist/"; private static final String FALLBACK_NODE = "http://localhost:8383/distFallback/"; private static HttpServer mainHttpServer; private static VertxServer vertxServer; private static VertxServer fallbackVertxServer; private final TestSubscriber<Event> testSubscriber = new TestSubscriber<>(); private final CommandExecutor mainNodeExecutor = CommandExecutors.webSocket(Nodes.ofMain(MAIN_NODE)); private final CommandExecutor mainNodeAndFallbackExecutor = CommandExecutors.webSocket(Nodes.ofMainAndFallback(MAIN_NODE, FALLBACK_NODE)); @BeforeClass public static void setUp() throws Exception { CommandRegistry mainCommands = CommandRegistry.of(TEST_COMMAND, cmd -> event1Arg("Called command with arg: " + cmd.get("arg")).toObservable() ) .and(TEST_COMMAND_MANY, o -> Observable.just( event1Arg("1. Called command with arg: " + o.get("arg")), event1Arg("2. Called command with arg: " + o.get("arg")), event1Arg("3. Called command with arg: " + o.get("arg")) )) .and(TEST_FAIL_COMMAND, o -> Observable.error(new RuntimeException("failed"))) .and(TEST_FAIL_BUT_FALLBACK_COMMAND, o -> Observable.error(new RuntimeException("failed"))) .and(COMMAND_WITHOUT_ARGS, o -> event1Arg("ok").toObservable()) .and(COMMAND_CUSTOM_ERROR, o -> Observable.error(new CustomError(o.get("arg")))) .and(COMMAND_EMIT_AND_FAIL, command -> Observable.create(subscriber -> { subscriber.onNext(Event.create("ok")); try { Thread.sleep(1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } })) .and(LONG_TASK, interval -> Observable.create(subscriber -> { try { Thread.sleep(Integer.valueOf(interval.get("arg"))); subscriber.onNext(event1Arg("ok")); subscriber.onCompleted(); } catch (InterruptedException e) { System.out.println(e.getMessage()); subscriber.onError(e); } })) ; CommandRegistry fallbackCommands = CommandRegistry.of(TEST_FAIL_BUT_FALLBACK_COMMAND, o -> event1Arg("Recovered: " + o.get("arg")).toObservable()); Vertx vertx = Vertx.vertx(); mainHttpServer = vertx.createHttpServer(new HttpServerOptions() .setPort(8282) .setSsl(false) .setReuseAddress(true)); HttpServer fallbackHttpServer = vertx.createHttpServer(new HttpServerOptions() .setPort(8383) .setSsl(false) .setReuseAddress(true)); vertxServer = new VertxServer(Router.router(vertx), mainHttpServer, "dist/", mainCommands); fallbackVertxServer = new VertxServer(Router.router(vertx), fallbackHttpServer, "distFallback/", fallbackCommands); fallbackVertxServer.start(); vertxServer.start(); } @AfterClass public static void tearDown() throws Exception { vertxServer.stop(); fallbackVertxServer.stop(); } private static Event event1Arg(String value) { return Event.create("testEvent", MetaData.of("arg", value)); } private static Command command1Arg(String name, String value) { return Command.create(name, Pair.of("arg", value)); } @Test public void shouldExecuteCommand() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_COMMAND, "foo")) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("Called command with arg: foo")); } @Test public void shouldCallCommandAndReceiveMultipleEvents() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_COMMAND_MANY, "bar")) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValues( event1Arg("1. Called command with arg: bar"), event1Arg("2. Called command with arg: bar"), event1Arg("3. Called command with arg: bar") ); } @Test public void shouldMainFailAndNoFallbackAvailable() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_FAIL_COMMAND, "foo")) .subscribe(testSubscriber); assertActualHystrixError(RuntimeException.class, e -> assertEquals("failed", e.getMessage())); } @Test public void shouldMainFailAndFallbackSucceed() throws Exception { mainNodeAndFallbackExecutor.execute(command1Arg(TEST_FAIL_BUT_FALLBACK_COMMAND, "foo")) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("Recovered: foo")); } @Test public void shouldComposeDifferentCommands() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_COMMAND, "foo")) .mergeWith(mainNodeExecutor.execute(command1Arg(TEST_COMMAND_MANY, "bar"))) .observeOn(Schedulers.computation()) .subscribeOn(Schedulers.computation()) .subscribe(testSubscriber); assertCompletedSuccessfully(); List<Event> onNextEvents = testSubscriber.getOnNextEvents(); assertEquals("Should be 4 elements", 4, onNextEvents.size()); assertTrue(onNextEvents.contains(event1Arg("1. Called command with arg: bar"))); assertTrue(onNextEvents.contains(event1Arg("2. Called command with arg: bar"))); assertTrue(onNextEvents.contains(event1Arg("3. Called command with arg: bar"))); assertTrue(onNextEvents.contains(event1Arg("Called command with arg: foo"))); } @Test public void shouldFailAfterHystrixTimeout() throws Exception { CommandExecutor sut = CommandExecutors.webSocket(Nodes.ofMain(MAIN_NODE), CommandExecutors.DEFAULT_EXECUTION_TIMEOUT); sut.execute(command1Arg(LONG_TASK, "5000")) .subscribe(testSubscriber); assertActualHystrixError(TimeoutException.class, e -> assertEquals("java.util.concurrent.TimeoutException", e.toString())); } @Test public void shouldFailWhenCommandIsInvokedWithInvalidArgument() throws Exception { mainNodeExecutor.execute(command1Arg(LONG_TASK, "foo")) .subscribe(testSubscriber); assertActualHystrixError(NumberFormatException.class, e -> assertEquals("For input string: \"foo\"", e.getMessage())); } @Test public void shouldFailAndReceiveCustomExceptionFromCommand() throws Exception { mainNodeExecutor.execute(command1Arg(COMMAND_CUSTOM_ERROR, "foo")) .subscribe(testSubscriber); assertActualHystrixError(CustomError.class, customError -> assertEquals("foo", customError.data)); } @Test public void shouldCallCommandWithoutArgs() throws Exception { mainNodeExecutor.execute(Command.create(COMMAND_WITHOUT_ARGS)) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("ok")); } @Test public void shouldFailWhenCommandExecutorIsInaccessible() throws Exception { CommandExecutor sut = CommandExecutors.webSocket(Nodes.ofMain("http://localhost:45689/foo/")); sut.execute(command1Arg(TEST_COMMAND, "foo")) .subscribe(testSubscriber); assertActualHystrixError(ConnectException.class, e -> assertFalse(e.getMessage().isEmpty())); } @Test public void shouldExecuteHugeCommandEntity() throws Exception { String commandWithHugePayload = createDataSize(100_000); mainNodeExecutor.execute(command1Arg(TEST_COMMAND, commandWithHugePayload)) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("Called command with arg: " + commandWithHugePayload)); } @Test public void shouldFailWithCommandNotFoundWhenCommandIsNotAvailableOnTheServer() throws Exception { mainNodeExecutor.execute(Command.create("someUnknownCommand")) .subscribe(testSubscriber); assertActualHystrixError(CommandNotFound.class, commandNotFound -> assertEquals("Command not found: someUnknownCommand", commandNotFound.getMessage())); } @Test public void shouldReceiveOneEventAndThenFail() throws Exception { HttpServer server = Factories.vertx().createHttpServer(new HttpServerOptions() .setPort(8183) .setSsl(false) .setReuseAddress(true)); final VertxServer reactoServer = new VertxServer(Router.router(Factories.vertx()), server, "distTest/", CommandRegistry.of(COMMAND_EMIT_AND_FAIL, command -> Observable.create(subscriber -> { subscriber.onNext(Event.create("ok")); try { Thread.sleep(1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } }))); final CommandExecutor executor = CommandExecutors.webSocket(Nodes.ofMain("http://localhost:8183/distTest/")); reactoServer.start(); executor.execute(Command.create(COMMAND_EMIT_AND_FAIL)) .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(500L, TimeUnit.MILLISECONDS); testSubscriber.assertValue(Event.create("ok")); //shut down main node reactoServer.stop(); assertActualHystrixError(ConnectionClosedUnexpectedly.class, connectionClosedUnexpectedly -> assertTrue(connectionClosedUnexpectedly.getMessage() .startsWith("WebSocket connection closed without completion for command: "))); } private void assertCompletedSuccessfully() { testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoErrors(); testSubscriber.assertCompleted(); } @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "unchecked"}) private <T extends Throwable> void assertActualHystrixError(Class<T> expected, Consumer<T> errorChecker) { testSubscriber.awaitTerminalEvent(); testSubscriber.assertNotCompleted(); final List<Throwable> onErrorEvents = testSubscriber.getOnErrorEvents(); assertEquals("Should be one error", 1, onErrorEvents.size()); final Throwable throwable = onErrorEvents.get(0); assertEquals("Should be HystrixRuntimeException", HystrixRuntimeException.class, throwable.getClass()); final Throwable actualCause = throwable.getCause(); assertEquals(expected, actualCause.getClass()); errorChecker.accept((T) actualCause); } private static String createDataSize(int msgSize) { StringBuilder sb = new StringBuilder(msgSize); for (int i=0; i<msgSize; i++) { sb.append('a'); } return sb.toString(); } }
src/test/java/net/soundvibe/reacto/client/commands/CommandExecutorTest.java
package net.soundvibe.reacto.client.commands; import com.netflix.hystrix.exception.HystrixRuntimeException; import net.soundvibe.reacto.utils.models.CustomError; import net.soundvibe.reacto.client.errors.CommandNotFound; import net.soundvibe.reacto.server.CommandRegistry; import net.soundvibe.reacto.server.VertxServer; import net.soundvibe.reacto.types.Command; import net.soundvibe.reacto.types.Event; import net.soundvibe.reacto.types.MetaData; import net.soundvibe.reacto.types.Pair; import net.soundvibe.reacto.utils.Factories; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; import io.vertx.ext.web.Router; import net.soundvibe.reacto.client.errors.ConnectionClosedUnexpectedly; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import java.net.ConnectException; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Cipolinas on 2015.12.01. */ public class CommandExecutorTest { private static final String TEST_COMMAND = "test"; private static final String TEST_COMMAND_MANY = "testMany"; private static final String TEST_FAIL_COMMAND = "testFail"; private static final String TEST_FAIL_BUT_FALLBACK_COMMAND = "testFailFallback"; private static final String LONG_TASK = "longTask"; private static final String COMMAND_WITHOUT_ARGS = "argLessCommand"; private static final String COMMAND_CUSTOM_ERROR = "commandCustomError"; private static final String COMMAND_EMIT_AND_FAIL = "emitAndFail"; private static final String MAIN_NODE = "http://localhost:8282/dist/"; private static final String FALLBACK_NODE = "http://localhost:8383/distFallback/"; private static HttpServer mainHttpServer; private static VertxServer vertxServer; private static VertxServer fallbackVertxServer; private final TestSubscriber<Event> testSubscriber = new TestSubscriber<>(); private final CommandExecutor mainNodeExecutor = CommandExecutors.webSocket(Nodes.ofMain(MAIN_NODE)); private final CommandExecutor mainNodeAndFallbackExecutor = CommandExecutors.webSocket(Nodes.ofMainAndFallback(MAIN_NODE, FALLBACK_NODE)); @BeforeClass public static void setUp() throws Exception { CommandRegistry mainCommands = CommandRegistry.of(TEST_COMMAND, cmd -> event1Arg("Called command with arg: " + cmd.get("arg")).toObservable() ) .and(TEST_COMMAND_MANY, o -> Observable.just( event1Arg("1. Called command with arg: " + o.get("arg")), event1Arg("2. Called command with arg: " + o.get("arg")), event1Arg("3. Called command with arg: " + o.get("arg")) )) .and(TEST_FAIL_COMMAND, o -> Observable.error(new RuntimeException("failed"))) .and(TEST_FAIL_BUT_FALLBACK_COMMAND, o -> Observable.error(new RuntimeException("failed"))) .and(COMMAND_WITHOUT_ARGS, o -> event1Arg("ok").toObservable()) .and(COMMAND_CUSTOM_ERROR, o -> Observable.error(new CustomError(o.get("arg")))) .and(COMMAND_EMIT_AND_FAIL, command -> Observable.create(subscriber -> { subscriber.onNext(Event.create("ok")); try { Thread.sleep(1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } })) .and(LONG_TASK, interval -> Observable.create(subscriber -> { try { Thread.sleep(Integer.valueOf(interval.get("arg"))); subscriber.onNext(event1Arg("ok")); subscriber.onCompleted(); } catch (InterruptedException e) { System.out.println(e.getMessage()); subscriber.onError(e); } })) ; CommandRegistry fallbackCommands = CommandRegistry.of(TEST_FAIL_BUT_FALLBACK_COMMAND, o -> event1Arg("Recovered: " + o.get("arg")).toObservable()); Vertx vertx = Factories.vertx(); mainHttpServer = vertx.createHttpServer(new HttpServerOptions() .setPort(8282) .setSsl(false) .setReuseAddress(true)); HttpServer fallbackHttpServer = vertx.createHttpServer(new HttpServerOptions() .setPort(8383) .setSsl(false) .setReuseAddress(true)); vertxServer = new VertxServer(Router.router(vertx), mainHttpServer, "dist/", mainCommands); fallbackVertxServer = new VertxServer(Router.router(vertx), fallbackHttpServer, "distFallback/", fallbackCommands); fallbackVertxServer.start(); vertxServer.start(); } @AfterClass public static void tearDown() throws Exception { vertxServer.stop(); fallbackVertxServer.stop(); } private static Event event1Arg(String value) { return Event.create("testEvent", MetaData.of("arg", value)); } private static Command command1Arg(String name, String value) { return Command.create(name, Pair.of("arg", value)); } @Test public void shouldExecuteCommand() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_COMMAND, "foo")) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("Called command with arg: foo")); } @Test public void shouldCallCommandAndReceiveMultipleEvents() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_COMMAND_MANY, "bar")) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValues( event1Arg("1. Called command with arg: bar"), event1Arg("2. Called command with arg: bar"), event1Arg("3. Called command with arg: bar") ); } @Test public void shouldMainFailAndNoFallbackAvailable() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_FAIL_COMMAND, "foo")) .subscribe(testSubscriber); assertActualHystrixError(RuntimeException.class, e -> assertEquals("failed", e.getMessage())); } @Test public void shouldMainFailAndFallbackSucceed() throws Exception { mainNodeAndFallbackExecutor.execute(command1Arg(TEST_FAIL_BUT_FALLBACK_COMMAND, "foo")) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("Recovered: foo")); } @Test public void shouldComposeDifferentCommands() throws Exception { mainNodeExecutor.execute(command1Arg(TEST_COMMAND, "foo")) .mergeWith(mainNodeExecutor.execute(command1Arg(TEST_COMMAND_MANY, "bar"))) .observeOn(Schedulers.computation()) .subscribeOn(Schedulers.computation()) .subscribe(testSubscriber); assertCompletedSuccessfully(); List<Event> onNextEvents = testSubscriber.getOnNextEvents(); assertEquals("Should be 4 elements", 4, onNextEvents.size()); assertTrue(onNextEvents.contains(event1Arg("1. Called command with arg: bar"))); assertTrue(onNextEvents.contains(event1Arg("2. Called command with arg: bar"))); assertTrue(onNextEvents.contains(event1Arg("3. Called command with arg: bar"))); assertTrue(onNextEvents.contains(event1Arg("Called command with arg: foo"))); } @Test public void shouldFailAfterHystrixTimeout() throws Exception { CommandExecutor sut = CommandExecutors.webSocket(Nodes.ofMain(MAIN_NODE), CommandExecutors.DEFAULT_EXECUTION_TIMEOUT); sut.execute(command1Arg(LONG_TASK, "5000")) .subscribe(testSubscriber); assertActualHystrixError(TimeoutException.class, e -> assertEquals("java.util.concurrent.TimeoutException", e.toString())); } @Test public void shouldFailWhenCommandIsInvokedWithInvalidArgument() throws Exception { mainNodeExecutor.execute(command1Arg(LONG_TASK, "foo")) .subscribe(testSubscriber); assertActualHystrixError(NumberFormatException.class, e -> assertEquals("For input string: \"foo\"", e.getMessage())); } @Test public void shouldFailAndReceiveCustomExceptionFromCommand() throws Exception { mainNodeExecutor.execute(command1Arg(COMMAND_CUSTOM_ERROR, "foo")) .subscribe(testSubscriber); assertActualHystrixError(CustomError.class, customError -> assertEquals("foo", customError.data)); } @Test public void shouldCallCommandWithoutArgs() throws Exception { mainNodeExecutor.execute(Command.create(COMMAND_WITHOUT_ARGS)) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("ok")); } @Test public void shouldFailWhenCommandExecutorIsInaccessible() throws Exception { CommandExecutor sut = CommandExecutors.webSocket(Nodes.ofMain("http://localhost:45689/foo/")); sut.execute(command1Arg(TEST_COMMAND, "foo")) .subscribe(testSubscriber); assertActualHystrixError(ConnectException.class, e -> assertFalse(e.getMessage().isEmpty())); } @Test public void shouldExecuteHugeCommandEntity() throws Exception { String commandWithHugePayload = createDataSize(100_000); mainNodeExecutor.execute(command1Arg(TEST_COMMAND, commandWithHugePayload)) .subscribe(testSubscriber); assertCompletedSuccessfully(); testSubscriber.assertValue(event1Arg("Called command with arg: " + commandWithHugePayload)); } @Test public void shouldFailWithCommandNotFoundWhenCommandIsNotAvailableOnTheServer() throws Exception { mainNodeExecutor.execute(Command.create("someUnknownCommand")) .subscribe(testSubscriber); assertActualHystrixError(CommandNotFound.class, commandNotFound -> assertEquals("Command not found: someUnknownCommand", commandNotFound.getMessage())); } @Test public void shouldReceiveOneEventAndThenFail() throws Exception { HttpServer server = Factories.vertx().createHttpServer(new HttpServerOptions() .setPort(8183) .setSsl(false) .setReuseAddress(true)); final VertxServer reactoServer = new VertxServer(Router.router(Factories.vertx()), server, "distTest/", CommandRegistry.of(COMMAND_EMIT_AND_FAIL, command -> Observable.create(subscriber -> { subscriber.onNext(Event.create("ok")); try { Thread.sleep(1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } }))); final CommandExecutor executor = CommandExecutors.webSocket(Nodes.ofMain("http://localhost:8183/distTest/")); reactoServer.start(); executor.execute(Command.create(COMMAND_EMIT_AND_FAIL)) .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(500L, TimeUnit.MILLISECONDS); testSubscriber.assertValue(Event.create("ok")); //shut down main node reactoServer.stop(); assertActualHystrixError(ConnectionClosedUnexpectedly.class, connectionClosedUnexpectedly -> assertTrue(connectionClosedUnexpectedly.getMessage() .startsWith("WebSocket connection closed without completion for command: "))); } private void assertCompletedSuccessfully() { testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoErrors(); testSubscriber.assertCompleted(); } @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "unchecked"}) private <T extends Throwable> void assertActualHystrixError(Class<T> expected, Consumer<T> errorChecker) { testSubscriber.awaitTerminalEvent(); testSubscriber.assertNotCompleted(); final List<Throwable> onErrorEvents = testSubscriber.getOnErrorEvents(); assertEquals("Should be one error", 1, onErrorEvents.size()); final Throwable throwable = onErrorEvents.get(0); assertEquals("Should be HystrixRuntimeException", HystrixRuntimeException.class, throwable.getClass()); final Throwable actualCause = throwable.getCause(); assertEquals(expected, actualCause.getClass()); errorChecker.accept((T) actualCause); } private static String createDataSize(int msgSize) { StringBuilder sb = new StringBuilder(msgSize); for (int i=0; i<msgSize; i++) { sb.append('a'); } return sb.toString(); } }
use separate vertx instance for itests
src/test/java/net/soundvibe/reacto/client/commands/CommandExecutorTest.java
use separate vertx instance for itests
<ide><path>rc/test/java/net/soundvibe/reacto/client/commands/CommandExecutorTest.java <ide> CommandRegistry fallbackCommands = CommandRegistry.of(TEST_FAIL_BUT_FALLBACK_COMMAND, <ide> o -> event1Arg("Recovered: " + o.get("arg")).toObservable()); <ide> <del> Vertx vertx = Factories.vertx(); <add> Vertx vertx = Vertx.vertx(); <ide> mainHttpServer = vertx.createHttpServer(new HttpServerOptions() <ide> .setPort(8282) <ide> .setSsl(false)
Java
apache-2.0
89fdeb08e1b327d6a6b1ffa75cc7a73757b1f4a6
0
rsudev/c-geo-opensource,rsudev/c-geo-opensource,cgeo/cgeo,cgeo/cgeo,rsudev/c-geo-opensource,cgeo/cgeo,tobiasge/cgeo,tobiasge/cgeo,tobiasge/cgeo,cgeo/cgeo
package cgeo.geocaching.filters.core; import cgeo.geocaching.log.LogType; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.storage.SqlBuilder; import cgeo.geocaching.utils.CollectionStream; import cgeo.geocaching.utils.expressions.ExpressionConfig; import java.util.Arrays; import org.apache.commons.lang3.BooleanUtils; public class FavoritesGeocacheFilter extends NumberRangeGeocacheFilter<Float> { private static final String CONFIG_KEY_PERCENTAGE = "percentage"; private boolean percentage = false; public FavoritesGeocacheFilter() { super(Float::valueOf); } public boolean isPercentage() { return percentage; } public void setPercentage(final boolean percentage) { this.percentage = percentage; } @Override public Float getValue(final Geocache cache) { if (!percentage) { return (float) cache.getFavoritePoints(); } final int rawFindsCount = cache.getFindsCount(); return rawFindsCount == 0 ? (float) cache.getFavoritePoints() : ((float) cache.getFavoritePoints()) / rawFindsCount; } @Override protected String getSqlColumnName() { return "favourite_cnt"; } @Override public void addToSql(final SqlBuilder sqlBuilder) { if (!percentage) { super.addToSql(sqlBuilder); } else { final String newTableId = sqlBuilder.getNewTableId(); sqlBuilder.addJoin("LEFT JOIN (" + getGroupClause(sqlBuilder.getNewTableId()) + ") " + newTableId + " ON " + sqlBuilder.getMainTableId() + ".geocode = " + newTableId + ".geocode"); addRangeToSqlBuilder(sqlBuilder, getFavoritePercentageStatement(sqlBuilder.getMainTableId() + ".favourite_cnt", newTableId + ".find_count")); } } private static String getGroupClause(final String tid) { final String logIds = CollectionStream.of(Arrays.asList(LogType.getFoundLogIds())).toJoinedString(","); return "select " + tid + ".geocode, sum(count) as find_count from cg_logCount " + tid + " where " + tid + ".type in (" + logIds + ") group by " + tid + ".geocode"; } private static String getFavoritePercentageStatement(final String favCountColumn, final String findCountColumn) { return "(CAST(" + favCountColumn + " AS REAL) / CASE WHEN " + findCountColumn + " IS NULL THEN 1 WHEN " + findCountColumn + " = 0 THEN 1 ELSE " + findCountColumn + " END)"; } @Override public void setConfig(final ExpressionConfig config) { super.setConfig(config); percentage = config.getFirstValue(CONFIG_KEY_PERCENTAGE, false, BooleanUtils::toBoolean); } @Override public ExpressionConfig getConfig() { final ExpressionConfig config = super.getConfig(); config.putList(CONFIG_KEY_PERCENTAGE, Boolean.toString(percentage)); return config; } @Override protected String getUserDisplayableConfig() { if (percentage) { return (getMinRangeValue() == null ? "*" : (Math.round(getMinRangeValue() * 100)) + "%") + "-" + (getMaxRangeValue() == null ? "*" : (Math.round(getMaxRangeValue() * 100)) + "%"); } return super.getUserDisplayableConfig(); } }
main/src/cgeo/geocaching/filters/core/FavoritesGeocacheFilter.java
package cgeo.geocaching.filters.core; import cgeo.geocaching.log.LogType; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.storage.SqlBuilder; import cgeo.geocaching.utils.CollectionStream; import cgeo.geocaching.utils.expressions.ExpressionConfig; import java.util.Arrays; import org.apache.commons.lang3.BooleanUtils; public class FavoritesGeocacheFilter extends NumberRangeGeocacheFilter<Float> { private static final String CONFIG_KEY_PERCENTAGE = "percentage"; private boolean percentage = false; public FavoritesGeocacheFilter() { super(Float::valueOf); } public boolean isPercentage() { return percentage; } public void setPercentage(final boolean percentage) { this.percentage = percentage; } @Override public Float getValue(final Geocache cache) { if (!percentage) { return (float) cache.getFavoritePoints(); } final int rawFindsCount = cache.getFindsCount(); return rawFindsCount == 0 ? (float) cache.getFavoritePoints() : ((float) cache.getFavoritePoints()) / rawFindsCount; } @Override protected String getSqlColumnName() { return "favourite_cnt"; } @Override public void addToSql(final SqlBuilder sqlBuilder) { if (!percentage) { super.addToSql(sqlBuilder); } else { final String newTableId = sqlBuilder.getNewTableId(); sqlBuilder.addJoin("LEFT JOIN (" + getGroupClause(sqlBuilder.getNewTableId()) + ") " + newTableId + " ON " + sqlBuilder.getMainTableId() + ".geocode = " + newTableId + ".geocode"); addRangeToSqlBuilder(sqlBuilder, getFavoritePercentageStatement(sqlBuilder.getMainTableId() + ".favourite_cnt", newTableId + ".find_count")); } } private static String getGroupClause(final String tid) { final String logIds = CollectionStream.of(Arrays.asList(LogType.getFoundLogIds())).toJoinedString(","); return "select " + tid + ".geocode, sum(count) as find_count from cg_logCount " + tid + " where " + tid + ".type in (" + logIds + ") group by " + tid + ".geocode"; } private static String getFavoritePercentageStatement(final String favCountColumn, final String findCountColumn) { return "(CAST(" + favCountColumn + " AS REAL) / CASE WHEN " + findCountColumn + " IS NULL THEN 1 WHEN " + findCountColumn + " = 0 THEN 1 ELSE " + findCountColumn + " END)"; } @Override public void setConfig(final ExpressionConfig config) { super.setConfig(config); percentage = config.getFirstValue(CONFIG_KEY_PERCENTAGE, false, BooleanUtils::toBoolean); } @Override public ExpressionConfig getConfig() { final ExpressionConfig config = super.getConfig(); config.putList(CONFIG_KEY_PERCENTAGE, Boolean.toString(percentage)); return config; } @Override protected String getUserDisplayableConfig() { return super.getUserDisplayableConfig() + (percentage ? "%:" : ""); } }
fix #11154: make filter by fav percentage better visible (#11158)
main/src/cgeo/geocaching/filters/core/FavoritesGeocacheFilter.java
fix #11154: make filter by fav percentage better visible (#11158)
<ide><path>ain/src/cgeo/geocaching/filters/core/FavoritesGeocacheFilter.java <ide> <ide> @Override <ide> protected String getUserDisplayableConfig() { <del> return super.getUserDisplayableConfig() + (percentage ? "%:" : ""); <add> if (percentage) { <add> return (getMinRangeValue() == null ? "*" : (Math.round(getMinRangeValue() * 100)) + "%") + "-" + (getMaxRangeValue() == null ? "*" : (Math.round(getMaxRangeValue() * 100)) + "%"); <add> } <add> return super.getUserDisplayableConfig(); <ide> } <ide> <ide>
JavaScript
mit
12ad782f040e251417696167bfb360105c482dc9
0
mephraim/candid_canvas
var CandidCanvas = CandidCanvas || {}; (function() { /** * The default time period (in milliseconds) between each tick * of the animation * * @const **/ var DEFAULT_FRAME_DURATION = 25; /** * Creates a new CandidCanvas Animator and attaches it to the * Canvas element. * * @param {HTMLCanvasElement} canvas The canvas element that * the animator will attach itself to * @param {Object} options (optional) An options hash (not currently used) **/ CandidCanvas.createAnimator = function(canvas, options) { return new Animator(canvas, options); }; /** * An Animator attaches itself to a canvas element and handles * the playing, pausing, looping and resetting of animator * scenes that act on the canvas element. * * @private * @constructor * @param {HTMLCanvasElement} canvas The canvas element that * the animator will attach itself to **/ var Animator = function(canvas) { _initContext(this, canvas); _initScenes(this); _initCurrentScene(this); }; /** * Adds a new CandidCanvas Scene to the animator. The scene will * be executed after any other scenes that have been added to the * animator. * * @param {Scene} scene a Scene to add to the Animator * @see addScenes **/ Animator.prototype.addScene = function(scene) { this.scenes().push(scene); }; /** * Adds a list of CandidCanvas Scenes to the animator. Each scene * will be added to the animator in the order that it was passed in * to the addScenes method. * * @param {Scene} scenes An unlimited list of scenes to add to the animator **/ Animator.prototype.addScenes = function() { for(var i = 0, len = arguments.length; i < len; i++) { this.addScene(arguments[i]); } }; /** * Start playing the animator. If the animator was paused, * continue playing where the animator left off. Otherwise, * start from the beginning. A call to the function is ignored * if the animator is already playing. * * @param {Object} (optional) options an object hash of options * Valid options: * - loop: if true, the animator will loop **/ Animator.prototype.play = function(options) { if (this._currentlyPlaying) { return; } _initForPlay(this, options || {}); _startFrameTimer(this); }; /** * The same as play, but the animator will loop * @see play **/ Animator.prototype.loop = function(options) { options = options || {}; options.loop = true; this.play(options); }; /** * Stop the current animator, but retain the current * animator's state. **/ Animator.prototype.pause = function() { this._currentlyPlaying = false; clearInterval(this._playTimer); }; /** * Stop the current animator and reset all state properties **/ Animator.prototype.reset = function() { _resetAnimator(this); }; /** * @private **/ function _initContext(anim, canvas) { var context = canvas.getContext('2d'); /** * @return {CanvasRenderingContext2D} the attached canvas context * for the animator **/ anim.context = function() { return context; }; } /** * @private **/ function _initScenes(anim) { var scenes = []; /* * @return {Array} the scenes for the animator **/ anim.scenes = function() { return scenes; }; /** * Clear all of the animator's scenes **/ anim.clearScenes = function() { scenes = []; }; } /** * @private **/ function _initCurrentScene(anim) { var currentScene; /** * If no parameters are passed in, returns the current scene. * Otherwise sets the current scene to the scene parameter. * * @param {Scene} scene (optional) the scene to be set as the current scene * @return {Scene} the current scene for the animator **/ anim.currentScene = function(scene) { if (arguments.length > 0) { currentScene = scene; } return currentScene; }; /** * Set the current scene back to null **/ anim.clearCurrentScene = function() { if (currentScene) { currentScene.timeElapsed(0); currentScene = null; } }; } /** * Sets up the animator for playing by making sure that the state * of the animator is maintained after an animator is paused. * * @private * @param {Animator} anim The animator * @param {Object} options A set of options carried over from the play * function **/ function _initForPlay(anim, options) { anim._currentlyPlaying = true; anim._looping = anim._looping || options.loop; // Load in the remaining scenes (after a pause) // or copy the entire the scenes array if there // are no remaining scenes anim._remainingScenes = anim._remainingScenes || anim.scenes().concat(); // Load in the Scenecurrent scene (after a pause) // or shift the next scene from the remaining scenes anim.currentScene(anim.currentScene() || anim._remainingScenes.shift()); // Set the amount of time elapsed for the current scene (after a pause) // or start at 0 for the next scene var currentScene = anim.currentScene(); currentScene.timeElapsed(currentScene.timeElapsed() || 0); } /** * The real meat of the animator. Starts a timer that will run * each tick of the animator. For each tick the animator needs * to run through each element of the current scene. * * @private * @param {Animator} anim an Animator **/ function _startFrameTimer(anim) { var frameDuration = DEFAULT_FRAME_DURATION; anim._playTimer = setInterval(function() { // if all of the scenes have been run if (!anim.currentScene()) { // if the animator should be looping copy the scenes array again // and load the first scene if (anim._looping) { anim._remainingScenes = anim.scenes().concat(); anim.currentScene(anim._remainingScenes.shift()); anim.currentScene().timeElapsed(0); } // otherwise, stop the timer, reset the values and return else { _resetAnimator(anim); return; } } var timeElapsedForCurrentScene = anim.currentScene().timeElapsed(); // if the current scene is still running then run another frame if (timeElapsedForCurrentScene < anim.currentScene().duration) { _runCurrentScene(anim); anim.currentScene().timeElapsed(timeElapsedForCurrentScene + frameDuration); // otherwise, load the next scene } else { var currentScene = anim.currentScene(); currentScene.oncomplete(); currentScene.timeElapsed(0); anim.currentScene(anim._remainingScenes.shift()); } }, frameDuration); } /** * Takes a Scene and runs through each of the elements of the scene. * If no time has elapsed for the scene yet, the scene's onstart handler * will be called. * * @private * @param {Animator} anim the Animator that the scene belongs to * @param {Scene} scene a Scene to run through * @param {Integer} timeElapsed the amount of time that has elapsed for the scene **/ function _runCurrentScene(anim) { var scene = anim.currentScene(); if (scene.timeElapsed() < 1) { scene.onstart(); } var elements = scene.elements; for(var i = 0, len = elements.length; i < len; i++) { elements[i](anim); } } /** * Resets the animator's timer and clears any state properties * that were store for the Animator * * @private * @param {Animator} anim an Animator to reset **/ function _resetAnimator(anim) { clearInterval(anim._playTimer); delete anim._currentlyPlaying; delete anim._looping; delete anim._playTimer; delete anim._remainingScenes; anim.clearCurrentScene(); } })();
lib/animator.js
var CandidCanvas = CandidCanvas || {}; (function() { /** * The default time period (in milliseconds) between each tick * of the animation * * @const **/ var DEFAULT_FRAME_DURATION = 25; /** * Creates a new CandidCanvas Animator and attaches it to the * Canvas element. * * @param {HTMLCanvasElement} canvas The canvas element that * the animator will attach itself to * @param {Object} options (optional) An options hash (not currently used) **/ CandidCanvas.createAnimator = function(canvas, options) { return new Animator(canvas, options); }; /** * An Animator attaches itself to a canvas element and handles * the playing, pausing, looping and resetting of animator * scenes that act on the canvas element. * * @private * @constructor * @param {HTMLCanvasElement} canvas The canvas element that * the animator will attach itself to **/ var Animator = function(canvas) { _initContext(this, canvas); _initScenes(this); _initCurrentScene(this); }; /** * Adds a new CandidCanvas Scene to the animator. The scene will * be executed after any other scenes that have been added to the * animator. * * @param {Scene} scene a Scene to add to the Animator * @see addScenes **/ Animator.prototype.addScene = function(scene) { this.scenes().push(scene); }; /** * Adds a list of CandidCanvas Scenes to the animator. Each scene * will be added to the animator in the order that it was passed in * to the addScenes method. * * @param {Scene} scenes An unlimited list of scenes to add to the animator **/ Animator.prototype.addScenes = function() { for(var i = 0, len = arguments.length; i < len; i++) { this.addScene(arguments[i]); } }; /** * Start playing the animator. If the animator was paused, * continue playing where the animator left off. Otherwise, * start from the beginning. A call to the function is ignored * if the animator is already playing. * * @param {Object} (optional) options an object hash of options * Valid options: * - loop: if true, the animator will loop **/ Animator.prototype.play = function(options) { if (this._currentlyPlaying) { return; } _initForPlay(this, options || {}); _startFrameTimer(this); }; /** * The same as play, but the animator will loop * @see play **/ Animator.prototype.loop = function(options) { options = options || {}; options.loop = true; this.play(options); }; /** * Stop the current animator, but retain the current * animator's state. **/ Animator.prototype.pause = function() { this._currentlyPlaying = false; clearInterval(this._playTimer); }; /** * Stop the current animator and reset all state properties **/ Animator.prototype.reset = function() { _resetAnimator(this); }; /** * @private **/ function _initContext(anim, canvas) { var context = canvas.getContext('2d'); /** * @return {CanvasRenderingContext2D} the attached canvas context * for the animator **/ anim.context = function() { return context; }; } /** * @private **/ function _initScenes(anim) { var scenes = []; /* * @return {Array} the scenes for the animator **/ anim.scenes = function() { return scenes; }; /** * Clear all of the animator's scenes **/ anim.clearScenes = function() { scenes = []; }; } /** * @private **/ function _initCurrentScene(anim) { var currentScene; /** * If no parameters are passed in, returns the current scene. * Otherwise sets the current scene to the scene parameter. * * @param {Scene} scene (optional) the scene to be set as the current scene * @return {Scene} the current scene for the animator **/ anim.currentScene = function(scene) { if (arguments.length > 0) { currentScene = scene; } return currentScene; }; /** * Set the current scene back to null **/ anim.clearCurrentScene = function() { current.timeElapsed(0); currentScene = null; }; } /** * Sets up the animator for playing by making sure that the state * of the animator is maintained after an animator is paused. * * @private * @param {Animator} anim The animator * @param {Object} options A set of options carried over from the play * function **/ function _initForPlay(anim, options) { anim._currentlyPlaying = true; anim._looping = anim._looping || options.loop; // Load in the remaining scenes (after a pause) // or copy the entire the scenes array if there // are no remaining scenes anim._remainingScenes = anim._remainingScenes || anim.scenes().concat(); // Load in the current scene (after a pause) // or shift the next scene from the remaining scenes anim.currentScene(anim.currentScene() || anim._remainingScenes.shift()); // Set the amount of time elapsed for the current scene (after a pause) // or start at 0 for the next scene var currentScene = anim.currentScene(); currentScene.timeElapsed(currentScene.timeElapsed() || 0); } /** * The real meat of the animator. Starts a timer that will run * each tick of the animator. For each tick the animator needs * to run through each element of the current scene. * * @private * @param {Animator} anim an Animator **/ function _startFrameTimer(anim) { var frameDuration = DEFAULT_FRAME_DURATION; anim._playTimer = setInterval(function() { // if all of the scenes have been run if (!anim.currentScene()) { // if the animator should be looping copy the scenes array again // and load the first scene if (anim._looping) { anim._remainingScenes = anim.scenes().concat(); anim.currentScene(anim._remainingScenes.shift()); anim.currentScene().timeElapsed(0); } // otherwise, stop the timer, reset the values and return else { _resetAnimator(anim); return; } } var timeElapsedForCurrentScene = anim.currentScene().timeElapsed(); // if the current scene is still running then run another frame if (timeElapsedForCurrentScene < anim.currentScene().duration) { _runCurrentScene(anim); anim.currentScene().timeElapsed(timeElapsedForCurrentScene + frameDuration); // otherwise, load the next scene } else { var currentScene = anim.currentScene(); currentScene.oncomplete(); currentScene.timeElapsed(0); anim.currentScene(anim._remainingScenes.shift()); } }, frameDuration); } /** * Takes a Scene and runs through each of the elements of the scene. * If no time has elapsed for the scene yet, the scene's onstart handler * will be called. * * @private * @param {Animator} anim the Animator that the scene belongs to * @param {Scene} scene a Scene to run through * @param {Integer} timeElapsed the amount of time that has elapsed for the scene **/ function _runCurrentScene(anim) { var scene = anim.currentScene(); if (scene.timeElapsed() < 1) { scene.onstart(); } var elements = scene.elements; for(var i = 0, len = elements.length; i < len; i++) { elements[i](anim); } } /** * Resets the animator's timer and clears any state properties * that were store for the Animator * * @private * @param {Animator} anim an Animator to reset **/ function _resetAnimator(anim) { clearInterval(anim._playTimer); delete anim._currentlyPlaying; delete anim._looping; delete anim._playTimer; delete anim._remainingScenes; anim.clearCurrentScene(); } })();
The clearCurrentScene method needs to check that a currentScene exists first
lib/animator.js
The clearCurrentScene method needs to check that a currentScene exists first
<ide><path>ib/animator.js <ide> * Set the current scene back to null <ide> **/ <ide> anim.clearCurrentScene = function() { <del> current.timeElapsed(0); <del> currentScene = null; <add> if (currentScene) { <add> currentScene.timeElapsed(0); <add> currentScene = null; <add> } <ide> }; <ide> } <ide> <ide> anim._remainingScenes = anim._remainingScenes || <ide> anim.scenes().concat(); <ide> <del> // Load in the current scene (after a pause) <add> // Load in the Scenecurrent scene (after a pause) <ide> // or shift the next scene from the remaining scenes <ide> anim.currentScene(anim.currentScene() || <ide> anim._remainingScenes.shift());
Java
apache-2.0
968f5080b6a9d2383efda3a734db84e27c39600b
0
kahboom/apiman,cmoulliard/apiman,jasonchaffee/apiman,apiman/apiman,eformat/apiman-1,EricWittmann/apiman,joelschuster/apiman,rnc/apiman,rnc/apiman,jasonchaffee/apiman,eformat/apiman-1,KurtStam/apiman,rnc/apiman,KurtStam/apiman,jasonchaffee/apiman,kahboom/apiman,cmoulliard/apiman,jcechace/apiman,joelschuster/apiman,apiman/apiman,KurtStam/apiman,joelschuster/apiman,msavy/apiman,jasonchaffee/apiman,kunallimaye/apiman,KevinHorvatin/apiman,KurtStam/apiman,msavy/apiman,cmoulliard/apiman,KevinHorvatin/apiman,bgaisford/apiman,kunallimaye/apiman,jcechace/apiman,kunallimaye/apiman,joelschuster/apiman,msavy/apiman,kahboom/apiman,EricWittmann/apiman,bgaisford/apiman,jcechace/apiman,eformat/apiman-1,bgaisford/apiman,msavy/apiman,rnc/apiman,EricWittmann/apiman,KevinHorvatin/apiman,jcechace/apiman,KurtStam/apiman,EricWittmann/apiman,msavy/apiman,apiman/apiman,cmoulliard/apiman,bgaisford/apiman,jcechace/apiman,KevinHorvatin/apiman,rnc/apiman,kunallimaye/apiman,kahboom/apiman,eformat/apiman-1,kahboom/apiman,kunallimaye/apiman,KevinHorvatin/apiman,joelschuster/apiman,apiman/apiman,cmoulliard/apiman,EricWittmann/apiman,eformat/apiman-1,apiman/apiman,jasonchaffee/apiman,bgaisford/apiman
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.manager.api.es; import io.apiman.manager.api.beans.apps.ApplicationBean; import io.apiman.manager.api.beans.apps.ApplicationVersionBean; import io.apiman.manager.api.beans.audit.AuditEntityType; import io.apiman.manager.api.beans.audit.AuditEntryBean; import io.apiman.manager.api.beans.contracts.ContractBean; import io.apiman.manager.api.beans.gateways.GatewayBean; import io.apiman.manager.api.beans.idm.PermissionBean; import io.apiman.manager.api.beans.idm.PermissionType; import io.apiman.manager.api.beans.idm.RoleBean; import io.apiman.manager.api.beans.idm.RoleMembershipBean; import io.apiman.manager.api.beans.idm.UserBean; import io.apiman.manager.api.beans.orgs.OrganizationBean; import io.apiman.manager.api.beans.plans.PlanBean; import io.apiman.manager.api.beans.plans.PlanVersionBean; import io.apiman.manager.api.beans.plugins.PluginBean; import io.apiman.manager.api.beans.policies.PolicyBean; import io.apiman.manager.api.beans.policies.PolicyDefinitionBean; import io.apiman.manager.api.beans.policies.PolicyType; import io.apiman.manager.api.beans.search.OrderByBean; import io.apiman.manager.api.beans.search.PagingBean; import io.apiman.manager.api.beans.search.SearchCriteriaBean; import io.apiman.manager.api.beans.search.SearchCriteriaFilterBean; import io.apiman.manager.api.beans.search.SearchCriteriaFilterOperator; import io.apiman.manager.api.beans.search.SearchResultsBean; import io.apiman.manager.api.beans.services.ServiceBean; import io.apiman.manager.api.beans.services.ServiceGatewayBean; import io.apiman.manager.api.beans.services.ServicePlanBean; import io.apiman.manager.api.beans.services.ServiceVersionBean; import io.apiman.manager.api.beans.summary.ApiEntryBean; import io.apiman.manager.api.beans.summary.ApiRegistryBean; import io.apiman.manager.api.beans.summary.ApplicationSummaryBean; import io.apiman.manager.api.beans.summary.ApplicationVersionSummaryBean; import io.apiman.manager.api.beans.summary.ContractSummaryBean; import io.apiman.manager.api.beans.summary.GatewaySummaryBean; import io.apiman.manager.api.beans.summary.OrganizationSummaryBean; import io.apiman.manager.api.beans.summary.PlanSummaryBean; import io.apiman.manager.api.beans.summary.PlanVersionSummaryBean; import io.apiman.manager.api.beans.summary.PluginSummaryBean; import io.apiman.manager.api.beans.summary.PolicyDefinitionSummaryBean; import io.apiman.manager.api.beans.summary.PolicySummaryBean; import io.apiman.manager.api.beans.summary.ServicePlanSummaryBean; import io.apiman.manager.api.beans.summary.ServiceSummaryBean; import io.apiman.manager.api.beans.summary.ServiceVersionSummaryBean; import io.apiman.manager.api.core.IIdmStorage; import io.apiman.manager.api.core.IStorage; import io.apiman.manager.api.core.IStorageQuery; import io.apiman.manager.api.core.exceptions.StorageException; import io.apiman.manager.api.core.util.PolicyTemplateUtil; import io.apiman.manager.api.es.beans.PoliciesBean; import io.apiman.manager.api.es.beans.ServiceDefinitionBean; import io.searchbox.action.Action; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.cluster.Health; import io.searchbox.core.Delete; import io.searchbox.core.DeleteByQuery; import io.searchbox.core.Get; import io.searchbox.core.Index; import io.searchbox.core.Search; import io.searchbox.core.SearchResult; import io.searchbox.core.SearchResult.Hit; import io.searchbox.indices.CreateIndex; import io.searchbox.indices.IndicesExists; import io.searchbox.params.Parameters; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.io.IOUtils; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.common.Base64; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.AndFilterBuilder; import org.elasticsearch.index.query.BaseQueryBuilder; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.FilteredQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermsQueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; /** * An implementation of the API Manager persistence layer that uses git to store * the entities. * * @author [email protected] */ @ApplicationScoped @Alternative public class EsStorage implements IStorage, IStorageQuery, IIdmStorage { private static final String INDEX_NAME = "apiman_manager"; //$NON-NLS-1$ private static int guidCounter = 100; @Inject @Named("storage") JestClient esClient; /** * Constructor. */ public EsStorage() { } /** * Called to initialize the storage. */ public void initialize() { try { esClient.execute(new Health.Builder().build()); // TODO Do we need a loop to wait for all nodes to join the cluster? Action<JestResult> action = new IndicesExists.Builder(INDEX_NAME).build(); JestResult result = esClient.execute(action); if (! result.isSucceeded()) { createIndex(INDEX_NAME); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @param indexName * @throws Exception */ private void createIndex(String indexName) throws Exception { CreateIndexRequest request = new CreateIndexRequest(indexName); URL settings = getClass().getResource("index-settings.json"); //$NON-NLS-1$ String source = IOUtils.toString(settings); request.source(source); JestResult response = esClient.execute(new CreateIndex.Builder(indexName).settings(source).build()); if (!response.isSucceeded()) { throw new StorageException("Failed to create index " + indexName + ": " + response.getErrorMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * @see io.apiman.manager.api.core.IStorage#beginTx() */ @Override public void beginTx() throws StorageException { // No Transaction support for ES } /** * @see io.apiman.manager.api.core.IStorage#commitTx() */ @Override public void commitTx() throws StorageException { // No Transaction support for ES } /** * @see io.apiman.manager.api.core.IStorage#rollbackTx() */ @Override public void rollbackTx() { // No Transaction support for ES } /** * @see io.apiman.manager.api.core.IStorage#createOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean) */ @Override public void createOrganization(OrganizationBean organization) throws StorageException { indexEntity("organization", organization.getId(), EsMarshalling.marshall(organization), true); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createApplication(io.apiman.manager.api.beans.apps.ApplicationBean) */ @Override public void createApplication(ApplicationBean application) throws StorageException { indexEntity("application", id(application.getOrganization().getId(), application.getId()), EsMarshalling.marshall(application)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createApplicationVersion(io.apiman.manager.api.beans.apps.ApplicationVersionBean) */ @Override public void createApplicationVersion(ApplicationVersionBean version) throws StorageException { ApplicationBean application = version.getApplication(); String id = id(application.getOrganization().getId(), application.getId(), version.getVersion()); indexEntity("applicationVersion", id, EsMarshalling.marshall(version)); //$NON-NLS-1$ PoliciesBean policies = PoliciesBean.from(PolicyType.Application, application.getOrganization().getId(), application.getId(), version.getVersion()); indexEntity("applicationPolicies", id, EsMarshalling.marshall(policies)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createContract(io.apiman.manager.api.beans.contracts.ContractBean) */ @Override public void createContract(ContractBean contract) throws StorageException { List<ContractSummaryBean> contracts = getApplicationContracts(contract.getApplication().getApplication().getOrganization().getId(), contract.getApplication().getApplication().getId(), contract.getApplication().getVersion()); for (ContractSummaryBean csb : contracts) { if (csb.getServiceOrganizationId().equals(contract.getService().getService().getOrganization().getId()) && csb.getServiceId().equals(contract.getService().getService().getId()) && csb.getServiceVersion().equals(contract.getService().getVersion()) && csb.getPlanId().equals(contract.getPlan().getPlan().getId())) { throw new StorageException("Error creating contract: duplicate contract detected."); //$NON-NLS-1$ } } contract.setId(generateGuid()); indexEntity("contract", String.valueOf(contract.getId()), EsMarshalling.marshall(contract), true); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createService(io.apiman.manager.api.beans.services.ServiceBean) */ @Override public void createService(ServiceBean service) throws StorageException { indexEntity("service", id(service.getOrganization().getId(), service.getId()), EsMarshalling.marshall(service)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createServiceVersion(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void createServiceVersion(ServiceVersionBean version) throws StorageException { ServiceBean service = version.getService(); String id = id(service.getOrganization().getId(), service.getId(), version.getVersion()); indexEntity("serviceVersion", id, EsMarshalling.marshall(version)); //$NON-NLS-1$ PoliciesBean policies = PoliciesBean.from(PolicyType.Service, service.getOrganization().getId(), service.getId(), version.getVersion()); indexEntity("servicePolicies", id, EsMarshalling.marshall(policies)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPlan(io.apiman.manager.api.beans.plans.PlanBean) */ @Override public void createPlan(PlanBean plan) throws StorageException { indexEntity("plan", id(plan.getOrganization().getId(), plan.getId()), EsMarshalling.marshall(plan)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean) */ @Override public void createPlanVersion(PlanVersionBean version) throws StorageException { PlanBean plan = version.getPlan(); String id = id(plan.getOrganization().getId(), plan.getId(), version.getVersion()); indexEntity("planVersion", id, EsMarshalling.marshall(version)); //$NON-NLS-1$ PoliciesBean policies = PoliciesBean.from(PolicyType.Plan, plan.getOrganization().getId(), plan.getId(), version.getVersion()); indexEntity("planPolicies", id, EsMarshalling.marshall(policies)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPolicy(io.apiman.manager.api.beans.policies.PolicyBean) */ @Override public void createPolicy(PolicyBean policy) throws StorageException { String docType = getPoliciesDocType(policy.getType()); String id = id(policy.getOrganizationId(), policy.getEntityId(), policy.getEntityVersion()); Map<String, Object> source = getEntity(docType, id); if (source == null) { throw new StorageException("Failed to create policy (missing PoliciesBean)."); //$NON-NLS-1$ } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); policy.setId(generateGuid()); policies.getPolicies().add(policy); orderPolicies(policies); updateEntity(docType, id, EsMarshalling.marshall(policies)); } /** * @see io.apiman.manager.api.core.IStorage#reorderPolicies(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.util.List) */ @Override public void reorderPolicies(PolicyType type, String organizationId, String entityId, String entityVersion, List<Long> newOrder) throws StorageException { String docType = getPoliciesDocType(type); String pid = id(organizationId, entityId, entityVersion); Map<String, Object> source = getEntity(docType, pid); if (source == null) { return; } PoliciesBean policiesBean = EsMarshalling.unmarshallPolicies(source); List<PolicyBean> policies = policiesBean.getPolicies(); List<PolicyBean> reordered = new ArrayList<>(policies.size()); for (Long policyId : newOrder) { ListIterator<PolicyBean> iterator = policies.listIterator(); while (iterator.hasNext()) { PolicyBean policyBean = iterator.next(); if (policyBean.getId().equals(policyId)) { iterator.remove(); reordered.add(policyBean); break; } } } // Make sure we don't stealth-delete any policies. Put anything // remaining at the end of the list. for (PolicyBean policyBean : policies) { reordered.add(policyBean); } policiesBean.setPolicies(reordered); updateEntity(docType, pid, EsMarshalling.marshall(policiesBean)); } /** * Set the order index of all policies. * @param policies */ private void orderPolicies(PoliciesBean policies) { int idx = 1; for (PolicyBean policy : policies.getPolicies()) { policy.setOrderIndex(idx++); } } /** * @see io.apiman.manager.api.core.IStorage#createGateway(io.apiman.manager.api.beans.gateways.GatewayBean) */ @Override public void createGateway(GatewayBean gateway) throws StorageException { indexEntity("gateway", gateway.getId(), EsMarshalling.marshall(gateway)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPlugin(io.apiman.manager.api.beans.plugins.PluginBean) */ @Override public void createPlugin(PluginBean plugin) throws StorageException { plugin.setId(generateGuid()); indexEntity("plugin", String.valueOf(plugin.getId()), EsMarshalling.marshall(plugin)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) */ @Override public void createPolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException { indexEntity("policyDef", policyDef.getId(), EsMarshalling.marshall(policyDef)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#createRole(io.apiman.manager.api.beans.idm.RoleBean) */ @Override public void createRole(RoleBean role) throws StorageException { indexEntity("role", role.getId(), EsMarshalling.marshall(role)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createAuditEntry(io.apiman.manager.api.beans.audit.AuditEntryBean) */ @Override public void createAuditEntry(AuditEntryBean entry) throws StorageException { if (entry == null) { return; } entry.setId(generateGuid()); indexEntity("auditEntry", String.valueOf(entry.getId()), EsMarshalling.marshall(entry)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#updateOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean) */ @Override public void updateOrganization(OrganizationBean organization) throws StorageException { updateEntity("organization", organization.getId(), EsMarshalling.marshall(organization)); //$NON-NLS-1$ // TODO also update all entities that inline the organization name, if that has changed! (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updateApplication(io.apiman.manager.api.beans.apps.ApplicationBean) */ @Override public void updateApplication(ApplicationBean application) throws StorageException { updateEntity("application", id(application.getOrganization().getId(), application.getId()), EsMarshalling.marshall(application)); //$NON-NLS-1$ // TODO also update the application versions (in case the description changed) (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updateApplicationVersion(io.apiman.manager.api.beans.apps.ApplicationVersionBean) */ @Override public void updateApplicationVersion(ApplicationVersionBean version) throws StorageException { ApplicationBean application = version.getApplication(); updateEntity("applicationVersion", id(application.getOrganization().getId(), application.getId(), version.getVersion()), //$NON-NLS-1$ EsMarshalling.marshall(version)); } /** * @see io.apiman.manager.api.core.IStorage#updateService(io.apiman.manager.api.beans.services.ServiceBean) */ @Override public void updateService(ServiceBean service) throws StorageException { updateEntity("service", id(service.getOrganization().getId(), service.getId()), EsMarshalling.marshall(service)); //$NON-NLS-1$ // TODO also update the service versions (in case the description changed) (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updateServiceVersion(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void updateServiceVersion(ServiceVersionBean version) throws StorageException { ServiceBean service = version.getService(); updateEntity("serviceVersion", id(service.getOrganization().getId(), service.getId(), version.getVersion()), //$NON-NLS-1$ EsMarshalling.marshall(version)); } /** * @see io.apiman.manager.api.core.IStorage#updateServiceDefinition(io.apiman.manager.api.beans.services.ServiceVersionBean, java.io.InputStream) */ @Override public void updateServiceDefinition(ServiceVersionBean version, InputStream definitionStream) throws StorageException { InputStream serviceDefinition = null; try { String id = id(version.getService().getOrganization().getId(), version.getService().getId(), version.getVersion()) + ":def"; //$NON-NLS-1$ serviceDefinition = getServiceDefinition(version); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(definitionStream, baos); String data = Base64.encodeBytes(baos.toByteArray()); ServiceDefinitionBean definition = new ServiceDefinitionBean(); definition.setData(data); if (serviceDefinition == null) { indexEntity("serviceDefinition", id, EsMarshalling.marshall(definition)); //$NON-NLS-1$ } else { updateEntity("serviceDefinition", id, EsMarshalling.marshall(definition)); //$NON-NLS-1$ } } catch (IOException e) { throw new StorageException(e); } finally { IOUtils.closeQuietly(serviceDefinition); } } /** * @see io.apiman.manager.api.core.IStorage#updatePlan(io.apiman.manager.api.beans.plans.PlanBean) */ @Override public void updatePlan(PlanBean plan) throws StorageException { updateEntity("plan", id(plan.getOrganization().getId(), plan.getId()), EsMarshalling.marshall(plan)); //$NON-NLS-1$ // TODO also update the plan versions (in case the description changed) (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updatePlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean) */ @Override public void updatePlanVersion(PlanVersionBean version) throws StorageException { PlanBean plan = version.getPlan(); updateEntity("planVersion", id(plan.getOrganization().getId(), plan.getId(), version.getVersion()), //$NON-NLS-1$ EsMarshalling.marshall(version)); } /** * @see io.apiman.manager.api.core.IStorage#updatePolicy(io.apiman.manager.api.beans.policies.PolicyBean) */ @Override public void updatePolicy(PolicyBean policy) throws StorageException { String docType = getPoliciesDocType(policy.getType()); String pid = id(policy.getOrganizationId(), policy.getEntityId(), policy.getEntityVersion()); Map<String, Object> source = getEntity(docType, pid); if (source == null) { throw new StorageException("Policy not found."); //$NON-NLS-1$ } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); List<PolicyBean> policyBeans = policies.getPolicies(); boolean found = false; if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { if (policyBean.getId().equals(policy.getId())) { policyBean.setConfiguration(policy.getConfiguration()); policyBean.setModifiedBy(policy.getModifiedBy()); policyBean.setModifiedOn(policy.getModifiedOn()); found = true; break; } } } if (found) { updateEntity(docType, pid, EsMarshalling.marshall(policies)); } else { throw new StorageException("Policy not found."); //$NON-NLS-1$ } } /** * @see io.apiman.manager.api.core.IStorage#updateGateway(io.apiman.manager.api.beans.gateways.GatewayBean) */ @Override public void updateGateway(GatewayBean gateway) throws StorageException { updateEntity("gateway", gateway.getId(), EsMarshalling.marshall(gateway)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#updatePolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) */ @Override public void updatePolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException { updateEntity("policyDef", policyDef.getId(), EsMarshalling.marshall(policyDef)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#updateRole(io.apiman.manager.api.beans.idm.RoleBean) */ @Override public void updateRole(RoleBean role) throws StorageException { updateEntity("role", role.getId(), EsMarshalling.marshall(role)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean) */ @Override public void deleteOrganization(OrganizationBean organization) throws StorageException { deleteEntity("organization", organization.getId()); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteApplication(io.apiman.manager.api.beans.apps.ApplicationBean) */ @Override public void deleteApplication(ApplicationBean application) throws StorageException { deleteEntity("application", id(application.getOrganization().getId(), application.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteApplicationVersion(io.apiman.manager.api.beans.apps.ApplicationVersionBean) */ @Override public void deleteApplicationVersion(ApplicationVersionBean version) throws StorageException { ApplicationBean application = version.getApplication(); deleteEntity("applicationVersion", id(application.getOrganization().getId(), application.getId(), version.getVersion())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteContract(io.apiman.manager.api.beans.contracts.ContractBean) */ @Override public void deleteContract(ContractBean contract) throws StorageException { deleteEntity("contract", String.valueOf(contract.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteService(io.apiman.manager.api.beans.services.ServiceBean) */ @Override public void deleteService(ServiceBean service) throws StorageException { deleteEntity("service", id(service.getOrganization().getId(), service.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteServiceVersion(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void deleteServiceVersion(ServiceVersionBean version) throws StorageException { ServiceBean service = version.getService(); deleteEntity("serviceVersion", id(service.getOrganization().getId(), service.getId(), version.getVersion())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteServiceDefinition(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void deleteServiceDefinition(ServiceVersionBean version) throws StorageException { String id = id(version.getService().getOrganization().getId(), version.getService().getId(), version.getVersion()) + ":def"; //$NON-NLS-1$ deleteEntity("serviceDefinition", id); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePlan(io.apiman.manager.api.beans.plans.PlanBean) */ @Override public void deletePlan(PlanBean plan) throws StorageException { deleteEntity("plan", id(plan.getOrganization().getId(), plan.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean) */ @Override public void deletePlanVersion(PlanVersionBean version) throws StorageException { PlanBean plan = version.getPlan(); deleteEntity("planVersion", id(plan.getOrganization().getId(), plan.getId(), version.getVersion())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePolicy(io.apiman.manager.api.beans.policies.PolicyBean) */ @Override public void deletePolicy(PolicyBean policy) throws StorageException { String docType = getPoliciesDocType(policy.getType()); String pid = id(policy.getOrganizationId(), policy.getEntityId(), policy.getEntityVersion()); Map<String, Object> source = getEntity(docType, pid); if (source == null) { throw new StorageException("Policy not found."); //$NON-NLS-1$ } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); if (policies == null) throw new StorageException("Policy not found."); //$NON-NLS-1$ List<PolicyBean> policyBeans = policies.getPolicies(); boolean found = false; if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { if (policyBean.getId().equals(policy.getId())) { policies.getPolicies().remove(policyBean); found = true; break; } } } if (found) { updateEntity(docType, pid, EsMarshalling.marshall(policies)); } else { throw new StorageException("Policy not found."); //$NON-NLS-1$ } } /** * @see io.apiman.manager.api.core.IStorage#deleteGateway(io.apiman.manager.api.beans.gateways.GatewayBean) */ @Override public void deleteGateway(GatewayBean gateway) throws StorageException { deleteEntity("gateway", gateway.getId()); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePlugin(io.apiman.manager.api.beans.plugins.PluginBean) */ @Override public void deletePlugin(PluginBean plugin) throws StorageException { deleteEntity("plugin", String.valueOf(plugin.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) */ @Override public void deletePolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException { deleteEntity("policyDef", policyDef.getId()); //$NON-NLS-1$ } /* (non-Javadoc) * @see io.apiman.manager.api.core.IIdmStorage#deleteRole(io.apiman.manager.api.beans.idm.RoleBean) */ @Override public void deleteRole(RoleBean role) throws StorageException { deleteEntity("role", role.getId()); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#getOrganization(java.lang.String) */ @Override public OrganizationBean getOrganization(String id) throws StorageException { Map<String, Object> source = getEntity("organization", id); //$NON-NLS-1$ return EsMarshalling.unmarshallOrganization(source); } /** * @see io.apiman.manager.api.core.IStorage#getApplication(java.lang.String, java.lang.String) */ @Override public ApplicationBean getApplication(String organizationId, String id) throws StorageException { Map<String, Object> source = getEntity("application", id(organizationId, id)); //$NON-NLS-1$ if (source == null) { return null; } ApplicationBean bean = EsMarshalling.unmarshallApplication(source); bean.setOrganization(getOrganization(organizationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getApplicationVersion(java.lang.String, java.lang.String, java.lang.String) */ @Override public ApplicationVersionBean getApplicationVersion(String organizationId, String applicationId, String version) throws StorageException { Map<String, Object> source = getEntity("applicationVersion", id(organizationId, applicationId, version)); //$NON-NLS-1$ if (source == null) { return null; } ApplicationVersionBean bean = EsMarshalling.unmarshallApplicationVersion(source); bean.setApplication(getApplication(organizationId, applicationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getContract(java.lang.Long) */ @SuppressWarnings("nls") @Override public ContractBean getContract(Long id) throws StorageException { Map<String, Object> source = getEntity("contract", String.valueOf(id)); //$NON-NLS-1$ ContractBean contract = EsMarshalling.unmarshallContract(source); String appOrgId = (String) source.get("appOrganizationId"); String appId = (String) source.get("appId"); String appVersion = (String) source.get("appVersion"); String svcOrgId = (String) source.get("serviceOrganizationId"); String svcId = (String) source.get("serviceId"); String svcVersion = (String) source.get("serviceVersion"); String planId = (String) source.get("planId"); String planVersion = (String) source.get("planVersion"); ApplicationVersionBean avb = getApplicationVersion(appOrgId, appId, appVersion); ServiceVersionBean svb = getServiceVersion(svcOrgId, svcId, svcVersion); PlanVersionBean pvb = getPlanVersion(svcOrgId, planId, planVersion); contract.setApplication(avb); contract.setPlan(pvb); contract.setService(svb); return contract; } /** * @see io.apiman.manager.api.core.IStorage#getService(java.lang.String, java.lang.String) */ @Override public ServiceBean getService(String organizationId, String id) throws StorageException { Map<String, Object> source = getEntity("service", id(organizationId, id)); //$NON-NLS-1$ if (source == null) { return null; } ServiceBean bean = EsMarshalling.unmarshallService(source); bean.setOrganization(getOrganization(organizationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getServiceVersion(java.lang.String, java.lang.String, java.lang.String) */ @Override public ServiceVersionBean getServiceVersion(String organizationId, String serviceId, String version) throws StorageException { Map<String, Object> source = getEntity("serviceVersion", id(organizationId, serviceId, version)); //$NON-NLS-1$ if (source == null) { return null; } ServiceVersionBean bean = EsMarshalling.unmarshallServiceVersion(source); bean.setService(getService(organizationId, serviceId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getServiceDefinition(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public InputStream getServiceDefinition(ServiceVersionBean version) throws StorageException { try { String id = id(version.getService().getOrganization().getId(), version.getService().getId(), version.getVersion()) + ":def"; //$NON-NLS-1$ Map<String, Object> source = getEntity("serviceDefinition", id); //$NON-NLS-1$ if (source == null) { return null; } ServiceDefinitionBean def = EsMarshalling.unmarshallServiceDefinition(source); if (def == null) return null; String data = def.getData(); return new ByteArrayInputStream(Base64.decode(data)); } catch (IOException e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IStorage#getPlan(java.lang.String, java.lang.String) */ @Override public PlanBean getPlan(String organizationId, String id) throws StorageException { Map<String, Object> source = getEntity("plan", id(organizationId, id)); //$NON-NLS-1$ if (source == null) { return null; } PlanBean bean = EsMarshalling.unmarshallPlan(source); bean.setOrganization(getOrganization(organizationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getPlanVersion(java.lang.String, java.lang.String, java.lang.String) */ @Override public PlanVersionBean getPlanVersion(String organizationId, String planId, String version) throws StorageException { Map<String, Object> source = getEntity("planVersion", id(organizationId, planId, version)); //$NON-NLS-1$ if (source == null) { return null; } PlanVersionBean bean = EsMarshalling.unmarshallPlanVersion(source); bean.setPlan(getPlan(organizationId, planId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getPolicy(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.lang.Long) */ @Override public PolicyBean getPolicy(PolicyType type, String organizationId, String entityId, String version, Long id) throws StorageException { String docType = getPoliciesDocType(type); String pid = id(organizationId, entityId, version); Map<String, Object> source = getEntity(docType, pid); if (source == null) { return null; } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); if (policies == null) return null; List<PolicyBean> policyBeans = policies.getPolicies(); if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { if (policyBean.getId().equals(id)) { PolicyDefinitionBean def = getPolicyDefinition(policyBean.getDefinition().getId()); policyBean.setDefinition(def); return policyBean; } } } return null; } /** * @see io.apiman.manager.api.core.IStorage#getGateway(java.lang.String) */ @Override public GatewayBean getGateway(String id) throws StorageException { Map<String, Object> source = getEntity("gateway", id); //$NON-NLS-1$ return EsMarshalling.unmarshallGateway(source); } /** * @see io.apiman.manager.api.core.IStorage#getPlugin(long) */ @Override public PluginBean getPlugin(long id) throws StorageException { Map<String, Object> source = getEntity("plugin", String.valueOf(id)); //$NON-NLS-1$ return EsMarshalling.unmarshallPlugin(source); } /** * @see io.apiman.manager.api.core.IStorage#getPlugin(java.lang.String, java.lang.String) */ @Override public PluginBean getPlugin(String groupId, String artifactId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("groupId", groupId), FilterBuilders.termFilter("artifactId", artifactId) ) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(2); SearchRequest request = new SearchRequest(INDEX_NAME); request.types("plugin"); //$NON-NLS-1$ request.source(builder); List<Hit<Map<String,Object>,Void>> hits = listEntities("plugin", builder); //$NON-NLS-1$ if (hits.size() == 1) { Hit<Map<String,Object>,Void> hit = hits.iterator().next(); return EsMarshalling.unmarshallPlugin(hit.source); } return null; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IStorage#getPolicyDefinition(java.lang.String) */ @Override public PolicyDefinitionBean getPolicyDefinition(String id) throws StorageException { Map<String, Object> source = getEntity("policyDef", id); //$NON-NLS-1$ return EsMarshalling.unmarshallPolicyDefinition(source); } /** * @see io.apiman.manager.api.core.IIdmStorage#getRole(java.lang.String) */ @Override public RoleBean getRole(String id) throws StorageException { Map<String, Object> source = getEntity("role", id); //$NON-NLS-1$ return EsMarshalling.unmarshallRole(source); } /** * @see io.apiman.manager.api.core.IStorageQuery#listPlugins() */ @Override public List<PluginSummaryBean> listPlugins() throws StorageException { @SuppressWarnings("nls") String[] fields = {"id", "artifactId", "groupId", "version", "classifier", "type", "name", "description", "createdBy", "createdOn"}; SearchSourceBuilder builder = new SearchSourceBuilder() .fetchSource(fields, null).sort("name.raw", SortOrder.ASC).size(200); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("plugin", builder); //$NON-NLS-1$ List<PluginSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PluginSummaryBean bean = EsMarshalling.unmarshallPluginSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#listGateways() */ @Override public List<GatewaySummaryBean> listGateways() throws StorageException { @SuppressWarnings("nls") String[] fields = {"id", "name", "description","type"}; SearchSourceBuilder builder = new SearchSourceBuilder().fetchSource(fields, null).sort("name.raw", SortOrder.ASC).size(100); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("gateway", builder); //$NON-NLS-1$ List<GatewaySummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { GatewaySummaryBean bean = EsMarshalling.unmarshallGatewaySummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#findOrganizations(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<OrganizationSummaryBean> findOrganizations(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "organization", new IUnmarshaller<OrganizationSummaryBean>() { //$NON-NLS-1$ @Override public OrganizationSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallOrganizationSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#findApplications(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<ApplicationSummaryBean> findApplications(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "application", new IUnmarshaller<ApplicationSummaryBean>() { //$NON-NLS-1$ @Override public ApplicationSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallApplicationSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#findServices(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<ServiceSummaryBean> findServices(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "service", new IUnmarshaller<ServiceSummaryBean>() { //$NON-NLS-1$ @Override public ServiceSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallServiceSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#findPlans(java.lang.String, io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<PlanSummaryBean> findPlans(String organizationId, SearchCriteriaBean criteria) throws StorageException { criteria.addFilter("organizationId", organizationId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ return find(criteria, "plan", new IUnmarshaller<PlanSummaryBean>() { //$NON-NLS-1$ @Override public PlanSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallPlanSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#auditEntity(java.lang.String, java.lang.String, java.lang.String, java.lang.Class, io.apiman.manager.api.beans.search.PagingBean) */ @Override public <T> SearchResultsBean<AuditEntryBean> auditEntity(String organizationId, String entityId, String entityVersion, Class<T> type, PagingBean paging) throws StorageException { SearchCriteriaBean criteria = new SearchCriteriaBean(); if (paging != null) { criteria.setPaging(paging); } else { criteria.setPage(1); criteria.setPageSize(20); } criteria.setOrder("createdOn", false); //$NON-NLS-1$ if (organizationId != null) { criteria.addFilter("organizationId", organizationId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } if (entityId != null) { criteria.addFilter("entityId", entityId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } if (entityVersion != null) { criteria.addFilter("entityVersion", entityVersion, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } if (type != null) { AuditEntityType entityType = null; if (type == OrganizationBean.class) { entityType = AuditEntityType.Organization; } else if (type == ApplicationBean.class) { entityType = AuditEntityType.Application; } else if (type == ServiceBean.class) { entityType = AuditEntityType.Service; } else if (type == PlanBean.class) { entityType = AuditEntityType.Plan; } if (entityType != null) { criteria.addFilter("entityType", entityType.name(), SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } } return find(criteria, "auditEntry", new IUnmarshaller<AuditEntryBean>() { //$NON-NLS-1$ @Override public AuditEntryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallAuditEntry(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#auditUser(java.lang.String, io.apiman.manager.api.beans.search.PagingBean) */ @Override public <T> SearchResultsBean<AuditEntryBean> auditUser(String userId, PagingBean paging) throws StorageException { SearchCriteriaBean criteria = new SearchCriteriaBean(); if (paging != null) { criteria.setPaging(paging); } else { criteria.setPage(1); criteria.setPageSize(20); } criteria.setOrder("createdOn", false); //$NON-NLS-1$ if (userId != null) { criteria.addFilter("who", userId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } return find(criteria, "auditEntry", new IUnmarshaller<AuditEntryBean>() { //$NON-NLS-1$ @Override public AuditEntryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallAuditEntry(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#getOrgs(java.util.Set) */ @Override public List<OrganizationSummaryBean> getOrgs(Set<String> organizationIds) throws StorageException { List<OrganizationSummaryBean> orgs = new ArrayList<>(); if (organizationIds == null || organizationIds.isEmpty()) { return orgs; } @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termsFilter("id", organizationIds.toArray()) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("name.raw", SortOrder.ASC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("organization", builder); //$NON-NLS-1$ List<OrganizationSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { OrganizationSummaryBean bean = EsMarshalling.unmarshallOrganizationSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationsInOrgs(java.util.Set) */ @Override public List<ApplicationSummaryBean> getApplicationsInOrgs(Set<String> organizationIds) throws StorageException { @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("organizationName.raw", SortOrder.ASC) .sort("name.raw", SortOrder.ASC) .size(500); TermsQueryBuilder query = QueryBuilders.termsQuery("organizationId", organizationIds.toArray(new String[organizationIds.size()])); //$NON-NLS-1$ builder.query(query); List<Hit<Map<String,Object>,Void>> hits = listEntities("application", builder); //$NON-NLS-1$ List<ApplicationSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ApplicationSummaryBean bean = EsMarshalling.unmarshallApplicationSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationsInOrg(java.lang.String) */ @Override public List<ApplicationSummaryBean> getApplicationsInOrg(String organizationId) throws StorageException { Set<String> orgs = new HashSet<>(); orgs.add(organizationId); return getApplicationsInOrgs(orgs); } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationVersions(java.lang.String, java.lang.String) */ @Override public List<ApplicationVersionSummaryBean> getApplicationVersions(String organizationId, String applicationId) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("applicationId", applicationId)) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("createdOn", SortOrder.DESC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("applicationVersion", builder); //$NON-NLS-1$ List<ApplicationVersionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ApplicationVersionSummaryBean bean = EsMarshalling.unmarshallApplicationVersionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationContracts(java.lang.String, java.lang.String, java.lang.String) */ @Override public List<ContractSummaryBean> getApplicationContracts(String organizationId, String applicationId, String version) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("appOrganizationId", organizationId), FilterBuilders.termFilter("appId", applicationId), FilterBuilders.termFilter("appVersion", version) ) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder().sort("serviceOrganizationId", SortOrder.ASC) .sort("serviceId", SortOrder.ASC).query(query).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("contract", builder); //$NON-NLS-1$ List<ContractSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ContractSummaryBean bean = EsMarshalling.unmarshallContractSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApiRegistry(java.lang.String, java.lang.String, java.lang.String) */ @Override public ApiRegistryBean getApiRegistry(String organizationId, String applicationId, String version) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("appOrganizationId", organizationId), FilterBuilders.termFilter("appId", applicationId), FilterBuilders.termFilter("appVersion", version) ) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder().sort("id", SortOrder.ASC).query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("contract", builder); //$NON-NLS-1$ ApiRegistryBean registry = new ApiRegistryBean(); for (Hit<Map<String,Object>,Void> hit : hits) { ApiEntryBean bean = EsMarshalling.unmarshallApiEntry(hit.source); ServiceVersionBean svb = getServiceVersion(bean.getServiceOrgId(), bean.getServiceId(), bean.getServiceVersion()); Set<ServiceGatewayBean> gateways = svb.getGateways(); if (gateways != null && gateways.size() > 0) { ServiceGatewayBean sgb = gateways.iterator().next(); bean.setGatewayId(sgb.getGatewayId()); } registry.getApis().add(bean); } return registry; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServicesInOrgs(java.util.Set) */ @Override public List<ServiceSummaryBean> getServicesInOrgs(Set<String> organizationIds) throws StorageException { @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("organizationName.raw", SortOrder.ASC) .sort("name.raw", SortOrder.ASC) .size(500); TermsQueryBuilder query = QueryBuilders.termsQuery("organizationId", organizationIds.toArray(new String[organizationIds.size()])); //$NON-NLS-1$ builder.query(query); List<Hit<Map<String,Object>,Void>> hits = listEntities("service", builder); //$NON-NLS-1$ List<ServiceSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ServiceSummaryBean bean = EsMarshalling.unmarshallServiceSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServicesInOrg(java.lang.String) */ @Override public List<ServiceSummaryBean> getServicesInOrg(String organizationId) throws StorageException { Set<String> orgs = new HashSet<>(); orgs.add(organizationId); return getServicesInOrgs(orgs); } /** * @see io.apiman.manager.api.core.IStorageQuery#getServiceVersions(java.lang.String, java.lang.String) */ @Override public List<ServiceVersionSummaryBean> getServiceVersions(String organizationId, String serviceId) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("serviceId", serviceId)) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("createdOn", SortOrder.DESC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("serviceVersion", builder); //$NON-NLS-1$ List<ServiceVersionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ServiceVersionSummaryBean bean = EsMarshalling.unmarshallServiceVersionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServiceVersionPlans(java.lang.String, java.lang.String, java.lang.String) */ @Override public List<ServicePlanSummaryBean> getServiceVersionPlans(String organizationId, String serviceId, String version) throws StorageException { List<ServicePlanSummaryBean> rval = new ArrayList<>(); ServiceVersionBean versionBean = getServiceVersion(organizationId, serviceId, version); if (versionBean != null) { Set<ServicePlanBean> plans = versionBean.getPlans(); if (plans != null) { for (ServicePlanBean spb : plans) { PlanBean planBean = getPlan(organizationId, spb.getPlanId()); ServicePlanSummaryBean plan = new ServicePlanSummaryBean(); plan.setPlanId(spb.getPlanId()); plan.setVersion(spb.getVersion()); plan.setPlanName(planBean.getName()); plan.setPlanDescription(planBean.getDescription()); rval.add(plan); } } } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getPlansInOrgs(java.util.Set) */ @Override public List<PlanSummaryBean> getPlansInOrgs(Set<String> organizationIds) throws StorageException { @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("organizationName.raw", SortOrder.ASC) .sort("name.raw", SortOrder.ASC) .size(500); TermsQueryBuilder query = QueryBuilders.termsQuery("organizationId", organizationIds.toArray(new String[organizationIds.size()])); //$NON-NLS-1$ builder.query(query); List<Hit<Map<String,Object>,Void>> hits = listEntities("plan", builder); //$NON-NLS-1$ List<PlanSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PlanSummaryBean bean = EsMarshalling.unmarshallPlanSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getPlansInOrg(java.lang.String) */ @Override public List<PlanSummaryBean> getPlansInOrg(String organizationId) throws StorageException { Set<String> orgs = new HashSet<>(); orgs.add(organizationId); return getPlansInOrgs(orgs); } /** * @see io.apiman.manager.api.core.IStorageQuery#getPlanVersions(java.lang.String, java.lang.String) */ @Override public List<PlanVersionSummaryBean> getPlanVersions(String organizationId, String planId) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("planId", planId)) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("createdOn", SortOrder.DESC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("planVersion", builder); //$NON-NLS-1$ List<PlanVersionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PlanVersionSummaryBean bean = EsMarshalling.unmarshallPlanVersionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getPolicies(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType) */ @Override public List<PolicySummaryBean> getPolicies(String organizationId, String entityId, String version, PolicyType type) throws StorageException { try { String docType = getPoliciesDocType(type); String pid = id(organizationId, entityId, version); List<PolicySummaryBean> rval = new ArrayList<>(); Map<String, Object> source = getEntity(docType, pid); if (source == null) { return rval; } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); if (policies == null) return rval; List<PolicyBean> policyBeans = policies.getPolicies(); if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { PolicyDefinitionBean def = getPolicyDefinition(policyBean.getDefinition().getId()); policyBean.setDefinition(def); PolicyTemplateUtil.generatePolicyDescription(policyBean); PolicySummaryBean psb = new PolicySummaryBean(); psb.setCreatedBy(policyBean.getCreatedBy()); psb.setCreatedOn(policyBean.getCreatedOn()); psb.setDescription(policyBean.getDescription()); psb.setIcon(def.getIcon()); psb.setId(policyBean.getId()); psb.setName(policyBean.getName()); psb.setPolicyDefinitionId(def.getId()); rval.add(psb); } } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IStorageQuery#listPolicyDefinitions() */ @Override public List<PolicyDefinitionSummaryBean> listPolicyDefinitions() throws StorageException { @SuppressWarnings("nls") String[] fields = {"id", "policyImpl", "name", "description", "icon", "pluginId", "formType"}; SearchSourceBuilder builder = new SearchSourceBuilder() .fetchSource(fields, null) .sort("name.raw", SortOrder.ASC).size(100); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("policyDef", builder); //$NON-NLS-1$ List<PolicyDefinitionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PolicyDefinitionSummaryBean bean = EsMarshalling.unmarshallPolicyDefinitionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServiceContracts(java.lang.String, java.lang.String, java.lang.String, int, int) */ @Override public List<ContractSummaryBean> getServiceContracts(String organizationId, String serviceId, String version, int page, int pageSize) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("serviceOrganizationId", organizationId), FilterBuilders.termFilter("serviceId", serviceId), FilterBuilders.termFilter("serviceVersion", version) ) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder().sort("appOrganizationId", SortOrder.ASC) .sort("appId", SortOrder.ASC).query(query).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("contract", builder); //$NON-NLS-1$ List<ContractSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ContractSummaryBean bean = EsMarshalling.unmarshallContractSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getMaxPolicyOrderIndex(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType) */ @Override public int getMaxPolicyOrderIndex(String organizationId, String entityId, String entityVersion, PolicyType type) throws StorageException { // We'll figure this out later, when adding a policy. return -1; } /** * @see io.apiman.manager.api.core.IStorageQuery#listPluginPolicyDefs(java.lang.Long) */ @Override public List<PolicyDefinitionSummaryBean> listPluginPolicyDefs(Long pluginId) throws StorageException { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("pluginId", pluginId) ); @SuppressWarnings("nls") String[] fields = {"id", "policyImpl", "name", "description", "icon", "pluginId", "formType"}; SearchSourceBuilder builder = new SearchSourceBuilder() .fetchSource(fields, null) .query(qb) .sort("name.raw", SortOrder.ASC).size(100); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("policyDef", builder); //$NON-NLS-1$ List<PolicyDefinitionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PolicyDefinitionSummaryBean bean = EsMarshalling.unmarshallPolicyDefinitionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IIdmStorage#createUser(io.apiman.manager.api.beans.idm.UserBean) */ @Override public void createUser(UserBean user) throws StorageException { indexEntity("user", user.getUsername(), EsMarshalling.marshall(user)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#getUser(java.lang.String) */ @Override public UserBean getUser(String userId) throws StorageException { Map<String, Object> source = getEntity("user", userId); //$NON-NLS-1$ return EsMarshalling.unmarshallUser(source); } /** * @see io.apiman.manager.api.core.IIdmStorage#updateUser(io.apiman.manager.api.beans.idm.UserBean) */ @Override public void updateUser(UserBean user) throws StorageException { updateEntity("user", user.getUsername(), EsMarshalling.marshall(user)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#findUsers(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<UserBean> findUsers(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "user", new IUnmarshaller<UserBean>() { //$NON-NLS-1$ @Override public UserBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallUser(source); } }); } /** * @see io.apiman.manager.api.core.IIdmStorage#findRoles(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<RoleBean> findRoles(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "role", new IUnmarshaller<RoleBean>() { //$NON-NLS-1$ @Override public RoleBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallRole(source); } }); } /** * @see io.apiman.manager.api.core.IIdmStorage#createMembership(io.apiman.manager.api.beans.idm.RoleMembershipBean) */ @Override public void createMembership(RoleMembershipBean membership) throws StorageException { membership.setId(generateGuid()); String id = id(membership.getOrganizationId(), membership.getUserId(), membership.getRoleId()); indexEntity("roleMembership", id, EsMarshalling.marshall(membership)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#getMembership(java.lang.String, java.lang.String, java.lang.String) */ @Override public RoleMembershipBean getMembership(String userId, String roleId, String organizationId) throws StorageException { String id = id(organizationId, userId, roleId); Map<String, Object> source = getEntity("roleMembership", id); //$NON-NLS-1$ if (source == null) { return null; } else { return EsMarshalling.unmarshallRoleMembership(source); } } /** * @see io.apiman.manager.api.core.IIdmStorage#deleteMembership(java.lang.String, java.lang.String, java.lang.String) */ @Override public void deleteMembership(String userId, String roleId, String organizationId) throws StorageException { String id = id(organizationId, userId, roleId); deleteEntity("roleMembership", id); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#deleteMemberships(java.lang.String, java.lang.String) */ @Override @SuppressWarnings("nls") public void deleteMemberships(String userId, String organizationId) throws StorageException { FilteredQueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("userId", userId)) ); String string = query.toString(); // Workaround for bug in FilteredQueryBuilder which does not (yet) wrap // the JSON in a query element if (string.indexOf("query") < 0 || string.indexOf("query") > 7) { string = "{ \"query\" : " + string + "}"; } DeleteByQuery deleteByQuery = new DeleteByQuery.Builder(string).addIndex(INDEX_NAME) .addType("roleMembership").build(); try { JestResult response = esClient.execute(deleteByQuery); if (!response.isSucceeded()) { throw new StorageException(response.getErrorMessage()); } } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getUserMemberships(java.lang.String) */ @Override public Set<RoleMembershipBean> getUserMemberships(String userId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("userId", userId) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(2); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<RoleMembershipBean> rval = new HashSet<>(); for (Hit<Map<String,Object>,Void> hit : hits) { RoleMembershipBean roleMembership = EsMarshalling.unmarshallRoleMembership(hit.source); rval.add(roleMembership); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getUserMemberships(java.lang.String, java.lang.String) */ @Override public Set<RoleMembershipBean> getUserMemberships(String userId, String organizationId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("userId", userId), FilterBuilders.termFilter("organizationId", organizationId) ) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(2); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<RoleMembershipBean> rval = new HashSet<>(); for (Hit<Map<String,Object>,Void> hit : hits) { RoleMembershipBean roleMembership = EsMarshalling.unmarshallRoleMembership(hit.source); rval.add(roleMembership); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getOrgMemberships(java.lang.String) */ @Override public Set<RoleMembershipBean> getOrgMemberships(String organizationId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("organizationId", organizationId) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<RoleMembershipBean> rval = new HashSet<>(); for (Hit<Map<String,Object>,Void> hit : hits) { RoleMembershipBean roleMembership = EsMarshalling.unmarshallRoleMembership(hit.source); rval.add(roleMembership); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getPermissions(java.lang.String) */ @Override public Set<PermissionBean> getPermissions(String userId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("userId", userId) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<PermissionBean> rval = new HashSet<>(hits.size()); if (hits.size() > 0) { for (Hit<Map<String,Object>,Void> hit : hits) { Map<String, Object> source = hit.source; String roleId = String.valueOf(source.get("roleId")); //$NON-NLS-1$ String qualifier = String.valueOf(source.get("organizationId")); //$NON-NLS-1$ RoleBean role = getRole(roleId); if (role != null) { for (PermissionType permission : role.getPermissions()) { PermissionBean p = new PermissionBean(); p.setName(permission); p.setOrganizationId(qualifier); rval.add(p); } } } } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * Indexes an entity. * @param type * @param id * @param entitySource * @throws StorageException */ private void indexEntity(String type, String id, XContentBuilder sourceEntity) throws StorageException { indexEntity(type, id, sourceEntity, false); } /** * Indexes an entity. * @param type * @param id * @param entitySource * @param refresh true if the operation should wait for a refresh before it returns * @throws StorageException */ @SuppressWarnings("nls") private void indexEntity(String type, String id, XContentBuilder sourceEntity, boolean refresh) throws StorageException { try { String json = sourceEntity.string(); JestResult response = esClient.execute(new Index.Builder(json).refresh(refresh).index(INDEX_NAME) .setParameter(Parameters.OP_TYPE, "create").type(type).id(id).build()); if (!response.isSucceeded()) { throw new StorageException("Failed to index document " + id + " of type " + type + ": " + response.getErrorMessage()); } } catch (StorageException e) { throw e; } catch (Exception e) { throw new StorageException(e); } } /** * Gets an entity. Callers must unmarshal the resulting map. * @param type * @param id * @throws StorageException */ private Map<String, Object> getEntity(String type, String id) throws StorageException { try { JestResult response = esClient.execute(new Get.Builder(INDEX_NAME, id).type(type).build()); if (!response.isSucceeded()) { return null; } return response.getSourceAsObject(Map.class); } catch (Exception e) { throw new StorageException(e); } } /** * Returns a list of entities. * @param type * @param searchSourceBuilder * @throws StorageException */ private List<Hit<Map<String, Object>, Void>> listEntities(String type, SearchSourceBuilder searchSourceBuilder) throws StorageException { try { String query = searchSourceBuilder.toString(); Search search = new Search.Builder(query).addIndex(INDEX_NAME).addType(type).build(); SearchResult response = esClient.execute(search); @SuppressWarnings({ "rawtypes", "unchecked" }) List<Hit<Map<String, Object>, Void>> thehits = (List) response.getHits(Map.class); return thehits; } catch (Exception e) { throw new StorageException(e); } } /** * Deletes an entity. * @param type * @param id * @throws StorageException */ private void deleteEntity(String type, String id) throws StorageException { try { JestResult response = esClient.execute(new Delete.Builder(id).index(INDEX_NAME).type(type).build()); if (!response.isSucceeded()) { throw new StorageException("Document could not be deleted because it did not exist:" + response.getErrorMessage()); //$NON-NLS-1$ } } catch (StorageException e) { throw e; } catch (Exception e) { throw new StorageException(e); } } /** * Updates a single entity. * @param type * @param id * @param source * @throws StorageException */ private void updateEntity(String type, String id, XContentBuilder source) throws StorageException { try { String doc = source.string(); /* JestResult response = */esClient.execute(new Index.Builder(doc) .setParameter(Parameters.OP_TYPE, "index").index(INDEX_NAME).type(type).id(id).build()); //$NON-NLS-1$ } catch (Exception e) { throw new StorageException(e); } } /** * Finds entities using a generic search criteria bean. * @param criteria * @param type * @param unmarshaller * @throws StorageException */ private <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, String type, IUnmarshaller<T> unmarshaller) throws StorageException { try { SearchResultsBean<T> rval = new SearchResultsBean<>(); // Set some default in the case that paging information was not included in the request. PagingBean paging = criteria.getPaging(); if (paging == null) { paging = new PagingBean(); paging.setPage(1); paging.setPageSize(20); } int page = paging.getPage(); int pageSize = paging.getPageSize(); int start = (page - 1) * pageSize; SearchSourceBuilder builder = new SearchSourceBuilder().size(pageSize).from(start).fetchSource(true); // Sort order OrderByBean orderBy = criteria.getOrderBy(); if (orderBy != null) { String name = orderBy.getName(); if (name.equals("name") || name.equals("fullName")) { //$NON-NLS-1$ //$NON-NLS-2$ name += ".raw"; //$NON-NLS-1$ } if (orderBy.isAscending()) { builder.sort(name, SortOrder.ASC); } else { builder.sort(name, SortOrder.DESC); } } // Now process the filter criteria List<SearchCriteriaFilterBean> filters = criteria.getFilters(); BaseQueryBuilder q = QueryBuilders.matchAllQuery(); if (filters != null && !filters.isEmpty()) { AndFilterBuilder andFilter = FilterBuilders.andFilter(); int filterCount = 0; for (SearchCriteriaFilterBean filter : filters) { if (filter.getOperator() == SearchCriteriaFilterOperator.eq) { andFilter.add(FilterBuilders.termFilter(filter.getName(), filter.getValue())); filterCount++; } else if (filter.getOperator() == SearchCriteriaFilterOperator.like) { q = QueryBuilders.wildcardQuery(filter.getName(), filter.getValue().toLowerCase().replace('%', '*')); } else if (filter.getOperator() == SearchCriteriaFilterOperator.bool_eq) { andFilter.add(FilterBuilders.termFilter(filter.getName(), "true".equals(filter.getValue()))); //$NON-NLS-1$ filterCount++; } // TODO implement the other filter operators here! } if (filterCount > 0) { q = QueryBuilders.filteredQuery(q, andFilter); } } builder.query(q); String query = builder.toString(); Search search = new Search.Builder(query).addIndex(INDEX_NAME) .addType(type).build(); SearchResult response = esClient.execute(search); @SuppressWarnings({ "unchecked", "rawtypes" }) List<Hit<Map<String, Object>, Void>> thehits = (List) response.getHits(Map.class); rval.setTotalSize(response.getTotal()); for (Hit<Map<String,Object>,Void> hit : thehits) { Map<String, Object> sourceAsMap = hit.source; T bean = unmarshaller.unmarshal(sourceAsMap); rval.getBeans().add(bean); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * Generates a (hopefully) unique ID. Mimics JPA's auto-generated long ID column. */ private static synchronized Long generateGuid() { StringBuilder builder = new StringBuilder(); builder.append(System.currentTimeMillis()); builder.append(guidCounter++); // Reset the counter if it gets too high. It's always a number // between 100 and 999 so that the # of digits in the guid is // always the same. if (guidCounter > 999) { guidCounter = 100; } return Long.parseLong(builder.toString()); } /** * Returns the policies document type to use given the policy type. * @param type */ private static String getPoliciesDocType(PolicyType type) { String docType = "planPolicies"; //$NON-NLS-1$ if (type == PolicyType.Service) { docType = "servicePolicies"; //$NON-NLS-1$ } else if (type == PolicyType.Application) { docType = "applicationPolicies"; //$NON-NLS-1$ } return docType; } /** * A composite ID created from an organization ID and entity ID. * @param organizationId * @param entityId */ private static String id(String organizationId, String entityId) { return organizationId + ":" + entityId; //$NON-NLS-1$ } /** * A composite ID created from an organization ID, entity ID, and version. * @param organizationId * @param entityId * @param version */ private static String id(String organizationId, String entityId, String version) { return organizationId + ':' + entityId + ':' + version; } private static interface IUnmarshaller<T> { /** * Unmarshal the source map into an entity. * @param source the source map * @return the unmarshalled instance of <T> */ public T unmarshal(Map<String, Object> source); } }
manager/api/es/src/main/java/io/apiman/manager/api/es/EsStorage.java
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.manager.api.es; import io.apiman.manager.api.beans.apps.ApplicationBean; import io.apiman.manager.api.beans.apps.ApplicationVersionBean; import io.apiman.manager.api.beans.audit.AuditEntityType; import io.apiman.manager.api.beans.audit.AuditEntryBean; import io.apiman.manager.api.beans.contracts.ContractBean; import io.apiman.manager.api.beans.gateways.GatewayBean; import io.apiman.manager.api.beans.idm.PermissionBean; import io.apiman.manager.api.beans.idm.PermissionType; import io.apiman.manager.api.beans.idm.RoleBean; import io.apiman.manager.api.beans.idm.RoleMembershipBean; import io.apiman.manager.api.beans.idm.UserBean; import io.apiman.manager.api.beans.orgs.OrganizationBean; import io.apiman.manager.api.beans.plans.PlanBean; import io.apiman.manager.api.beans.plans.PlanVersionBean; import io.apiman.manager.api.beans.plugins.PluginBean; import io.apiman.manager.api.beans.policies.PolicyBean; import io.apiman.manager.api.beans.policies.PolicyDefinitionBean; import io.apiman.manager.api.beans.policies.PolicyType; import io.apiman.manager.api.beans.search.OrderByBean; import io.apiman.manager.api.beans.search.PagingBean; import io.apiman.manager.api.beans.search.SearchCriteriaBean; import io.apiman.manager.api.beans.search.SearchCriteriaFilterBean; import io.apiman.manager.api.beans.search.SearchCriteriaFilterOperator; import io.apiman.manager.api.beans.search.SearchResultsBean; import io.apiman.manager.api.beans.services.ServiceBean; import io.apiman.manager.api.beans.services.ServiceGatewayBean; import io.apiman.manager.api.beans.services.ServicePlanBean; import io.apiman.manager.api.beans.services.ServiceVersionBean; import io.apiman.manager.api.beans.summary.ApiEntryBean; import io.apiman.manager.api.beans.summary.ApiRegistryBean; import io.apiman.manager.api.beans.summary.ApplicationSummaryBean; import io.apiman.manager.api.beans.summary.ApplicationVersionSummaryBean; import io.apiman.manager.api.beans.summary.ContractSummaryBean; import io.apiman.manager.api.beans.summary.GatewaySummaryBean; import io.apiman.manager.api.beans.summary.OrganizationSummaryBean; import io.apiman.manager.api.beans.summary.PlanSummaryBean; import io.apiman.manager.api.beans.summary.PlanVersionSummaryBean; import io.apiman.manager.api.beans.summary.PluginSummaryBean; import io.apiman.manager.api.beans.summary.PolicyDefinitionSummaryBean; import io.apiman.manager.api.beans.summary.PolicySummaryBean; import io.apiman.manager.api.beans.summary.ServicePlanSummaryBean; import io.apiman.manager.api.beans.summary.ServiceSummaryBean; import io.apiman.manager.api.beans.summary.ServiceVersionSummaryBean; import io.apiman.manager.api.core.IIdmStorage; import io.apiman.manager.api.core.IStorage; import io.apiman.manager.api.core.IStorageQuery; import io.apiman.manager.api.core.exceptions.StorageException; import io.apiman.manager.api.core.util.PolicyTemplateUtil; import io.apiman.manager.api.es.beans.PoliciesBean; import io.apiman.manager.api.es.beans.ServiceDefinitionBean; import io.searchbox.action.Action; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.cluster.Health; import io.searchbox.core.Delete; import io.searchbox.core.DeleteByQuery; import io.searchbox.core.Get; import io.searchbox.core.Index; import io.searchbox.core.Search; import io.searchbox.core.SearchResult; import io.searchbox.core.SearchResult.Hit; import io.searchbox.indices.CreateIndex; import io.searchbox.indices.IndicesExists; import io.searchbox.params.Parameters; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.io.IOUtils; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.common.Base64; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.AndFilterBuilder; import org.elasticsearch.index.query.BaseQueryBuilder; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.FilteredQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermsQueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; /** * An implementation of the API Manager persistence layer that uses git to store * the entities. * * @author [email protected] */ @ApplicationScoped @Alternative public class EsStorage implements IStorage, IStorageQuery, IIdmStorage { private static final String INDEX_NAME = "apiman_manager"; //$NON-NLS-1$ private static int guidCounter = 100; @Inject @Named("storage") JestClient esClient; /** * Constructor. */ public EsStorage() { } /** * Called to initialize the storage. */ public void initialize() { try { esClient.execute(new Health.Builder().build()); // TODO Do we need a loop to wait for all nodes to join the cluster? Action<JestResult> action = new IndicesExists.Builder(INDEX_NAME).build(); JestResult result = esClient.execute(action); if (! result.isSucceeded()) { createIndex(INDEX_NAME); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @param indexName * @throws Exception */ private void createIndex(String indexName) throws Exception { CreateIndexRequest request = new CreateIndexRequest(indexName); URL settings = getClass().getResource("index-settings.json"); //$NON-NLS-1$ String source = IOUtils.toString(settings); request.source(source); JestResult response = esClient.execute(new CreateIndex.Builder(indexName).settings(source).build()); if (!response.isSucceeded()) { throw new StorageException("Failed to create index: " + indexName); //$NON-NLS-1$ } } /** * @see io.apiman.manager.api.core.IStorage#beginTx() */ @Override public void beginTx() throws StorageException { // No Transaction support for ES } /** * @see io.apiman.manager.api.core.IStorage#commitTx() */ @Override public void commitTx() throws StorageException { // No Transaction support for ES } /** * @see io.apiman.manager.api.core.IStorage#rollbackTx() */ @Override public void rollbackTx() { // No Transaction support for ES } /** * @see io.apiman.manager.api.core.IStorage#createOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean) */ @Override public void createOrganization(OrganizationBean organization) throws StorageException { indexEntity("organization", organization.getId(), EsMarshalling.marshall(organization), true); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createApplication(io.apiman.manager.api.beans.apps.ApplicationBean) */ @Override public void createApplication(ApplicationBean application) throws StorageException { indexEntity("application", id(application.getOrganization().getId(), application.getId()), EsMarshalling.marshall(application)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createApplicationVersion(io.apiman.manager.api.beans.apps.ApplicationVersionBean) */ @Override public void createApplicationVersion(ApplicationVersionBean version) throws StorageException { ApplicationBean application = version.getApplication(); String id = id(application.getOrganization().getId(), application.getId(), version.getVersion()); indexEntity("applicationVersion", id, EsMarshalling.marshall(version)); //$NON-NLS-1$ PoliciesBean policies = PoliciesBean.from(PolicyType.Application, application.getOrganization().getId(), application.getId(), version.getVersion()); indexEntity("applicationPolicies", id, EsMarshalling.marshall(policies)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createContract(io.apiman.manager.api.beans.contracts.ContractBean) */ @Override public void createContract(ContractBean contract) throws StorageException { List<ContractSummaryBean> contracts = getApplicationContracts(contract.getApplication().getApplication().getOrganization().getId(), contract.getApplication().getApplication().getId(), contract.getApplication().getVersion()); for (ContractSummaryBean csb : contracts) { if (csb.getServiceOrganizationId().equals(contract.getService().getService().getOrganization().getId()) && csb.getServiceId().equals(contract.getService().getService().getId()) && csb.getServiceVersion().equals(contract.getService().getVersion()) && csb.getPlanId().equals(contract.getPlan().getPlan().getId())) { throw new StorageException("Error creating contract: duplicate contract detected."); //$NON-NLS-1$ } } contract.setId(generateGuid()); indexEntity("contract", String.valueOf(contract.getId()), EsMarshalling.marshall(contract), true); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createService(io.apiman.manager.api.beans.services.ServiceBean) */ @Override public void createService(ServiceBean service) throws StorageException { indexEntity("service", id(service.getOrganization().getId(), service.getId()), EsMarshalling.marshall(service)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createServiceVersion(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void createServiceVersion(ServiceVersionBean version) throws StorageException { ServiceBean service = version.getService(); String id = id(service.getOrganization().getId(), service.getId(), version.getVersion()); indexEntity("serviceVersion", id, EsMarshalling.marshall(version)); //$NON-NLS-1$ PoliciesBean policies = PoliciesBean.from(PolicyType.Service, service.getOrganization().getId(), service.getId(), version.getVersion()); indexEntity("servicePolicies", id, EsMarshalling.marshall(policies)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPlan(io.apiman.manager.api.beans.plans.PlanBean) */ @Override public void createPlan(PlanBean plan) throws StorageException { indexEntity("plan", id(plan.getOrganization().getId(), plan.getId()), EsMarshalling.marshall(plan)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean) */ @Override public void createPlanVersion(PlanVersionBean version) throws StorageException { PlanBean plan = version.getPlan(); String id = id(plan.getOrganization().getId(), plan.getId(), version.getVersion()); indexEntity("planVersion", id, EsMarshalling.marshall(version)); //$NON-NLS-1$ PoliciesBean policies = PoliciesBean.from(PolicyType.Plan, plan.getOrganization().getId(), plan.getId(), version.getVersion()); indexEntity("planPolicies", id, EsMarshalling.marshall(policies)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPolicy(io.apiman.manager.api.beans.policies.PolicyBean) */ @Override public void createPolicy(PolicyBean policy) throws StorageException { String docType = getPoliciesDocType(policy.getType()); String id = id(policy.getOrganizationId(), policy.getEntityId(), policy.getEntityVersion()); Map<String, Object> source = getEntity(docType, id); if (source == null) { throw new StorageException("Failed to create policy (missing PoliciesBean)."); //$NON-NLS-1$ } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); policy.setId(generateGuid()); policies.getPolicies().add(policy); orderPolicies(policies); updateEntity(docType, id, EsMarshalling.marshall(policies)); } /** * @see io.apiman.manager.api.core.IStorage#reorderPolicies(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.util.List) */ @Override public void reorderPolicies(PolicyType type, String organizationId, String entityId, String entityVersion, List<Long> newOrder) throws StorageException { String docType = getPoliciesDocType(type); String pid = id(organizationId, entityId, entityVersion); Map<String, Object> source = getEntity(docType, pid); if (source == null) { return; } PoliciesBean policiesBean = EsMarshalling.unmarshallPolicies(source); List<PolicyBean> policies = policiesBean.getPolicies(); List<PolicyBean> reordered = new ArrayList<>(policies.size()); for (Long policyId : newOrder) { ListIterator<PolicyBean> iterator = policies.listIterator(); while (iterator.hasNext()) { PolicyBean policyBean = iterator.next(); if (policyBean.getId().equals(policyId)) { iterator.remove(); reordered.add(policyBean); break; } } } // Make sure we don't stealth-delete any policies. Put anything // remaining at the end of the list. for (PolicyBean policyBean : policies) { reordered.add(policyBean); } policiesBean.setPolicies(reordered); updateEntity(docType, pid, EsMarshalling.marshall(policiesBean)); } /** * Set the order index of all policies. * @param policies */ private void orderPolicies(PoliciesBean policies) { int idx = 1; for (PolicyBean policy : policies.getPolicies()) { policy.setOrderIndex(idx++); } } /** * @see io.apiman.manager.api.core.IStorage#createGateway(io.apiman.manager.api.beans.gateways.GatewayBean) */ @Override public void createGateway(GatewayBean gateway) throws StorageException { indexEntity("gateway", gateway.getId(), EsMarshalling.marshall(gateway)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPlugin(io.apiman.manager.api.beans.plugins.PluginBean) */ @Override public void createPlugin(PluginBean plugin) throws StorageException { plugin.setId(generateGuid()); indexEntity("plugin", String.valueOf(plugin.getId()), EsMarshalling.marshall(plugin)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createPolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) */ @Override public void createPolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException { indexEntity("policyDef", policyDef.getId(), EsMarshalling.marshall(policyDef)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#createRole(io.apiman.manager.api.beans.idm.RoleBean) */ @Override public void createRole(RoleBean role) throws StorageException { indexEntity("role", role.getId(), EsMarshalling.marshall(role)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#createAuditEntry(io.apiman.manager.api.beans.audit.AuditEntryBean) */ @Override public void createAuditEntry(AuditEntryBean entry) throws StorageException { if (entry == null) { return; } entry.setId(generateGuid()); indexEntity("auditEntry", String.valueOf(entry.getId()), EsMarshalling.marshall(entry)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#updateOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean) */ @Override public void updateOrganization(OrganizationBean organization) throws StorageException { updateEntity("organization", organization.getId(), EsMarshalling.marshall(organization)); //$NON-NLS-1$ // TODO also update all entities that inline the organization name, if that has changed! (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updateApplication(io.apiman.manager.api.beans.apps.ApplicationBean) */ @Override public void updateApplication(ApplicationBean application) throws StorageException { updateEntity("application", id(application.getOrganization().getId(), application.getId()), EsMarshalling.marshall(application)); //$NON-NLS-1$ // TODO also update the application versions (in case the description changed) (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updateApplicationVersion(io.apiman.manager.api.beans.apps.ApplicationVersionBean) */ @Override public void updateApplicationVersion(ApplicationVersionBean version) throws StorageException { ApplicationBean application = version.getApplication(); updateEntity("applicationVersion", id(application.getOrganization().getId(), application.getId(), version.getVersion()), //$NON-NLS-1$ EsMarshalling.marshall(version)); } /** * @see io.apiman.manager.api.core.IStorage#updateService(io.apiman.manager.api.beans.services.ServiceBean) */ @Override public void updateService(ServiceBean service) throws StorageException { updateEntity("service", id(service.getOrganization().getId(), service.getId()), EsMarshalling.marshall(service)); //$NON-NLS-1$ // TODO also update the service versions (in case the description changed) (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updateServiceVersion(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void updateServiceVersion(ServiceVersionBean version) throws StorageException { ServiceBean service = version.getService(); updateEntity("serviceVersion", id(service.getOrganization().getId(), service.getId(), version.getVersion()), //$NON-NLS-1$ EsMarshalling.marshall(version)); } /** * @see io.apiman.manager.api.core.IStorage#updateServiceDefinition(io.apiman.manager.api.beans.services.ServiceVersionBean, java.io.InputStream) */ @Override public void updateServiceDefinition(ServiceVersionBean version, InputStream definitionStream) throws StorageException { InputStream serviceDefinition = null; try { String id = id(version.getService().getOrganization().getId(), version.getService().getId(), version.getVersion()) + ":def"; //$NON-NLS-1$ serviceDefinition = getServiceDefinition(version); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(definitionStream, baos); String data = Base64.encodeBytes(baos.toByteArray()); ServiceDefinitionBean definition = new ServiceDefinitionBean(); definition.setData(data); if (serviceDefinition == null) { indexEntity("serviceDefinition", id, EsMarshalling.marshall(definition)); //$NON-NLS-1$ } else { updateEntity("serviceDefinition", id, EsMarshalling.marshall(definition)); //$NON-NLS-1$ } } catch (IOException e) { throw new StorageException(e); } finally { IOUtils.closeQuietly(serviceDefinition); } } /** * @see io.apiman.manager.api.core.IStorage#updatePlan(io.apiman.manager.api.beans.plans.PlanBean) */ @Override public void updatePlan(PlanBean plan) throws StorageException { updateEntity("plan", id(plan.getOrganization().getId(), plan.getId()), EsMarshalling.marshall(plan)); //$NON-NLS-1$ // TODO also update the plan versions (in case the description changed) (bulk api?) } /** * @see io.apiman.manager.api.core.IStorage#updatePlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean) */ @Override public void updatePlanVersion(PlanVersionBean version) throws StorageException { PlanBean plan = version.getPlan(); updateEntity("planVersion", id(plan.getOrganization().getId(), plan.getId(), version.getVersion()), //$NON-NLS-1$ EsMarshalling.marshall(version)); } /** * @see io.apiman.manager.api.core.IStorage#updatePolicy(io.apiman.manager.api.beans.policies.PolicyBean) */ @Override public void updatePolicy(PolicyBean policy) throws StorageException { String docType = getPoliciesDocType(policy.getType()); String pid = id(policy.getOrganizationId(), policy.getEntityId(), policy.getEntityVersion()); Map<String, Object> source = getEntity(docType, pid); if (source == null) { throw new StorageException("Policy not found."); //$NON-NLS-1$ } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); List<PolicyBean> policyBeans = policies.getPolicies(); boolean found = false; if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { if (policyBean.getId().equals(policy.getId())) { policyBean.setConfiguration(policy.getConfiguration()); policyBean.setModifiedBy(policy.getModifiedBy()); policyBean.setModifiedOn(policy.getModifiedOn()); found = true; break; } } } if (found) { updateEntity(docType, pid, EsMarshalling.marshall(policies)); } else { throw new StorageException("Policy not found."); //$NON-NLS-1$ } } /** * @see io.apiman.manager.api.core.IStorage#updateGateway(io.apiman.manager.api.beans.gateways.GatewayBean) */ @Override public void updateGateway(GatewayBean gateway) throws StorageException { updateEntity("gateway", gateway.getId(), EsMarshalling.marshall(gateway)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#updatePolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) */ @Override public void updatePolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException { updateEntity("policyDef", policyDef.getId(), EsMarshalling.marshall(policyDef)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#updateRole(io.apiman.manager.api.beans.idm.RoleBean) */ @Override public void updateRole(RoleBean role) throws StorageException { updateEntity("role", role.getId(), EsMarshalling.marshall(role)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean) */ @Override public void deleteOrganization(OrganizationBean organization) throws StorageException { deleteEntity("organization", organization.getId()); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteApplication(io.apiman.manager.api.beans.apps.ApplicationBean) */ @Override public void deleteApplication(ApplicationBean application) throws StorageException { deleteEntity("application", id(application.getOrganization().getId(), application.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteApplicationVersion(io.apiman.manager.api.beans.apps.ApplicationVersionBean) */ @Override public void deleteApplicationVersion(ApplicationVersionBean version) throws StorageException { ApplicationBean application = version.getApplication(); deleteEntity("applicationVersion", id(application.getOrganization().getId(), application.getId(), version.getVersion())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteContract(io.apiman.manager.api.beans.contracts.ContractBean) */ @Override public void deleteContract(ContractBean contract) throws StorageException { deleteEntity("contract", String.valueOf(contract.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteService(io.apiman.manager.api.beans.services.ServiceBean) */ @Override public void deleteService(ServiceBean service) throws StorageException { deleteEntity("service", id(service.getOrganization().getId(), service.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteServiceVersion(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void deleteServiceVersion(ServiceVersionBean version) throws StorageException { ServiceBean service = version.getService(); deleteEntity("serviceVersion", id(service.getOrganization().getId(), service.getId(), version.getVersion())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deleteServiceDefinition(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public void deleteServiceDefinition(ServiceVersionBean version) throws StorageException { String id = id(version.getService().getOrganization().getId(), version.getService().getId(), version.getVersion()) + ":def"; //$NON-NLS-1$ deleteEntity("serviceDefinition", id); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePlan(io.apiman.manager.api.beans.plans.PlanBean) */ @Override public void deletePlan(PlanBean plan) throws StorageException { deleteEntity("plan", id(plan.getOrganization().getId(), plan.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean) */ @Override public void deletePlanVersion(PlanVersionBean version) throws StorageException { PlanBean plan = version.getPlan(); deleteEntity("planVersion", id(plan.getOrganization().getId(), plan.getId(), version.getVersion())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePolicy(io.apiman.manager.api.beans.policies.PolicyBean) */ @Override public void deletePolicy(PolicyBean policy) throws StorageException { String docType = getPoliciesDocType(policy.getType()); String pid = id(policy.getOrganizationId(), policy.getEntityId(), policy.getEntityVersion()); Map<String, Object> source = getEntity(docType, pid); if (source == null) { throw new StorageException("Policy not found."); //$NON-NLS-1$ } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); if (policies == null) throw new StorageException("Policy not found."); //$NON-NLS-1$ List<PolicyBean> policyBeans = policies.getPolicies(); boolean found = false; if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { if (policyBean.getId().equals(policy.getId())) { policies.getPolicies().remove(policyBean); found = true; break; } } } if (found) { updateEntity(docType, pid, EsMarshalling.marshall(policies)); } else { throw new StorageException("Policy not found."); //$NON-NLS-1$ } } /** * @see io.apiman.manager.api.core.IStorage#deleteGateway(io.apiman.manager.api.beans.gateways.GatewayBean) */ @Override public void deleteGateway(GatewayBean gateway) throws StorageException { deleteEntity("gateway", gateway.getId()); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePlugin(io.apiman.manager.api.beans.plugins.PluginBean) */ @Override public void deletePlugin(PluginBean plugin) throws StorageException { deleteEntity("plugin", String.valueOf(plugin.getId())); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#deletePolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean) */ @Override public void deletePolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException { deleteEntity("policyDef", policyDef.getId()); //$NON-NLS-1$ } /* (non-Javadoc) * @see io.apiman.manager.api.core.IIdmStorage#deleteRole(io.apiman.manager.api.beans.idm.RoleBean) */ @Override public void deleteRole(RoleBean role) throws StorageException { deleteEntity("role", role.getId()); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IStorage#getOrganization(java.lang.String) */ @Override public OrganizationBean getOrganization(String id) throws StorageException { Map<String, Object> source = getEntity("organization", id); //$NON-NLS-1$ return EsMarshalling.unmarshallOrganization(source); } /** * @see io.apiman.manager.api.core.IStorage#getApplication(java.lang.String, java.lang.String) */ @Override public ApplicationBean getApplication(String organizationId, String id) throws StorageException { Map<String, Object> source = getEntity("application", id(organizationId, id)); //$NON-NLS-1$ if (source == null) { return null; } ApplicationBean bean = EsMarshalling.unmarshallApplication(source); bean.setOrganization(getOrganization(organizationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getApplicationVersion(java.lang.String, java.lang.String, java.lang.String) */ @Override public ApplicationVersionBean getApplicationVersion(String organizationId, String applicationId, String version) throws StorageException { Map<String, Object> source = getEntity("applicationVersion", id(organizationId, applicationId, version)); //$NON-NLS-1$ if (source == null) { return null; } ApplicationVersionBean bean = EsMarshalling.unmarshallApplicationVersion(source); bean.setApplication(getApplication(organizationId, applicationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getContract(java.lang.Long) */ @SuppressWarnings("nls") @Override public ContractBean getContract(Long id) throws StorageException { Map<String, Object> source = getEntity("contract", String.valueOf(id)); //$NON-NLS-1$ ContractBean contract = EsMarshalling.unmarshallContract(source); String appOrgId = (String) source.get("appOrganizationId"); String appId = (String) source.get("appId"); String appVersion = (String) source.get("appVersion"); String svcOrgId = (String) source.get("serviceOrganizationId"); String svcId = (String) source.get("serviceId"); String svcVersion = (String) source.get("serviceVersion"); String planId = (String) source.get("planId"); String planVersion = (String) source.get("planVersion"); ApplicationVersionBean avb = getApplicationVersion(appOrgId, appId, appVersion); ServiceVersionBean svb = getServiceVersion(svcOrgId, svcId, svcVersion); PlanVersionBean pvb = getPlanVersion(svcOrgId, planId, planVersion); contract.setApplication(avb); contract.setPlan(pvb); contract.setService(svb); return contract; } /** * @see io.apiman.manager.api.core.IStorage#getService(java.lang.String, java.lang.String) */ @Override public ServiceBean getService(String organizationId, String id) throws StorageException { Map<String, Object> source = getEntity("service", id(organizationId, id)); //$NON-NLS-1$ if (source == null) { return null; } ServiceBean bean = EsMarshalling.unmarshallService(source); bean.setOrganization(getOrganization(organizationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getServiceVersion(java.lang.String, java.lang.String, java.lang.String) */ @Override public ServiceVersionBean getServiceVersion(String organizationId, String serviceId, String version) throws StorageException { Map<String, Object> source = getEntity("serviceVersion", id(organizationId, serviceId, version)); //$NON-NLS-1$ if (source == null) { return null; } ServiceVersionBean bean = EsMarshalling.unmarshallServiceVersion(source); bean.setService(getService(organizationId, serviceId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getServiceDefinition(io.apiman.manager.api.beans.services.ServiceVersionBean) */ @Override public InputStream getServiceDefinition(ServiceVersionBean version) throws StorageException { try { String id = id(version.getService().getOrganization().getId(), version.getService().getId(), version.getVersion()) + ":def"; //$NON-NLS-1$ Map<String, Object> source = getEntity("serviceDefinition", id); //$NON-NLS-1$ if (source == null) { return null; } ServiceDefinitionBean def = EsMarshalling.unmarshallServiceDefinition(source); if (def == null) return null; String data = def.getData(); return new ByteArrayInputStream(Base64.decode(data)); } catch (IOException e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IStorage#getPlan(java.lang.String, java.lang.String) */ @Override public PlanBean getPlan(String organizationId, String id) throws StorageException { Map<String, Object> source = getEntity("plan", id(organizationId, id)); //$NON-NLS-1$ if (source == null) { return null; } PlanBean bean = EsMarshalling.unmarshallPlan(source); bean.setOrganization(getOrganization(organizationId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getPlanVersion(java.lang.String, java.lang.String, java.lang.String) */ @Override public PlanVersionBean getPlanVersion(String organizationId, String planId, String version) throws StorageException { Map<String, Object> source = getEntity("planVersion", id(organizationId, planId, version)); //$NON-NLS-1$ if (source == null) { return null; } PlanVersionBean bean = EsMarshalling.unmarshallPlanVersion(source); bean.setPlan(getPlan(organizationId, planId)); return bean; } /** * @see io.apiman.manager.api.core.IStorage#getPolicy(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.lang.Long) */ @Override public PolicyBean getPolicy(PolicyType type, String organizationId, String entityId, String version, Long id) throws StorageException { String docType = getPoliciesDocType(type); String pid = id(organizationId, entityId, version); Map<String, Object> source = getEntity(docType, pid); if (source == null) { return null; } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); if (policies == null) return null; List<PolicyBean> policyBeans = policies.getPolicies(); if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { if (policyBean.getId().equals(id)) { PolicyDefinitionBean def = getPolicyDefinition(policyBean.getDefinition().getId()); policyBean.setDefinition(def); return policyBean; } } } return null; } /** * @see io.apiman.manager.api.core.IStorage#getGateway(java.lang.String) */ @Override public GatewayBean getGateway(String id) throws StorageException { Map<String, Object> source = getEntity("gateway", id); //$NON-NLS-1$ return EsMarshalling.unmarshallGateway(source); } /** * @see io.apiman.manager.api.core.IStorage#getPlugin(long) */ @Override public PluginBean getPlugin(long id) throws StorageException { Map<String, Object> source = getEntity("plugin", String.valueOf(id)); //$NON-NLS-1$ return EsMarshalling.unmarshallPlugin(source); } /** * @see io.apiman.manager.api.core.IStorage#getPlugin(java.lang.String, java.lang.String) */ @Override public PluginBean getPlugin(String groupId, String artifactId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("groupId", groupId), FilterBuilders.termFilter("artifactId", artifactId) ) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(2); SearchRequest request = new SearchRequest(INDEX_NAME); request.types("plugin"); //$NON-NLS-1$ request.source(builder); List<Hit<Map<String,Object>,Void>> hits = listEntities("plugin", builder); //$NON-NLS-1$ if (hits.size() == 1) { Hit<Map<String,Object>,Void> hit = hits.iterator().next(); return EsMarshalling.unmarshallPlugin(hit.source); } return null; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IStorage#getPolicyDefinition(java.lang.String) */ @Override public PolicyDefinitionBean getPolicyDefinition(String id) throws StorageException { Map<String, Object> source = getEntity("policyDef", id); //$NON-NLS-1$ return EsMarshalling.unmarshallPolicyDefinition(source); } /** * @see io.apiman.manager.api.core.IIdmStorage#getRole(java.lang.String) */ @Override public RoleBean getRole(String id) throws StorageException { Map<String, Object> source = getEntity("role", id); //$NON-NLS-1$ return EsMarshalling.unmarshallRole(source); } /** * @see io.apiman.manager.api.core.IStorageQuery#listPlugins() */ @Override public List<PluginSummaryBean> listPlugins() throws StorageException { @SuppressWarnings("nls") String[] fields = {"id", "artifactId", "groupId", "version", "classifier", "type", "name", "description", "createdBy", "createdOn"}; SearchSourceBuilder builder = new SearchSourceBuilder() .fetchSource(fields, null).sort("name.raw", SortOrder.ASC).size(200); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("plugin", builder); //$NON-NLS-1$ List<PluginSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PluginSummaryBean bean = EsMarshalling.unmarshallPluginSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#listGateways() */ @Override public List<GatewaySummaryBean> listGateways() throws StorageException { @SuppressWarnings("nls") String[] fields = {"id", "name", "description","type"}; SearchSourceBuilder builder = new SearchSourceBuilder().fetchSource(fields, null).sort("name.raw", SortOrder.ASC).size(100); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("gateway", builder); //$NON-NLS-1$ List<GatewaySummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { GatewaySummaryBean bean = EsMarshalling.unmarshallGatewaySummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#findOrganizations(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<OrganizationSummaryBean> findOrganizations(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "organization", new IUnmarshaller<OrganizationSummaryBean>() { //$NON-NLS-1$ @Override public OrganizationSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallOrganizationSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#findApplications(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<ApplicationSummaryBean> findApplications(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "application", new IUnmarshaller<ApplicationSummaryBean>() { //$NON-NLS-1$ @Override public ApplicationSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallApplicationSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#findServices(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<ServiceSummaryBean> findServices(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "service", new IUnmarshaller<ServiceSummaryBean>() { //$NON-NLS-1$ @Override public ServiceSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallServiceSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#findPlans(java.lang.String, io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<PlanSummaryBean> findPlans(String organizationId, SearchCriteriaBean criteria) throws StorageException { criteria.addFilter("organizationId", organizationId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ return find(criteria, "plan", new IUnmarshaller<PlanSummaryBean>() { //$NON-NLS-1$ @Override public PlanSummaryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallPlanSummary(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#auditEntity(java.lang.String, java.lang.String, java.lang.String, java.lang.Class, io.apiman.manager.api.beans.search.PagingBean) */ @Override public <T> SearchResultsBean<AuditEntryBean> auditEntity(String organizationId, String entityId, String entityVersion, Class<T> type, PagingBean paging) throws StorageException { SearchCriteriaBean criteria = new SearchCriteriaBean(); if (paging != null) { criteria.setPaging(paging); } else { criteria.setPage(1); criteria.setPageSize(20); } criteria.setOrder("createdOn", false); //$NON-NLS-1$ if (organizationId != null) { criteria.addFilter("organizationId", organizationId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } if (entityId != null) { criteria.addFilter("entityId", entityId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } if (entityVersion != null) { criteria.addFilter("entityVersion", entityVersion, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } if (type != null) { AuditEntityType entityType = null; if (type == OrganizationBean.class) { entityType = AuditEntityType.Organization; } else if (type == ApplicationBean.class) { entityType = AuditEntityType.Application; } else if (type == ServiceBean.class) { entityType = AuditEntityType.Service; } else if (type == PlanBean.class) { entityType = AuditEntityType.Plan; } if (entityType != null) { criteria.addFilter("entityType", entityType.name(), SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } } return find(criteria, "auditEntry", new IUnmarshaller<AuditEntryBean>() { //$NON-NLS-1$ @Override public AuditEntryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallAuditEntry(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#auditUser(java.lang.String, io.apiman.manager.api.beans.search.PagingBean) */ @Override public <T> SearchResultsBean<AuditEntryBean> auditUser(String userId, PagingBean paging) throws StorageException { SearchCriteriaBean criteria = new SearchCriteriaBean(); if (paging != null) { criteria.setPaging(paging); } else { criteria.setPage(1); criteria.setPageSize(20); } criteria.setOrder("createdOn", false); //$NON-NLS-1$ if (userId != null) { criteria.addFilter("who", userId, SearchCriteriaFilterOperator.eq); //$NON-NLS-1$ } return find(criteria, "auditEntry", new IUnmarshaller<AuditEntryBean>() { //$NON-NLS-1$ @Override public AuditEntryBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallAuditEntry(source); } }); } /** * @see io.apiman.manager.api.core.IStorageQuery#getOrgs(java.util.Set) */ @Override public List<OrganizationSummaryBean> getOrgs(Set<String> organizationIds) throws StorageException { List<OrganizationSummaryBean> orgs = new ArrayList<>(); if (organizationIds == null || organizationIds.isEmpty()) { return orgs; } @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termsFilter("id", organizationIds.toArray()) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("name.raw", SortOrder.ASC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("organization", builder); //$NON-NLS-1$ List<OrganizationSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { OrganizationSummaryBean bean = EsMarshalling.unmarshallOrganizationSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationsInOrgs(java.util.Set) */ @Override public List<ApplicationSummaryBean> getApplicationsInOrgs(Set<String> organizationIds) throws StorageException { @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("organizationName.raw", SortOrder.ASC) .sort("name.raw", SortOrder.ASC) .size(500); TermsQueryBuilder query = QueryBuilders.termsQuery("organizationId", organizationIds.toArray(new String[organizationIds.size()])); //$NON-NLS-1$ builder.query(query); List<Hit<Map<String,Object>,Void>> hits = listEntities("application", builder); //$NON-NLS-1$ List<ApplicationSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ApplicationSummaryBean bean = EsMarshalling.unmarshallApplicationSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationsInOrg(java.lang.String) */ @Override public List<ApplicationSummaryBean> getApplicationsInOrg(String organizationId) throws StorageException { Set<String> orgs = new HashSet<>(); orgs.add(organizationId); return getApplicationsInOrgs(orgs); } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationVersions(java.lang.String, java.lang.String) */ @Override public List<ApplicationVersionSummaryBean> getApplicationVersions(String organizationId, String applicationId) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("applicationId", applicationId)) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("createdOn", SortOrder.DESC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("applicationVersion", builder); //$NON-NLS-1$ List<ApplicationVersionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ApplicationVersionSummaryBean bean = EsMarshalling.unmarshallApplicationVersionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApplicationContracts(java.lang.String, java.lang.String, java.lang.String) */ @Override public List<ContractSummaryBean> getApplicationContracts(String organizationId, String applicationId, String version) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("appOrganizationId", organizationId), FilterBuilders.termFilter("appId", applicationId), FilterBuilders.termFilter("appVersion", version) ) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder().sort("serviceOrganizationId", SortOrder.ASC) .sort("serviceId", SortOrder.ASC).query(query).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("contract", builder); //$NON-NLS-1$ List<ContractSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ContractSummaryBean bean = EsMarshalling.unmarshallContractSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getApiRegistry(java.lang.String, java.lang.String, java.lang.String) */ @Override public ApiRegistryBean getApiRegistry(String organizationId, String applicationId, String version) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("appOrganizationId", organizationId), FilterBuilders.termFilter("appId", applicationId), FilterBuilders.termFilter("appVersion", version) ) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder().sort("id", SortOrder.ASC).query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("contract", builder); //$NON-NLS-1$ ApiRegistryBean registry = new ApiRegistryBean(); for (Hit<Map<String,Object>,Void> hit : hits) { ApiEntryBean bean = EsMarshalling.unmarshallApiEntry(hit.source); ServiceVersionBean svb = getServiceVersion(bean.getServiceOrgId(), bean.getServiceId(), bean.getServiceVersion()); Set<ServiceGatewayBean> gateways = svb.getGateways(); if (gateways != null && gateways.size() > 0) { ServiceGatewayBean sgb = gateways.iterator().next(); bean.setGatewayId(sgb.getGatewayId()); } registry.getApis().add(bean); } return registry; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServicesInOrgs(java.util.Set) */ @Override public List<ServiceSummaryBean> getServicesInOrgs(Set<String> organizationIds) throws StorageException { @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("organizationName.raw", SortOrder.ASC) .sort("name.raw", SortOrder.ASC) .size(500); TermsQueryBuilder query = QueryBuilders.termsQuery("organizationId", organizationIds.toArray(new String[organizationIds.size()])); //$NON-NLS-1$ builder.query(query); List<Hit<Map<String,Object>,Void>> hits = listEntities("service", builder); //$NON-NLS-1$ List<ServiceSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ServiceSummaryBean bean = EsMarshalling.unmarshallServiceSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServicesInOrg(java.lang.String) */ @Override public List<ServiceSummaryBean> getServicesInOrg(String organizationId) throws StorageException { Set<String> orgs = new HashSet<>(); orgs.add(organizationId); return getServicesInOrgs(orgs); } /** * @see io.apiman.manager.api.core.IStorageQuery#getServiceVersions(java.lang.String, java.lang.String) */ @Override public List<ServiceVersionSummaryBean> getServiceVersions(String organizationId, String serviceId) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("serviceId", serviceId)) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("createdOn", SortOrder.DESC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("serviceVersion", builder); //$NON-NLS-1$ List<ServiceVersionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ServiceVersionSummaryBean bean = EsMarshalling.unmarshallServiceVersionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServiceVersionPlans(java.lang.String, java.lang.String, java.lang.String) */ @Override public List<ServicePlanSummaryBean> getServiceVersionPlans(String organizationId, String serviceId, String version) throws StorageException { List<ServicePlanSummaryBean> rval = new ArrayList<>(); ServiceVersionBean versionBean = getServiceVersion(organizationId, serviceId, version); if (versionBean != null) { Set<ServicePlanBean> plans = versionBean.getPlans(); if (plans != null) { for (ServicePlanBean spb : plans) { PlanBean planBean = getPlan(organizationId, spb.getPlanId()); ServicePlanSummaryBean plan = new ServicePlanSummaryBean(); plan.setPlanId(spb.getPlanId()); plan.setVersion(spb.getVersion()); plan.setPlanName(planBean.getName()); plan.setPlanDescription(planBean.getDescription()); rval.add(plan); } } } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getPlansInOrgs(java.util.Set) */ @Override public List<PlanSummaryBean> getPlansInOrgs(Set<String> organizationIds) throws StorageException { @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("organizationName.raw", SortOrder.ASC) .sort("name.raw", SortOrder.ASC) .size(500); TermsQueryBuilder query = QueryBuilders.termsQuery("organizationId", organizationIds.toArray(new String[organizationIds.size()])); //$NON-NLS-1$ builder.query(query); List<Hit<Map<String,Object>,Void>> hits = listEntities("plan", builder); //$NON-NLS-1$ List<PlanSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PlanSummaryBean bean = EsMarshalling.unmarshallPlanSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getPlansInOrg(java.lang.String) */ @Override public List<PlanSummaryBean> getPlansInOrg(String organizationId) throws StorageException { Set<String> orgs = new HashSet<>(); orgs.add(organizationId); return getPlansInOrgs(orgs); } /** * @see io.apiman.manager.api.core.IStorageQuery#getPlanVersions(java.lang.String, java.lang.String) */ @Override public List<PlanVersionSummaryBean> getPlanVersions(String organizationId, String planId) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("planId", planId)) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder() .sort("createdOn", SortOrder.DESC) .query(query) .size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("planVersion", builder); //$NON-NLS-1$ List<PlanVersionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PlanVersionSummaryBean bean = EsMarshalling.unmarshallPlanVersionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getPolicies(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType) */ @Override public List<PolicySummaryBean> getPolicies(String organizationId, String entityId, String version, PolicyType type) throws StorageException { try { String docType = getPoliciesDocType(type); String pid = id(organizationId, entityId, version); List<PolicySummaryBean> rval = new ArrayList<>(); Map<String, Object> source = getEntity(docType, pid); if (source == null) { return rval; } PoliciesBean policies = EsMarshalling.unmarshallPolicies(source); if (policies == null) return rval; List<PolicyBean> policyBeans = policies.getPolicies(); if (policyBeans != null) { for (PolicyBean policyBean : policyBeans) { PolicyDefinitionBean def = getPolicyDefinition(policyBean.getDefinition().getId()); policyBean.setDefinition(def); PolicyTemplateUtil.generatePolicyDescription(policyBean); PolicySummaryBean psb = new PolicySummaryBean(); psb.setCreatedBy(policyBean.getCreatedBy()); psb.setCreatedOn(policyBean.getCreatedOn()); psb.setDescription(policyBean.getDescription()); psb.setIcon(def.getIcon()); psb.setId(policyBean.getId()); psb.setName(policyBean.getName()); psb.setPolicyDefinitionId(def.getId()); rval.add(psb); } } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IStorageQuery#listPolicyDefinitions() */ @Override public List<PolicyDefinitionSummaryBean> listPolicyDefinitions() throws StorageException { @SuppressWarnings("nls") String[] fields = {"id", "policyImpl", "name", "description", "icon", "pluginId", "formType"}; SearchSourceBuilder builder = new SearchSourceBuilder() .fetchSource(fields, null) .sort("name.raw", SortOrder.ASC).size(100); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("policyDef", builder); //$NON-NLS-1$ List<PolicyDefinitionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PolicyDefinitionSummaryBean bean = EsMarshalling.unmarshallPolicyDefinitionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getServiceContracts(java.lang.String, java.lang.String, java.lang.String, int, int) */ @Override public List<ContractSummaryBean> getServiceContracts(String organizationId, String serviceId, String version, int page, int pageSize) throws StorageException { @SuppressWarnings("nls") QueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("serviceOrganizationId", organizationId), FilterBuilders.termFilter("serviceId", serviceId), FilterBuilders.termFilter("serviceVersion", version) ) ); @SuppressWarnings("nls") SearchSourceBuilder builder = new SearchSourceBuilder().sort("appOrganizationId", SortOrder.ASC) .sort("appId", SortOrder.ASC).query(query).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("contract", builder); //$NON-NLS-1$ List<ContractSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { ContractSummaryBean bean = EsMarshalling.unmarshallContractSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IStorageQuery#getMaxPolicyOrderIndex(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType) */ @Override public int getMaxPolicyOrderIndex(String organizationId, String entityId, String entityVersion, PolicyType type) throws StorageException { // We'll figure this out later, when adding a policy. return -1; } /** * @see io.apiman.manager.api.core.IStorageQuery#listPluginPolicyDefs(java.lang.Long) */ @Override public List<PolicyDefinitionSummaryBean> listPluginPolicyDefs(Long pluginId) throws StorageException { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("pluginId", pluginId) ); @SuppressWarnings("nls") String[] fields = {"id", "policyImpl", "name", "description", "icon", "pluginId", "formType"}; SearchSourceBuilder builder = new SearchSourceBuilder() .fetchSource(fields, null) .query(qb) .sort("name.raw", SortOrder.ASC).size(100); //$NON-NLS-1$ List<Hit<Map<String,Object>,Void>> hits = listEntities("policyDef", builder); //$NON-NLS-1$ List<PolicyDefinitionSummaryBean> rval = new ArrayList<>(hits.size()); for (Hit<Map<String,Object>,Void> hit : hits) { PolicyDefinitionSummaryBean bean = EsMarshalling.unmarshallPolicyDefinitionSummary(hit.source); rval.add(bean); } return rval; } /** * @see io.apiman.manager.api.core.IIdmStorage#createUser(io.apiman.manager.api.beans.idm.UserBean) */ @Override public void createUser(UserBean user) throws StorageException { indexEntity("user", user.getUsername(), EsMarshalling.marshall(user)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#getUser(java.lang.String) */ @Override public UserBean getUser(String userId) throws StorageException { Map<String, Object> source = getEntity("user", userId); //$NON-NLS-1$ return EsMarshalling.unmarshallUser(source); } /** * @see io.apiman.manager.api.core.IIdmStorage#updateUser(io.apiman.manager.api.beans.idm.UserBean) */ @Override public void updateUser(UserBean user) throws StorageException { updateEntity("user", user.getUsername(), EsMarshalling.marshall(user)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#findUsers(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<UserBean> findUsers(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "user", new IUnmarshaller<UserBean>() { //$NON-NLS-1$ @Override public UserBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallUser(source); } }); } /** * @see io.apiman.manager.api.core.IIdmStorage#findRoles(io.apiman.manager.api.beans.search.SearchCriteriaBean) */ @Override public SearchResultsBean<RoleBean> findRoles(SearchCriteriaBean criteria) throws StorageException { return find(criteria, "role", new IUnmarshaller<RoleBean>() { //$NON-NLS-1$ @Override public RoleBean unmarshal(Map<String, Object> source) { return EsMarshalling.unmarshallRole(source); } }); } /** * @see io.apiman.manager.api.core.IIdmStorage#createMembership(io.apiman.manager.api.beans.idm.RoleMembershipBean) */ @Override public void createMembership(RoleMembershipBean membership) throws StorageException { membership.setId(generateGuid()); String id = id(membership.getOrganizationId(), membership.getUserId(), membership.getRoleId()); indexEntity("roleMembership", id, EsMarshalling.marshall(membership)); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#getMembership(java.lang.String, java.lang.String, java.lang.String) */ @Override public RoleMembershipBean getMembership(String userId, String roleId, String organizationId) throws StorageException { String id = id(organizationId, userId, roleId); Map<String, Object> source = getEntity("roleMembership", id); //$NON-NLS-1$ if (source == null) { return null; } else { return EsMarshalling.unmarshallRoleMembership(source); } } /** * @see io.apiman.manager.api.core.IIdmStorage#deleteMembership(java.lang.String, java.lang.String, java.lang.String) */ @Override public void deleteMembership(String userId, String roleId, String organizationId) throws StorageException { String id = id(organizationId, userId, roleId); deleteEntity("roleMembership", id); //$NON-NLS-1$ } /** * @see io.apiman.manager.api.core.IIdmStorage#deleteMemberships(java.lang.String, java.lang.String) */ @Override @SuppressWarnings("nls") public void deleteMemberships(String userId, String organizationId) throws StorageException { FilteredQueryBuilder query = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("organizationId", organizationId), FilterBuilders.termFilter("userId", userId)) ); String string = query.toString(); // Workaround for bug in FilteredQueryBuilder which does not (yet) wrap // the JSON in a query element if (string.indexOf("query") < 0 || string.indexOf("query") > 7) { string = "{ \"query\" : " + string + "}"; } DeleteByQuery deleteByQuery = new DeleteByQuery.Builder(string).addIndex(INDEX_NAME) .addType("roleMembership").build(); try { JestResult response = esClient.execute(deleteByQuery); if (!response.isSucceeded()) { throw new StorageException(response.getErrorMessage()); } } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getUserMemberships(java.lang.String) */ @Override public Set<RoleMembershipBean> getUserMemberships(String userId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("userId", userId) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(2); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<RoleMembershipBean> rval = new HashSet<>(); for (Hit<Map<String,Object>,Void> hit : hits) { RoleMembershipBean roleMembership = EsMarshalling.unmarshallRoleMembership(hit.source); rval.add(roleMembership); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getUserMemberships(java.lang.String, java.lang.String) */ @Override public Set<RoleMembershipBean> getUserMemberships(String userId, String organizationId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.andFilter( FilterBuilders.termFilter("userId", userId), FilterBuilders.termFilter("organizationId", organizationId) ) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(2); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<RoleMembershipBean> rval = new HashSet<>(); for (Hit<Map<String,Object>,Void> hit : hits) { RoleMembershipBean roleMembership = EsMarshalling.unmarshallRoleMembership(hit.source); rval.add(roleMembership); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getOrgMemberships(java.lang.String) */ @Override public Set<RoleMembershipBean> getOrgMemberships(String organizationId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("organizationId", organizationId) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<RoleMembershipBean> rval = new HashSet<>(); for (Hit<Map<String,Object>,Void> hit : hits) { RoleMembershipBean roleMembership = EsMarshalling.unmarshallRoleMembership(hit.source); rval.add(roleMembership); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * @see io.apiman.manager.api.core.IIdmStorage#getPermissions(java.lang.String) */ @Override public Set<PermissionBean> getPermissions(String userId) throws StorageException { try { @SuppressWarnings("nls") QueryBuilder qb = QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("userId", userId) ); SearchSourceBuilder builder = new SearchSourceBuilder().query(qb).size(500); List<Hit<Map<String,Object>,Void>> hits = listEntities("roleMembership", builder); //$NON-NLS-1$ Set<PermissionBean> rval = new HashSet<>(hits.size()); if (hits.size() > 0) { for (Hit<Map<String,Object>,Void> hit : hits) { Map<String, Object> source = hit.source; String roleId = String.valueOf(source.get("roleId")); //$NON-NLS-1$ String qualifier = String.valueOf(source.get("organizationId")); //$NON-NLS-1$ RoleBean role = getRole(roleId); if (role != null) { for (PermissionType permission : role.getPermissions()) { PermissionBean p = new PermissionBean(); p.setName(permission); p.setOrganizationId(qualifier); rval.add(p); } } } } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * Indexes an entity. * @param type * @param id * @param entitySource * @throws StorageException */ private void indexEntity(String type, String id, XContentBuilder sourceEntity) throws StorageException { indexEntity(type, id, sourceEntity, false); } /** * Indexes an entity. * @param type * @param id * @param entitySource * @param refresh true if the operation should wait for a refresh before it returns * @throws StorageException */ @SuppressWarnings("nls") private void indexEntity(String type, String id, XContentBuilder sourceEntity, boolean refresh) throws StorageException { try { String json = sourceEntity.string(); JestResult response = esClient.execute(new Index.Builder(json).refresh(refresh).index(INDEX_NAME) .setParameter(Parameters.OP_TYPE, "create").type(type).id(id).build()); if (!response.isSucceeded()) { throw new StorageException("Failed to index document " + id + " of type " + type + "."); } } catch (StorageException e) { throw e; } catch (Exception e) { throw new StorageException(e); } } /** * Gets an entity. Callers must unmarshal the resulting map. * @param type * @param id * @throws StorageException */ private Map<String, Object> getEntity(String type, String id) throws StorageException { try { JestResult response = esClient.execute(new Get.Builder(INDEX_NAME, id).type(type).build()); if (!response.isSucceeded()) { return null; } return response.getSourceAsObject(Map.class); } catch (Exception e) { throw new StorageException(e); } } /** * Returns a list of entities. * @param type * @param searchSourceBuilder * @throws StorageException */ private List<Hit<Map<String, Object>, Void>> listEntities(String type, SearchSourceBuilder searchSourceBuilder) throws StorageException { try { String query = searchSourceBuilder.toString(); Search search = new Search.Builder(query).addIndex(INDEX_NAME).addType(type).build(); SearchResult response = esClient.execute(search); @SuppressWarnings({ "rawtypes", "unchecked" }) List<Hit<Map<String, Object>, Void>> thehits = (List) response.getHits(Map.class); return thehits; } catch (Exception e) { throw new StorageException(e); } } /** * Deletes an entity. * @param type * @param id * @throws StorageException */ private void deleteEntity(String type, String id) throws StorageException { try { JestResult response = esClient.execute(new Delete.Builder(id).index(INDEX_NAME).type(type).build()); if (!response.isSucceeded()) { throw new StorageException("Document could not be deleted because it did not exist."); //$NON-NLS-1$ } } catch (StorageException e) { throw e; } catch (Exception e) { throw new StorageException(e); } } /** * Updates a single entity. * @param type * @param id * @param source * @throws StorageException */ private void updateEntity(String type, String id, XContentBuilder source) throws StorageException { try { String doc = source.string(); /* JestResult response = */esClient.execute(new Index.Builder(doc) .setParameter(Parameters.OP_TYPE, "index").index(INDEX_NAME).type(type).id(id).build()); //$NON-NLS-1$ } catch (Exception e) { throw new StorageException(e); } } /** * Finds entities using a generic search criteria bean. * @param criteria * @param type * @param unmarshaller * @throws StorageException */ private <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, String type, IUnmarshaller<T> unmarshaller) throws StorageException { try { SearchResultsBean<T> rval = new SearchResultsBean<>(); // Set some default in the case that paging information was not included in the request. PagingBean paging = criteria.getPaging(); if (paging == null) { paging = new PagingBean(); paging.setPage(1); paging.setPageSize(20); } int page = paging.getPage(); int pageSize = paging.getPageSize(); int start = (page - 1) * pageSize; SearchSourceBuilder builder = new SearchSourceBuilder().size(pageSize).from(start).fetchSource(true); // Sort order OrderByBean orderBy = criteria.getOrderBy(); if (orderBy != null) { String name = orderBy.getName(); if (name.equals("name") || name.equals("fullName")) { //$NON-NLS-1$ //$NON-NLS-2$ name += ".raw"; //$NON-NLS-1$ } if (orderBy.isAscending()) { builder.sort(name, SortOrder.ASC); } else { builder.sort(name, SortOrder.DESC); } } // Now process the filter criteria List<SearchCriteriaFilterBean> filters = criteria.getFilters(); BaseQueryBuilder q = QueryBuilders.matchAllQuery(); if (filters != null && !filters.isEmpty()) { AndFilterBuilder andFilter = FilterBuilders.andFilter(); int filterCount = 0; for (SearchCriteriaFilterBean filter : filters) { if (filter.getOperator() == SearchCriteriaFilterOperator.eq) { andFilter.add(FilterBuilders.termFilter(filter.getName(), filter.getValue())); filterCount++; } else if (filter.getOperator() == SearchCriteriaFilterOperator.like) { q = QueryBuilders.wildcardQuery(filter.getName(), filter.getValue().toLowerCase().replace('%', '*')); } else if (filter.getOperator() == SearchCriteriaFilterOperator.bool_eq) { andFilter.add(FilterBuilders.termFilter(filter.getName(), "true".equals(filter.getValue()))); //$NON-NLS-1$ filterCount++; } // TODO implement the other filter operators here! } if (filterCount > 0) { q = QueryBuilders.filteredQuery(q, andFilter); } } builder.query(q); String query = builder.toString(); Search search = new Search.Builder(query).addIndex(INDEX_NAME) .addType(type).build(); SearchResult response = esClient.execute(search); @SuppressWarnings({ "unchecked", "rawtypes" }) List<Hit<Map<String, Object>, Void>> thehits = (List) response.getHits(Map.class); rval.setTotalSize(response.getTotal()); for (Hit<Map<String,Object>,Void> hit : thehits) { Map<String, Object> sourceAsMap = hit.source; T bean = unmarshaller.unmarshal(sourceAsMap); rval.getBeans().add(bean); } return rval; } catch (Exception e) { throw new StorageException(e); } } /** * Generates a (hopefully) unique ID. Mimics JPA's auto-generated long ID column. */ private static synchronized Long generateGuid() { StringBuilder builder = new StringBuilder(); builder.append(System.currentTimeMillis()); builder.append(guidCounter++); // Reset the counter if it gets too high. It's always a number // between 100 and 999 so that the # of digits in the guid is // always the same. if (guidCounter > 999) { guidCounter = 100; } return Long.parseLong(builder.toString()); } /** * Returns the policies document type to use given the policy type. * @param type */ private static String getPoliciesDocType(PolicyType type) { String docType = "planPolicies"; //$NON-NLS-1$ if (type == PolicyType.Service) { docType = "servicePolicies"; //$NON-NLS-1$ } else if (type == PolicyType.Application) { docType = "applicationPolicies"; //$NON-NLS-1$ } return docType; } /** * A composite ID created from an organization ID and entity ID. * @param organizationId * @param entityId */ private static String id(String organizationId, String entityId) { return organizationId + ":" + entityId; //$NON-NLS-1$ } /** * A composite ID created from an organization ID, entity ID, and version. * @param organizationId * @param entityId * @param version */ private static String id(String organizationId, String entityId, String version) { return organizationId + ':' + entityId + ':' + version; } private static interface IUnmarshaller<T> { /** * Unmarshal the source map into an entity. * @param source the source map * @return the unmarshalled instance of <T> */ public T unmarshal(Map<String, Object> source); } }
better error reporting for failed ES indexing
manager/api/es/src/main/java/io/apiman/manager/api/es/EsStorage.java
better error reporting for failed ES indexing
<ide><path>anager/api/es/src/main/java/io/apiman/manager/api/es/EsStorage.java <ide> request.source(source); <ide> JestResult response = esClient.execute(new CreateIndex.Builder(indexName).settings(source).build()); <ide> if (!response.isSucceeded()) { <del> throw new StorageException("Failed to create index: " + indexName); //$NON-NLS-1$ <add> throw new StorageException("Failed to create index " + indexName + ": " + response.getErrorMessage()); //$NON-NLS-1$ //$NON-NLS-2$ <ide> } <ide> } <ide> <ide> JestResult response = esClient.execute(new Index.Builder(json).refresh(refresh).index(INDEX_NAME) <ide> .setParameter(Parameters.OP_TYPE, "create").type(type).id(id).build()); <ide> if (!response.isSucceeded()) { <del> throw new StorageException("Failed to index document " + id + " of type " + type + "."); <add> throw new StorageException("Failed to index document " + id + " of type " + type + ": " + response.getErrorMessage()); <ide> } <ide> } catch (StorageException e) { <ide> throw e; <ide> try { <ide> JestResult response = esClient.execute(new Delete.Builder(id).index(INDEX_NAME).type(type).build()); <ide> if (!response.isSucceeded()) { <del> throw new StorageException("Document could not be deleted because it did not exist."); //$NON-NLS-1$ <add> throw new StorageException("Document could not be deleted because it did not exist:" + response.getErrorMessage()); //$NON-NLS-1$ <ide> } <ide> } catch (StorageException e) { <ide> throw e;
Java
apache-2.0
b8d44e5c164e50df2b928dddf14d035f0b635ba7
0
apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,kalaspuffar/pdfbox
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.pdfparser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.util.DateConverter; import org.junit.Test; public class TestPDFParser { private static final File TARGETPDFDIR = new File("target/pdfs"); @Test public void testPDFParserMissingCatalog() throws URISyntaxException { // PDFBOX-3060 try { Loader.loadPDF(new File(TestPDFParser.class.getResource("MissingCatalog.pdf").toURI())) .close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * Test whether /Info dictionary is retrieved correctly when rebuilding the trailer of a corrupt * file. An incorrect algorithm would result in an outline dictionary being mistaken for an * /Info. * * @throws IOException */ @Test public void testPDFBox3208() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3208-L33MUTT2SVCWGCS6UIYL5TH3PNPXHIS6.pdf"))) { PDDocumentInformation di = doc.getDocumentInformation(); assertEquals("Liquent Enterprise Services", di.getAuthor()); assertEquals("Liquent services server", di.getCreator()); assertEquals("Amyuni PDF Converter version 4.0.0.9", di.getProducer()); assertEquals("", di.getKeywords()); assertEquals("", di.getSubject()); assertEquals("892B77DE781B4E71A1BEFB81A51A5ABC_20140326022424.docx", di.getTitle()); assertEquals(DateConverter.toCalendar("D:20140326142505-02'00'"), di.getCreationDate()); assertEquals(DateConverter.toCalendar("20140326172513Z"), di.getModificationDate()); } } /** * Test whether the /Info is retrieved correctly when rebuilding the trailer of a corrupt file, * despite the /Info dictionary not having a modification date. * * @throws IOException */ @Test public void testPDFBox3940() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3940-079977.pdf"))) { PDDocumentInformation di = doc.getDocumentInformation(); assertEquals("Unknown", di.getAuthor()); assertEquals("C:REGULA~1IREGSFR_EQ_EM.WP", di.getCreator()); assertEquals("Acrobat PDFWriter 3.02 for Windows", di.getProducer()); assertEquals("", di.getKeywords()); assertEquals("", di.getSubject()); assertEquals("C:REGULA~1IREGSFR_EQ_EM.PDF", di.getTitle()); assertEquals(DateConverter.toCalendar("Tuesday, July 28, 1998 4:00:09 PM"), di.getCreationDate()); } } /** * PDFBOX-3783: test parsing of file with trash after %%EOF. */ @Test public void testPDFBox3783() { try { Loader.loadPDF( new File(TARGETPDFDIR, "PDFBOX-3783-72GLBIGUC6LB46ELZFBARRJTLN4RBSQM.pdf")) .close(); } catch (Exception exception) { fail("Unexpected IOException"); } } /** * PDFBOX-3785, PDFBOX-3957: * Test whether truncated file with several revisions has correct page count. * * @throws IOException */ @Test public void testPDFBox3785() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3785-202097.pdf"))) { assertEquals(11, doc.getNumberOfPages()); } } /** * PDFBOX-3947: test parsing of file with broken object stream. */ @Test public void testPDFBox3947() { try { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3947-670064.pdf")).close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * PDFBOX-3948: test parsing of file with object stream containing some unexpected newlines. */ @Test public void testPDFBox3948() { try { Loader.loadPDF( new File(TARGETPDFDIR, "PDFBOX-3948-EUWO6SQS5TM4VGOMRD3FLXZHU35V2CP2.pdf")) .close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * PDFBOX-3949: test parsing of file with incomplete object stream. */ @Test public void testPDFBox3949() { try { Loader.loadPDF( new File(TARGETPDFDIR, "PDFBOX-3949-MKFYUGZWS3OPXLLVU2Z4LWCTVA5WNOGF.pdf")) .close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * PDFBOX-3950: test parsing and rendering of truncated file with missing pages. * * @throws IOException */ @Test public void testPDFBox3950() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3950-23EGDHXSBBYQLKYOKGZUOVYVNE675PRD.pdf"))) { assertEquals(4, doc.getNumberOfPages()); PDFRenderer renderer = new PDFRenderer(doc); for (int i = 0; i < doc.getNumberOfPages(); ++i) { try { renderer.renderImage(i); } catch (IOException ex) { if (i == 3 && ex.getMessage().equals("Missing descendant font array")) { continue; } throw ex; } } } } /** * PDFBOX-3951: test parsing of truncated file. * * @throws IOException */ @Test public void testPDFBox3951() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3951-FIHUZWDDL2VGPOE34N6YHWSIGSH5LVGZ.pdf"))) { assertEquals(143, doc.getNumberOfPages()); } } /** * PDFBOX-3964: test parsing of broken file. * * @throws IOException */ @Test public void testPDFBox3964() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3964-c687766d68ac766be3f02aaec5e0d713_2.pdf"))) { assertEquals(10, doc.getNumberOfPages()); } } /** * Test whether /Info dictionary is retrieved correctly in brute force search for the * Info/Catalog dictionaries. * * @throws IOException */ @Test public void testPDFBox3977() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3977-63NGFQRI44HQNPIPEJH5W2TBM6DJZWMI.pdf"))) { PDDocumentInformation di = doc.getDocumentInformation(); assertEquals("QuarkXPress(tm) 6.52", di.getCreator()); assertEquals("Acrobat Distiller 7.0 pour Macintosh", di.getProducer()); assertEquals("Fich sal Fabr corr1 (Page 6)", di.getTitle()); assertEquals(DateConverter.toCalendar("D:20070608151915+02'00'"), di.getCreationDate()); assertEquals(DateConverter.toCalendar("D:20080604152122+02'00'"), di.getModificationDate()); } } /** * Test parsing the "genko_oc_shiryo1.pdf" file, which is susceptible to regression. */ @Test public void testParseGenko() { try { Loader.loadPDF(new File(TARGETPDFDIR, "genko_oc_shiryo1.pdf")).close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * Test parsing the file from PDFBOX-4338, which brought an * ArrayIndexOutOfBoundsException before the bug was fixed. */ @Test public void testPDFBox4338() { try { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4338.pdf")).close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * Test parsing the file from PDFBOX-4339, which brought a * NullPointerException before the bug was fixed. */ @Test public void testPDFBox4339() { try { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4339.pdf")).close(); } catch (Exception exception) { fail("Unexpected Exception"); } } /** * Test parsing the "WXMDXCYRWFDCMOSFQJ5OAJIAFXYRZ5OA.pdf" file, which is susceptible to * regression. * * @throws IOException */ @Test public void testPDFBox4153() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4153-WXMDXCYRWFDCMOSFQJ5OAJIAFXYRZ5OA.pdf"))) { PDDocumentOutline documentOutline = doc.getDocumentCatalog().getDocumentOutline(); PDOutlineItem firstChild = documentOutline.getFirstChild(); assertEquals("Main Menu", firstChild.getTitle()); } } /** * Test that PDFBOX-4490 has 3 pages. * * @throws IOException */ @Test public void testPDFBox4490() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4490.pdf"))) { assertEquals(3, doc.getNumberOfPages()); } } }
pdfbox/src/test/java/org/apache/pdfbox/pdfparser/TestPDFParser.java
/***************************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ****************************************************************************/ package org.apache.pdfbox.pdfparser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.net.URISyntaxException; import org.apache.pdfbox.Loader; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.io.RandomAccessReadBufferedFile; import org.apache.pdfbox.io.RandomAccessRead; import org.apache.pdfbox.io.ScratchFile; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.util.DateConverter; import org.junit.Before; import org.junit.Test; public class TestPDFParser { private static final String PATH_OF_PDF = "src/test/resources/input/yaddatest.pdf"; private static final File tmpDirectory = new File(System.getProperty("java.io.tmpdir")); private static final File TARGETPDFDIR = new File("target/pdfs"); private int numberOfTmpFiles = 0; /** * Initialize the number of tmp file before the test * * @throws Exception */ @Before public void setUp() throws Exception { numberOfTmpFiles = getNumberOfTempFile(); } /** * Count the number of temporary files * * @return */ private int getNumberOfTempFile() { int result = 0; File[] tmpPdfs = tmpDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(COSParser.TMP_FILE_PREFIX) && name.endsWith("pdf"); } }); if (tmpPdfs != null) { result = tmpPdfs.length; } return result; } @Test public void testPDFParserFile() throws IOException { executeParserTest(new RandomAccessReadBufferedFile(new File(PATH_OF_PDF)), MemoryUsageSetting.setupMainMemoryOnly()); } @Test public void testPDFParserFileScratchFile() throws IOException { executeParserTest(new RandomAccessReadBufferedFile(new File(PATH_OF_PDF)), MemoryUsageSetting.setupTempFileOnly()); } @Test public void testPDFParserMissingCatalog() throws IOException, URISyntaxException { // PDFBOX-3060 Loader.loadPDF(new File(TestPDFParser.class.getResource("MissingCatalog.pdf").toURI())) .close(); } /** * Test whether /Info dictionary is retrieved correctly when rebuilding the trailer of a corrupt * file. An incorrect algorithm would result in an outline dictionary being mistaken for an * /Info. * * @throws IOException */ @Test public void testPDFBox3208() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3208-L33MUTT2SVCWGCS6UIYL5TH3PNPXHIS6.pdf"))) { PDDocumentInformation di = doc.getDocumentInformation(); assertEquals("Liquent Enterprise Services", di.getAuthor()); assertEquals("Liquent services server", di.getCreator()); assertEquals("Amyuni PDF Converter version 4.0.0.9", di.getProducer()); assertEquals("", di.getKeywords()); assertEquals("", di.getSubject()); assertEquals("892B77DE781B4E71A1BEFB81A51A5ABC_20140326022424.docx", di.getTitle()); assertEquals(DateConverter.toCalendar("D:20140326142505-02'00'"), di.getCreationDate()); assertEquals(DateConverter.toCalendar("20140326172513Z"), di.getModificationDate()); } } /** * Test whether the /Info is retrieved correctly when rebuilding the trailer of a corrupt file, * despite the /Info dictionary not having a modification date. * * @throws IOException */ @Test public void testPDFBox3940() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3940-079977.pdf"))) { PDDocumentInformation di = doc.getDocumentInformation(); assertEquals("Unknown", di.getAuthor()); assertEquals("C:REGULA~1IREGSFR_EQ_EM.WP", di.getCreator()); assertEquals("Acrobat PDFWriter 3.02 for Windows", di.getProducer()); assertEquals("", di.getKeywords()); assertEquals("", di.getSubject()); assertEquals("C:REGULA~1IREGSFR_EQ_EM.PDF", di.getTitle()); assertEquals(DateConverter.toCalendar("Tuesday, July 28, 1998 4:00:09 PM"), di.getCreationDate()); } } /** * PDFBOX-3783: test parsing of file with trash after %%EOF. * * @throws IOException */ @Test public void testPDFBox3783() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3783-72GLBIGUC6LB46ELZFBARRJTLN4RBSQM.pdf")) .close(); } /** * PDFBOX-3785, PDFBOX-3957: * Test whether truncated file with several revisions has correct page count. * * @throws IOException */ @Test public void testPDFBox3785() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3785-202097.pdf"))) { assertEquals(11, doc.getNumberOfPages()); } } /** * PDFBOX-3947: test parsing of file with broken object stream. * * @throws IOException */ @Test public void testPDFBox3947() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3947-670064.pdf")).close(); } /** * PDFBOX-3948: test parsing of file with object stream containing some unexpected newlines. * * @throws IOException */ @Test public void testPDFBox3948() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3948-EUWO6SQS5TM4VGOMRD3FLXZHU35V2CP2.pdf")) .close(); } /** * PDFBOX-3949: test parsing of file with incomplete object stream. * * @throws IOException */ @Test public void testPDFBox3949() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3949-MKFYUGZWS3OPXLLVU2Z4LWCTVA5WNOGF.pdf")) .close(); } /** * PDFBOX-3950: test parsing and rendering of truncated file with missing pages. * * @throws IOException */ @Test public void testPDFBox3950() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3950-23EGDHXSBBYQLKYOKGZUOVYVNE675PRD.pdf"))) { assertEquals(4, doc.getNumberOfPages()); PDFRenderer renderer = new PDFRenderer(doc); for (int i = 0; i < doc.getNumberOfPages(); ++i) { try { renderer.renderImage(i); } catch (IOException ex) { if (i == 3 && ex.getMessage().equals("Missing descendant font array")) { continue; } throw ex; } } } } /** * PDFBOX-3951: test parsing of truncated file. * * @throws IOException */ @Test public void testPDFBox3951() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3951-FIHUZWDDL2VGPOE34N6YHWSIGSH5LVGZ.pdf"))) { assertEquals(143, doc.getNumberOfPages()); } } /** * PDFBOX-3964: test parsing of broken file. * * @throws IOException */ @Test public void testPDFBox3964() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3964-c687766d68ac766be3f02aaec5e0d713_2.pdf"))) { assertEquals(10, doc.getNumberOfPages()); } } /** * Test whether /Info dictionary is retrieved correctly in brute force search for the * Info/Catalog dictionaries. * * @throws IOException */ @Test public void testPDFBox3977() throws IOException { try (PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3977-63NGFQRI44HQNPIPEJH5W2TBM6DJZWMI.pdf"))) { PDDocumentInformation di = doc.getDocumentInformation(); assertEquals("QuarkXPress(tm) 6.52", di.getCreator()); assertEquals("Acrobat Distiller 7.0 pour Macintosh", di.getProducer()); assertEquals("Fich sal Fabr corr1 (Page 6)", di.getTitle()); assertEquals(DateConverter.toCalendar("D:20070608151915+02'00'"), di.getCreationDate()); assertEquals(DateConverter.toCalendar("D:20080604152122+02'00'"), di.getModificationDate()); } } /** * Test parsing the "genko_oc_shiryo1.pdf" file, which is susceptible to regression. * * @throws IOException */ @Test public void testParseGenko() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "genko_oc_shiryo1.pdf")).close(); } /** * Test parsing the file from PDFBOX-4338, which brought an * ArrayIndexOutOfBoundsException before the bug was fixed. * * @throws IOException */ @Test public void testPDFBox4338() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4338.pdf")).close(); } /** * Test parsing the file from PDFBOX-4339, which brought a * NullPointerException before the bug was fixed. * * @throws IOException */ @Test public void testPDFBox4339() throws IOException { Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4339.pdf")).close(); } /** * Test parsing the "WXMDXCYRWFDCMOSFQJ5OAJIAFXYRZ5OA.pdf" file, which is susceptible to * regression. * * @throws IOException */ @Test public void testPDFBox4153() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4153-WXMDXCYRWFDCMOSFQJ5OAJIAFXYRZ5OA.pdf"))) { PDDocumentOutline documentOutline = doc.getDocumentCatalog().getDocumentOutline(); PDOutlineItem firstChild = documentOutline.getFirstChild(); assertEquals("Main Menu", firstChild.getTitle()); } } /** * Test that PDFBOX-4490 has 3 pages. * * @throws IOException */ @Test public void testPDFBox4490() throws IOException { try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4490.pdf"))) { assertEquals(3, doc.getNumberOfPages()); } } private void executeParserTest(RandomAccessRead source, MemoryUsageSetting memUsageSetting) throws IOException { ScratchFile scratchFile = new ScratchFile(memUsageSetting); PDFParser pdfParser = new PDFParser(source, scratchFile); try (PDDocument doc = pdfParser.parse()) { assertNotNull(doc); } source.close(); // number tmp file must be the same assertEquals(numberOfTmpFiles, getNumberOfTempFile()); } }
PDFBOX-4836: remove some tests as ScratchFile isn't no longer used when reading a file, added some fail statements to complete existing test cases git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1881872 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/test/java/org/apache/pdfbox/pdfparser/TestPDFParser.java
PDFBOX-4836: remove some tests as ScratchFile isn't no longer used when reading a file, added some fail statements to complete existing test cases
<ide><path>dfbox/src/test/java/org/apache/pdfbox/pdfparser/TestPDFParser.java <del>/***************************************************************************** <del> * <del> * Licensed to the Apache Software Foundation (ASF) under one <del> * or more contributor license agreements. See the NOTICE file <del> * distributed with this work for additional information <del> * regarding copyright ownership. The ASF licenses this file <del> * to you under the Apache License, Version 2.0 (the <del> * "License"); you may not use this file except in compliance <del> * with the License. You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, <del> * software distributed under the License is distributed on an <del> * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <del> * KIND, either express or implied. See the License for the <del> * specific language governing permissions and limitations <del> * under the License. <del> * <del> ****************************************************************************/ <add>/* <add> * Licensed to the Apache Software Foundation (ASF) under one or more <add> * contributor license agreements. See the NOTICE file distributed with <add> * this work for additional information regarding copyright ownership. <add> * The ASF licenses this file to You under the Apache License, Version 2.0 <add> * (the "License"); you may not use this file except in compliance with <add> * the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> <ide> package org.apache.pdfbox.pdfparser; <ide> <ide> import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.fail; <ide> <ide> import java.io.File; <del>import java.io.FileInputStream; <del>import java.io.FilenameFilter; <ide> import java.io.IOException; <ide> import java.net.URISyntaxException; <ide> <ide> import org.apache.pdfbox.Loader; <del>import org.apache.pdfbox.io.MemoryUsageSetting; <del>import org.apache.pdfbox.io.RandomAccessReadBufferedFile; <del>import org.apache.pdfbox.io.RandomAccessRead; <del>import org.apache.pdfbox.io.ScratchFile; <ide> import org.apache.pdfbox.pdmodel.PDDocument; <ide> import org.apache.pdfbox.pdmodel.PDDocumentInformation; <ide> import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; <ide> import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; <ide> import org.apache.pdfbox.rendering.PDFRenderer; <ide> import org.apache.pdfbox.util.DateConverter; <del>import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> public class TestPDFParser <ide> { <del> private static final String PATH_OF_PDF = "src/test/resources/input/yaddatest.pdf"; <del> private static final File tmpDirectory = new File(System.getProperty("java.io.tmpdir")); <ide> private static final File TARGETPDFDIR = new File("target/pdfs"); <ide> <del> private int numberOfTmpFiles = 0; <del> <del> /** <del> * Initialize the number of tmp file before the test <del> * <del> * @throws Exception <del> */ <del> @Before <del> public void setUp() throws Exception <del> { <del> numberOfTmpFiles = getNumberOfTempFile(); <del> } <del> <del> /** <del> * Count the number of temporary files <del> * <del> * @return <del> */ <del> private int getNumberOfTempFile() <del> { <del> int result = 0; <del> File[] tmpPdfs = tmpDirectory.listFiles(new FilenameFilter() <del> { <del> @Override <del> public boolean accept(File dir, String name) <del> { <del> return name.startsWith(COSParser.TMP_FILE_PREFIX) <del> && name.endsWith("pdf"); <del> } <del> }); <del> <del> if (tmpPdfs != null) <del> { <del> result = tmpPdfs.length; <del> } <del> <del> return result; <del> } <del> <del> @Test <del> public void testPDFParserFile() throws IOException <del> { <del> executeParserTest(new RandomAccessReadBufferedFile(new File(PATH_OF_PDF)), MemoryUsageSetting.setupMainMemoryOnly()); <del> } <del> <del> @Test <del> public void testPDFParserFileScratchFile() throws IOException <del> { <del> executeParserTest(new RandomAccessReadBufferedFile(new File(PATH_OF_PDF)), MemoryUsageSetting.setupTempFileOnly()); <del> } <del> <del> @Test <del> public void testPDFParserMissingCatalog() throws IOException, URISyntaxException <add> @Test <add> public void testPDFParserMissingCatalog() throws URISyntaxException <ide> { <ide> // PDFBOX-3060 <del> Loader.loadPDF(new File(TestPDFParser.class.getResource("MissingCatalog.pdf").toURI())) <add> try <add> { <add> Loader.loadPDF(new File(TestPDFParser.class.getResource("MissingCatalog.pdf").toURI())) <ide> .close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> <ide> /** <ide> * PDFBOX-3783: test parsing of file with trash after %%EOF. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testPDFBox3783() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3783-72GLBIGUC6LB46ELZFBARRJTLN4RBSQM.pdf")) <del> .close(); <add> */ <add> @Test <add> public void testPDFBox3783() <add> { <add> try <add> { <add> Loader.loadPDF( <add> new File(TARGETPDFDIR, "PDFBOX-3783-72GLBIGUC6LB46ELZFBARRJTLN4RBSQM.pdf")) <add> .close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected IOException"); <add> } <add> <ide> } <ide> <ide> /** <ide> <ide> /** <ide> * PDFBOX-3947: test parsing of file with broken object stream. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testPDFBox3947() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3947-670064.pdf")).close(); <add> */ <add> @Test <add> public void testPDFBox3947() <add> { <add> try <add> { <add> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3947-670064.pdf")).close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> * PDFBOX-3948: test parsing of file with object stream containing some unexpected newlines. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testPDFBox3948() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3948-EUWO6SQS5TM4VGOMRD3FLXZHU35V2CP2.pdf")) <del> .close(); <add> */ <add> @Test <add> public void testPDFBox3948() <add> { <add> try <add> { <add> Loader.loadPDF( <add> new File(TARGETPDFDIR, "PDFBOX-3948-EUWO6SQS5TM4VGOMRD3FLXZHU35V2CP2.pdf")) <add> .close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> * PDFBOX-3949: test parsing of file with incomplete object stream. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testPDFBox3949() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3949-MKFYUGZWS3OPXLLVU2Z4LWCTVA5WNOGF.pdf")) <del> .close(); <add> */ <add> @Test <add> public void testPDFBox3949() <add> { <add> try <add> { <add> Loader.loadPDF( <add> new File(TARGETPDFDIR, "PDFBOX-3949-MKFYUGZWS3OPXLLVU2Z4LWCTVA5WNOGF.pdf")) <add> .close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> <ide> /** <ide> * Test parsing the "genko_oc_shiryo1.pdf" file, which is susceptible to regression. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testParseGenko() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "genko_oc_shiryo1.pdf")).close(); <add> */ <add> @Test <add> public void testParseGenko() <add> { <add> try <add> { <add> Loader.loadPDF(new File(TARGETPDFDIR, "genko_oc_shiryo1.pdf")).close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> * Test parsing the file from PDFBOX-4338, which brought an <ide> * ArrayIndexOutOfBoundsException before the bug was fixed. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testPDFBox4338() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4338.pdf")).close(); <add> */ <add> @Test <add> public void testPDFBox4338() <add> { <add> try <add> { <add> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4338.pdf")).close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> * Test parsing the file from PDFBOX-4339, which brought a <ide> * NullPointerException before the bug was fixed. <del> * <del> * @throws IOException <del> */ <del> @Test <del> public void testPDFBox4339() throws IOException <del> { <del> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4339.pdf")).close(); <add> */ <add> @Test <add> public void testPDFBox4339() <add> { <add> try <add> { <add> Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4339.pdf")).close(); <add> } <add> catch (Exception exception) <add> { <add> fail("Unexpected Exception"); <add> } <ide> } <ide> <ide> /** <ide> } <ide> } <ide> <del> private void executeParserTest(RandomAccessRead source, MemoryUsageSetting memUsageSetting) throws IOException <del> { <del> ScratchFile scratchFile = new ScratchFile(memUsageSetting); <del> PDFParser pdfParser = new PDFParser(source, scratchFile); <del> try (PDDocument doc = pdfParser.parse()) <del> { <del> assertNotNull(doc); <del> } <del> source.close(); <del> // number tmp file must be the same <del> assertEquals(numberOfTmpFiles, getNumberOfTempFile()); <del> } <del> <ide> }
Java
apache-2.0
90ed5549e8e4cc686393a972fea921b9bbe7dbb9
0
mcollovati/camel,gautric/camel,christophd/camel,johnpoth/camel,sabre1041/camel,punkhorn/camel-upstream,objectiser/camel,sabre1041/camel,pkletsko/camel,neoramon/camel,lburgazzoli/camel,gilfernandes/camel,apache/camel,akhettar/camel,anton-k11/camel,jlpedrosa/camel,isavin/camel,isavin/camel,drsquidop/camel,ssharma/camel,anton-k11/camel,mgyongyosi/camel,oalles/camel,driseley/camel,nikvaessen/camel,jlpedrosa/camel,lburgazzoli/apache-camel,oalles/camel,snurmine/camel,lburgazzoli/apache-camel,jonmcewen/camel,bgaudaen/camel,jamesnetherton/camel,zregvart/camel,punkhorn/camel-upstream,JYBESSON/camel,bhaveshdt/camel,driseley/camel,nicolaferraro/camel,nikhilvibhav/camel,ullgren/camel,jlpedrosa/camel,YoshikiHigo/camel,arnaud-deprez/camel,nboukhed/camel,veithen/camel,jmandawg/camel,oalles/camel,nikvaessen/camel,akhettar/camel,borcsokj/camel,alvinkwekel/camel,sverkera/camel,lburgazzoli/camel,tdiesler/camel,adessaigne/camel,pkletsko/camel,johnpoth/camel,gilfernandes/camel,jkorab/camel,chirino/camel,tkopczynski/camel,dmvolod/camel,jmandawg/camel,nikhilvibhav/camel,jamesnetherton/camel,lburgazzoli/camel,isavin/camel,NickCis/camel,w4tson/camel,jkorab/camel,Thopap/camel,nicolaferraro/camel,lburgazzoli/apache-camel,anoordover/camel,edigrid/camel,curso007/camel,neoramon/camel,neoramon/camel,sabre1041/camel,nikvaessen/camel,rmarting/camel,gnodet/camel,jonmcewen/camel,cunningt/camel,lburgazzoli/apache-camel,gnodet/camel,scranton/camel,sverkera/camel,gautric/camel,kevinearls/camel,prashant2402/camel,chirino/camel,YoshikiHigo/camel,JYBESSON/camel,sirlatrom/camel,tkopczynski/camel,tadayosi/camel,FingolfinTEK/camel,curso007/camel,jonmcewen/camel,akhettar/camel,CodeSmell/camel,yuruki/camel,Thopap/camel,NickCis/camel,christophd/camel,RohanHart/camel,hqstevenson/camel,jlpedrosa/camel,borcsokj/camel,ullgren/camel,onders86/camel,salikjan/camel,kevinearls/camel,pmoerenhout/camel,gnodet/camel,lburgazzoli/camel,tadayosi/camel,gautric/camel,sverkera/camel,jamesnetherton/camel,drsquidop/camel,Fabryprog/camel,yuruki/camel,apache/camel,anoordover/camel,nboukhed/camel,w4tson/camel,jarst/camel,bgaudaen/camel,prashant2402/camel,johnpoth/camel,ssharma/camel,acartapanis/camel,adessaigne/camel,oalles/camel,oalles/camel,pax95/camel,akhettar/camel,pkletsko/camel,scranton/camel,adessaigne/camel,jmandawg/camel,yuruki/camel,christophd/camel,curso007/camel,tkopczynski/camel,edigrid/camel,neoramon/camel,nikvaessen/camel,curso007/camel,pmoerenhout/camel,mgyongyosi/camel,tlehoux/camel,cunningt/camel,sabre1041/camel,dmvolod/camel,rmarting/camel,ullgren/camel,allancth/camel,kevinearls/camel,gilfernandes/camel,nikvaessen/camel,arnaud-deprez/camel,tkopczynski/camel,FingolfinTEK/camel,erwelch/camel,nboukhed/camel,sverkera/camel,JYBESSON/camel,tdiesler/camel,hqstevenson/camel,gnodet/camel,jlpedrosa/camel,DariusX/camel,w4tson/camel,bhaveshdt/camel,johnpoth/camel,adessaigne/camel,jamesnetherton/camel,RohanHart/camel,tlehoux/camel,edigrid/camel,arnaud-deprez/camel,scranton/camel,w4tson/camel,YoshikiHigo/camel,davidkarlsen/camel,bhaveshdt/camel,tlehoux/camel,mcollovati/camel,christophd/camel,FingolfinTEK/camel,cunningt/camel,gautric/camel,objectiser/camel,Thopap/camel,NickCis/camel,driseley/camel,edigrid/camel,christophd/camel,erwelch/camel,YoshikiHigo/camel,alvinkwekel/camel,RohanHart/camel,adessaigne/camel,nikvaessen/camel,veithen/camel,sirlatrom/camel,DariusX/camel,Fabryprog/camel,anton-k11/camel,kevinearls/camel,lburgazzoli/apache-camel,tlehoux/camel,hqstevenson/camel,jkorab/camel,tdiesler/camel,jarst/camel,CodeSmell/camel,acartapanis/camel,sirlatrom/camel,sirlatrom/camel,objectiser/camel,FingolfinTEK/camel,nicolaferraro/camel,gautric/camel,snurmine/camel,salikjan/camel,akhettar/camel,lburgazzoli/camel,jmandawg/camel,tkopczynski/camel,curso007/camel,arnaud-deprez/camel,cunningt/camel,tkopczynski/camel,anton-k11/camel,zregvart/camel,mgyongyosi/camel,bgaudaen/camel,pax95/camel,sabre1041/camel,JYBESSON/camel,gautric/camel,sverkera/camel,snurmine/camel,tdiesler/camel,edigrid/camel,scranton/camel,anton-k11/camel,yuruki/camel,kevinearls/camel,driseley/camel,yuruki/camel,jarst/camel,prashant2402/camel,rmarting/camel,RohanHart/camel,cunningt/camel,chirino/camel,w4tson/camel,rmarting/camel,apache/camel,scranton/camel,onders86/camel,YoshikiHigo/camel,rmarting/camel,driseley/camel,pkletsko/camel,anoordover/camel,prashant2402/camel,pkletsko/camel,erwelch/camel,FingolfinTEK/camel,RohanHart/camel,pmoerenhout/camel,borcsokj/camel,ssharma/camel,onders86/camel,CodeSmell/camel,zregvart/camel,erwelch/camel,ullgren/camel,hqstevenson/camel,dmvolod/camel,edigrid/camel,RohanHart/camel,mgyongyosi/camel,jkorab/camel,jarst/camel,sirlatrom/camel,JYBESSON/camel,tdiesler/camel,anoordover/camel,onders86/camel,drsquidop/camel,lburgazzoli/camel,davidkarlsen/camel,pax95/camel,anoordover/camel,sirlatrom/camel,pmoerenhout/camel,jamesnetherton/camel,jkorab/camel,sverkera/camel,w4tson/camel,jonmcewen/camel,tadayosi/camel,erwelch/camel,punkhorn/camel-upstream,anoordover/camel,neoramon/camel,borcsokj/camel,allancth/camel,johnpoth/camel,isavin/camel,pmoerenhout/camel,chirino/camel,drsquidop/camel,allancth/camel,bhaveshdt/camel,ssharma/camel,christophd/camel,lburgazzoli/apache-camel,drsquidop/camel,mcollovati/camel,jmandawg/camel,bgaudaen/camel,YoshikiHigo/camel,ssharma/camel,davidkarlsen/camel,davidkarlsen/camel,DariusX/camel,veithen/camel,onders86/camel,yuruki/camel,arnaud-deprez/camel,gilfernandes/camel,apache/camel,borcsokj/camel,Fabryprog/camel,pmoerenhout/camel,Thopap/camel,JYBESSON/camel,dmvolod/camel,tlehoux/camel,pax95/camel,FingolfinTEK/camel,alvinkwekel/camel,acartapanis/camel,veithen/camel,acartapanis/camel,kevinearls/camel,mgyongyosi/camel,hqstevenson/camel,NickCis/camel,borcsokj/camel,snurmine/camel,snurmine/camel,jmandawg/camel,pax95/camel,jarst/camel,apache/camel,prashant2402/camel,dmvolod/camel,pax95/camel,acartapanis/camel,erwelch/camel,cunningt/camel,objectiser/camel,dmvolod/camel,onders86/camel,jonmcewen/camel,jarst/camel,arnaud-deprez/camel,ssharma/camel,nboukhed/camel,scranton/camel,veithen/camel,nboukhed/camel,tlehoux/camel,mgyongyosi/camel,acartapanis/camel,anton-k11/camel,NickCis/camel,gilfernandes/camel,NickCis/camel,allancth/camel,tadayosi/camel,DariusX/camel,bgaudaen/camel,bhaveshdt/camel,mcollovati/camel,Thopap/camel,pkletsko/camel,johnpoth/camel,jkorab/camel,snurmine/camel,gnodet/camel,apache/camel,drsquidop/camel,chirino/camel,tadayosi/camel,alvinkwekel/camel,oalles/camel,punkhorn/camel-upstream,jonmcewen/camel,tdiesler/camel,isavin/camel,hqstevenson/camel,gilfernandes/camel,nikhilvibhav/camel,neoramon/camel,sabre1041/camel,allancth/camel,Thopap/camel,tadayosi/camel,driseley/camel,nboukhed/camel,jlpedrosa/camel,veithen/camel,rmarting/camel,adessaigne/camel,CodeSmell/camel,Fabryprog/camel,chirino/camel,isavin/camel,curso007/camel,bgaudaen/camel,nikhilvibhav/camel,jamesnetherton/camel,nicolaferraro/camel,akhettar/camel,zregvart/camel,allancth/camel,bhaveshdt/camel,prashant2402/camel
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.remote; import org.apache.camel.builder.NotifyBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.processor.idempotent.MemoryIdempotentRepository; import org.junit.Test; /** * Memory repo test */ public class FtpConsumerIdempotentMemoryRefTest extends FtpServerTestSupport { private MemoryIdempotentRepository repo; private String getFtpUrl() { return "ftp://admin@localhost:" + getPort() + "/idempotent?password=admin&binary=false&idempotent=true&idempotentRepository=#myRepo&idempotentKey=${file:onlyname}&delete=true"; } @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); repo = new MemoryIdempotentRepository(); repo.setCacheSize(5); jndi.bind("myRepo", repo); return jndi; } @Test public void testIdempotent() throws Exception { NotifyBuilder notify = new NotifyBuilder(context).whenDone(5).create(); getMockEndpoint("mock:result").expectedMessageCount(5); sendFile(getFtpUrl(), "Hello A", "a.txt"); sendFile(getFtpUrl(), "Hello B", "b.txt"); sendFile(getFtpUrl(), "Hello C", "c.txt"); sendFile(getFtpUrl(), "Hello D", "d.txt"); sendFile(getFtpUrl(), "Hello E", "e.txt"); assertMockEndpointsSatisfied(); assertTrue(notify.matchesMockWaitTime()); assertEquals(5, repo.getCache().size()); assertTrue(repo.contains("a.txt")); assertTrue(repo.contains("b.txt")); assertTrue(repo.contains("c.txt")); assertTrue(repo.contains("d.txt")); assertTrue(repo.contains("e.txt")); resetMocks(); notify = new NotifyBuilder(context).whenDone(4).create(); getMockEndpoint("mock:result").expectedMessageCount(2); // duplicate sendFile(getFtpUrl(), "Hello A", "a.txt"); sendFile(getFtpUrl(), "Hello B", "b.txt"); // new files sendFile(getFtpUrl(), "Hello F", "f.txt"); sendFile(getFtpUrl(), "Hello G", "g.txt"); assertMockEndpointsSatisfied(); assertTrue(notify.matchesMockWaitTime()); assertEquals(5, repo.getCache().size()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from(getFtpUrl()).to("mock:result"); } }; } }
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerIdempotentMemoryRefTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.remote; import java.util.concurrent.TimeUnit; import org.apache.camel.builder.NotifyBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.processor.idempotent.MemoryIdempotentRepository; import org.junit.Test; /** * Memory repo test */ public class FtpConsumerIdempotentMemoryRefTest extends FtpServerTestSupport { private MemoryIdempotentRepository repo; private String getFtpUrl() { return "ftp://admin@localhost:" + getPort() + "/idempotent?password=admin&binary=false&idempotent=true&idempotentRepository=#myRepo&idempotentKey=${file:onlyname}&delete=true"; } @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); repo = new MemoryIdempotentRepository(); repo.setCacheSize(5); jndi.bind("myRepo", repo); return jndi; } @Test public void testIdempotent() throws Exception { NotifyBuilder notify = new NotifyBuilder(context).whenDone(5).create(); getMockEndpoint("mock:result").expectedMessageCount(5); sendFile(getFtpUrl(), "Hello A", "a.txt"); sendFile(getFtpUrl(), "Hello B", "b.txt"); sendFile(getFtpUrl(), "Hello C", "c.txt"); sendFile(getFtpUrl(), "Hello D", "d.txt"); sendFile(getFtpUrl(), "Hello E", "e.txt"); assertMockEndpointsSatisfied(); assertTrue(notify.matches(5, TimeUnit.SECONDS)); assertEquals(5, repo.getCache().size()); assertTrue(repo.contains("a.txt")); assertTrue(repo.contains("b.txt")); assertTrue(repo.contains("c.txt")); assertTrue(repo.contains("d.txt")); assertTrue(repo.contains("e.txt")); resetMocks(); notify = new NotifyBuilder(context).whenDone(4).create(); getMockEndpoint("mock:result").expectedMessageCount(2); // duplicate sendFile(getFtpUrl(), "Hello A", "a.txt"); sendFile(getFtpUrl(), "Hello B", "b.txt"); // new files sendFile(getFtpUrl(), "Hello F", "f.txt"); sendFile(getFtpUrl(), "Hello G", "g.txt"); assertMockEndpointsSatisfied(); assertTrue(notify.matches(5, TimeUnit.SECONDS)); assertEquals(5, repo.getCache().size()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from(getFtpUrl()).to("mock:result"); } }; } }
Fixed test
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerIdempotentMemoryRefTest.java
Fixed test
<ide><path>omponents/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerIdempotentMemoryRefTest.java <ide> * limitations under the License. <ide> */ <ide> package org.apache.camel.component.file.remote; <del> <del>import java.util.concurrent.TimeUnit; <ide> <ide> import org.apache.camel.builder.NotifyBuilder; <ide> import org.apache.camel.builder.RouteBuilder; <ide> sendFile(getFtpUrl(), "Hello E", "e.txt"); <ide> <ide> assertMockEndpointsSatisfied(); <del> assertTrue(notify.matches(5, TimeUnit.SECONDS)); <add> assertTrue(notify.matchesMockWaitTime()); <ide> <ide> assertEquals(5, repo.getCache().size()); <ide> assertTrue(repo.contains("a.txt")); <ide> sendFile(getFtpUrl(), "Hello G", "g.txt"); <ide> <ide> assertMockEndpointsSatisfied(); <del> assertTrue(notify.matches(5, TimeUnit.SECONDS)); <add> assertTrue(notify.matchesMockWaitTime()); <ide> <ide> assertEquals(5, repo.getCache().size()); <ide> }
Java
apache-2.0
be0ebab31d0c89026381429935979ee0cbd34318
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.lang.module; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.smoothbuild.lang.base.Types.BLOB; import static org.smoothbuild.lang.base.Types.BLOB_ARRAY; import static org.smoothbuild.lang.base.Types.FILE; import static org.smoothbuild.lang.base.Types.FILE_ARRAY; import static org.smoothbuild.lang.base.Types.STRING; import static org.smoothbuild.lang.base.Types.STRING_ARRAY; import static org.smoothbuild.lang.function.base.Name.name; import static org.smoothbuild.lang.function.base.Parameter.optionalParameter; import static org.smoothbuild.util.Classes.binaryPath; import static org.testory.Testory.given; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import org.hamcrest.Matchers; import org.junit.Test; import org.smoothbuild.lang.base.Array; import org.smoothbuild.lang.base.Blob; import org.smoothbuild.lang.base.NativeApi; import org.smoothbuild.lang.base.SFile; import org.smoothbuild.lang.base.SString; import org.smoothbuild.lang.function.base.Function; import org.smoothbuild.lang.function.nativ.err.IllegalFunctionNameException; import org.smoothbuild.lang.function.nativ.err.IllegalParamTypeException; import org.smoothbuild.lang.function.nativ.err.IllegalReturnTypeException; import org.smoothbuild.lang.function.nativ.err.NonPublicSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.NonStaticSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.ParamMethodHasArgumentsException; import org.smoothbuild.lang.plugin.Required; import org.smoothbuild.lang.plugin.SmoothFunction; import org.smoothbuild.util.Classes; import com.google.common.io.ByteStreams; public class NativeModuleFactoryTest { private Module module; private Function<?> function; @Test public void module_available_names_contains_smooth_function_names() throws Exception { given(module = createNativeModule(ModuleWithOneFunction.class)); when(module.availableNames()); thenReturned(contains(name("func"))); } public static class ModuleWithOneFunction { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void module_with_more_than_one_function_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithTwoFunctions.class)); when(module.availableNames()); thenReturned(contains(name("func1"), name("func2"))); } public static class ModuleWithTwoFunctions { public interface Parameters {} @SmoothFunction public static SString func1(NativeApi nativeApi, Parameters params) { return null; } @SmoothFunction public static SString func2(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalArgumentException.class) public void two_functions_with_same_name_are_forbidden() throws Exception { createNativeModule(ModuleWithTwoFunctionsWithSameName.class); } public static class ModuleWithTwoFunctionsWithSameName { public interface Parameters {} public interface Parameters2 {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters2 params) { return null; } } @Test public void function_type_equals_java_function_type() throws Exception { given(module = createNativeModule(ModuleWithSStringFunction.class)); when(module.getFunction(name("func")).type()); thenReturned(STRING); } public static class ModuleWithSStringFunction { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_signature_contains_all_params() throws Exception { given(module = createNativeModule(ModuleWithTwoParamFunction.class)); when(module.getFunction(name("func")).parameters()); thenReturned(containsInAnyOrder(optionalParameter(STRING, "param1"), optionalParameter(STRING, "param2"))); } public static class ModuleWithTwoParamFunction { public interface Parameters { SString param1(); SString param2(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void allowed_param_types_are_accepted() throws Exception { given(module = createNativeModule(ModuleWithFunctionWithParametersOfAllTypes.class)); when(module.getFunction(name("func"))); thenReturned(); } public static class ModuleWithFunctionWithParametersOfAllTypes { public interface Parameters { public SString string(); public Array<SString> stringArray(); public SFile file(); public Array<SFile> fileArray(); public Blob blob(); public Array<Blob> blobArray(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void params_annotated_as_required_are_required() throws Exception { given(module = createNativeModule(ModuleWithFunctionWithRequiredParam.class)); given(function = module.getFunction(name("func"))); when(function.parameters().get(0).isRequired()); thenReturned(true); } public static class ModuleWithFunctionWithRequiredParam { public interface Parameters { @Required public SString param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void params_not_annotated_as_required_are_not_required() throws Exception { given(module = createNativeModule(ModuleWithFunctionWithNotRequiredParam.class)); given(function = module.getFunction(name("func"))); when(function.parameters().get(0).isRequired()); thenReturned(false); } public static class ModuleWithFunctionWithNotRequiredParam { public interface Parameters { public SString param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalParamTypeException.class) public void array_of_array_is_forbidden_as_param_type() throws Exception { module = createNativeModule(ModuleWithFunctionWithArrayOfArraysParameter.class); } public static class ModuleWithFunctionWithArrayOfArraysParameter { public interface Parameters { public Array<Array<SString>> param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalParamTypeException.class) public void non_smooth_type_is_forbidden_as_param_type() throws Exception { module = createNativeModule(ModuleWithFunctionWithNonSmoothParameter.class); } public static class ModuleWithFunctionWithNonSmoothParameter { public interface Parameters { public String param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_without_parameters_is_allowed() throws Exception { when(createNativeModule(ModuleWithFunctionWithNoParameter.class)); thenReturned(); } public static class ModuleWithFunctionWithNoParameter { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_string_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningString.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(STRING); } public static class ModuleWithFunctionReturningString { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_blob_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningBlob.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(BLOB); } public static class ModuleWithFunctionReturningBlob { public interface Parameters {} @SmoothFunction public static Blob func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_file_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningFile.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(FILE); } public static class ModuleWithFunctionReturningFile { public interface Parameters {} @SmoothFunction public static SFile func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_string_aray_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningStringArray.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(STRING_ARRAY); } public static class ModuleWithFunctionReturningStringArray { public interface Parameters {} @SmoothFunction public static Array<SString> func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_blob_aray_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningBlobArray.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(BLOB_ARRAY); } public static class ModuleWithFunctionReturningBlobArray { public interface Parameters {} @SmoothFunction public static Array<Blob> func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_file_aray_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningFileArray.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(FILE_ARRAY); } public static class ModuleWithFunctionReturningFileArray { public interface Parameters {} @SmoothFunction public static Array<SFile> func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalReturnTypeException.class) public void array_of_arrays_is_not_allowed_for_return_type() throws Exception { createNativeModule(ModuleWithFunctionReturningArrayOfArrays.class); } public static class ModuleWithFunctionReturningArrayOfArrays { public interface Parameters {} @SmoothFunction public static Array<Array<SString>> func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalReturnTypeException.class) public void non_smooth_type_is_not_allowed_for_return_type() throws Exception { createNativeModule(ModuleWithFunctionReturningNonSmoothType.class); } public static class ModuleWithFunctionReturningNonSmoothType { public interface Parameters {} @SmoothFunction public static String func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalFunctionNameException.class) public void function_with_illegal_smooth_names_are_not_allowed() throws Exception { createNativeModule(ModuleWithFunctionWithIllegalName.class); } public static class ModuleWithFunctionWithIllegalName { public interface Parameters {} @SmoothFunction public static SString my$function(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = NonPublicSmoothFunctionException.class) public void non_public_functions_are_forbidden() throws Exception { createNativeModule(ModuleWithNonPublicFunction.class); } public static class ModuleWithNonPublicFunction { public interface Parameters {} @SmoothFunction protected static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = NonStaticSmoothFunctionException.class) public void non_static_function_is_forbidden() throws Exception { createNativeModule(ModuleWithNonStaticFunction.class); } public static class ModuleWithNonStaticFunction { public interface Parameters {} @SmoothFunction public SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = ParamMethodHasArgumentsException.class) public void method_in_params_interface_cannot_have_parameters() throws Exception { createNativeModule(ModuleWithFunctionWhithParamsInterfaceWithMethodWithParams.class); } public static class ModuleWithFunctionWhithParamsInterfaceWithMethodWithParams { public interface Parameters { SString param(SString notAllowed); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void module_with_zero_functions_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithNoFunctions.class)); when(module).availableNames(); thenReturned(Matchers.emptyIterable()); } public static class ModuleWithNoFunctions {} public static Module createNativeModule(Class<?> clazz) throws Exception { File tempJarFile = File.createTempFile("tmp", ".jar"); try (JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tempJarFile))) { jarOutputStream.putNextEntry(new ZipEntry(binaryPath(clazz))); try (InputStream byteCodeInputStream = Classes.byteCodeAsInputStream(clazz)) { ByteStreams.copy(byteCodeInputStream, jarOutputStream); } } return NativeModuleFactory.createNativeModule(tempJarFile.toPath()); } }
src/main/test/org/smoothbuild/lang/module/NativeModuleFactoryTest.java
package org.smoothbuild.lang.module; import static org.hamcrest.Matchers.contains; import static org.smoothbuild.lang.base.Types.BLOB; import static org.smoothbuild.lang.base.Types.BLOB_ARRAY; import static org.smoothbuild.lang.base.Types.FILE; import static org.smoothbuild.lang.base.Types.FILE_ARRAY; import static org.smoothbuild.lang.base.Types.STRING; import static org.smoothbuild.lang.base.Types.STRING_ARRAY; import static org.smoothbuild.lang.function.base.Name.name; import static org.smoothbuild.lang.function.base.Parameter.optionalParameter; import static org.smoothbuild.util.Classes.binaryPath; import static org.testory.Testory.given; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import org.hamcrest.Matchers; import org.junit.Test; import org.smoothbuild.lang.base.Array; import org.smoothbuild.lang.base.Blob; import org.smoothbuild.lang.base.NativeApi; import org.smoothbuild.lang.base.SFile; import org.smoothbuild.lang.base.SString; import org.smoothbuild.lang.function.base.Function; import org.smoothbuild.lang.function.nativ.err.IllegalFunctionNameException; import org.smoothbuild.lang.function.nativ.err.IllegalParamTypeException; import org.smoothbuild.lang.function.nativ.err.IllegalReturnTypeException; import org.smoothbuild.lang.function.nativ.err.NonPublicSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.NonStaticSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.ParamMethodHasArgumentsException; import org.smoothbuild.lang.plugin.Required; import org.smoothbuild.lang.plugin.SmoothFunction; import org.smoothbuild.util.Classes; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; public class NativeModuleFactoryTest { private Module module; private Function<?> function; @Test public void module_available_names_contains_smooth_function_names() throws Exception { given(module = createNativeModule(ModuleWithOneFunction.class)); when(module.availableNames()); thenReturned(contains(name("func"))); } public static class ModuleWithOneFunction { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void module_with_more_than_one_function_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithTwoFunctions.class)); when(module.availableNames()); thenReturned(contains(name("func1"), name("func2"))); } public static class ModuleWithTwoFunctions { public interface Parameters {} @SmoothFunction public static SString func1(NativeApi nativeApi, Parameters params) { return null; } @SmoothFunction public static SString func2(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalArgumentException.class) public void two_functions_with_same_name_are_forbidden() throws Exception { createNativeModule(ModuleWithTwoFunctionsWithSameName.class); } public static class ModuleWithTwoFunctionsWithSameName { public interface Parameters {} public interface Parameters2 {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters2 params) { return null; } } @Test public void function_type_equals_java_function_type() throws Exception { given(module = createNativeModule(ModuleWithSStringFunction.class)); when(module.getFunction(name("func")).type()); thenReturned(STRING); } public static class ModuleWithSStringFunction { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_signature_contains_all_params() throws Exception { given(module = createNativeModule(ModuleWithTwoParamFunction.class)); when(module.getFunction(name("func")).parameters()); thenReturned(ImmutableList.of(optionalParameter(STRING, "param1"), optionalParameter(STRING, "param2"))); } public static class ModuleWithTwoParamFunction { public interface Parameters { SString param1(); SString param2(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void allowed_param_types_are_accepted() throws Exception { given(module = createNativeModule(ModuleWithFunctionWithParametersOfAllTypes.class)); when(module.getFunction(name("func"))); thenReturned(); } public static class ModuleWithFunctionWithParametersOfAllTypes { public interface Parameters { public SString string(); public Array<SString> stringArray(); public SFile file(); public Array<SFile> fileArray(); public Blob blob(); public Array<Blob> blobArray(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void params_annotated_as_required_are_required() throws Exception { given(module = createNativeModule(ModuleWithFunctionWithRequiredParam.class)); given(function = module.getFunction(name("func"))); when(function.parameters().get(0).isRequired()); thenReturned(true); } public static class ModuleWithFunctionWithRequiredParam { public interface Parameters { @Required public SString param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void params_not_annotated_as_required_are_not_required() throws Exception { given(module = createNativeModule(ModuleWithFunctionWithNotRequiredParam.class)); given(function = module.getFunction(name("func"))); when(function.parameters().get(0).isRequired()); thenReturned(false); } public static class ModuleWithFunctionWithNotRequiredParam { public interface Parameters { public SString param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalParamTypeException.class) public void array_of_array_is_forbidden_as_param_type() throws Exception { module = createNativeModule(ModuleWithFunctionWithArrayOfArraysParameter.class); } public static class ModuleWithFunctionWithArrayOfArraysParameter { public interface Parameters { public Array<Array<SString>> param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalParamTypeException.class) public void non_smooth_type_is_forbidden_as_param_type() throws Exception { module = createNativeModule(ModuleWithFunctionWithNonSmoothParameter.class); } public static class ModuleWithFunctionWithNonSmoothParameter { public interface Parameters { public String param(); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_without_parameters_is_allowed() throws Exception { when(createNativeModule(ModuleWithFunctionWithNoParameter.class)); thenReturned(); } public static class ModuleWithFunctionWithNoParameter { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_string_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningString.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(STRING); } public static class ModuleWithFunctionReturningString { public interface Parameters {} @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_blob_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningBlob.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(BLOB); } public static class ModuleWithFunctionReturningBlob { public interface Parameters {} @SmoothFunction public static Blob func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_file_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningFile.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(FILE); } public static class ModuleWithFunctionReturningFile { public interface Parameters {} @SmoothFunction public static SFile func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_string_aray_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningStringArray.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(STRING_ARRAY); } public static class ModuleWithFunctionReturningStringArray { public interface Parameters {} @SmoothFunction public static Array<SString> func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_blob_aray_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningBlobArray.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(BLOB_ARRAY); } public static class ModuleWithFunctionReturningBlobArray { public interface Parameters {} @SmoothFunction public static Array<Blob> func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void function_with_file_aray_result_type_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithFunctionReturningFileArray.class)); given(function = module.getFunction(name("func"))); when(function).type(); thenReturned(FILE_ARRAY); } public static class ModuleWithFunctionReturningFileArray { public interface Parameters {} @SmoothFunction public static Array<SFile> func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalReturnTypeException.class) public void array_of_arrays_is_not_allowed_for_return_type() throws Exception { createNativeModule(ModuleWithFunctionReturningArrayOfArrays.class); } public static class ModuleWithFunctionReturningArrayOfArrays { public interface Parameters {} @SmoothFunction public static Array<Array<SString>> func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalReturnTypeException.class) public void non_smooth_type_is_not_allowed_for_return_type() throws Exception { createNativeModule(ModuleWithFunctionReturningNonSmoothType.class); } public static class ModuleWithFunctionReturningNonSmoothType { public interface Parameters {} @SmoothFunction public static String func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = IllegalFunctionNameException.class) public void function_with_illegal_smooth_names_are_not_allowed() throws Exception { createNativeModule(ModuleWithFunctionWithIllegalName.class); } public static class ModuleWithFunctionWithIllegalName { public interface Parameters {} @SmoothFunction public static SString my$function(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = NonPublicSmoothFunctionException.class) public void non_public_functions_are_forbidden() throws Exception { createNativeModule(ModuleWithNonPublicFunction.class); } public static class ModuleWithNonPublicFunction { public interface Parameters {} @SmoothFunction protected static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = NonStaticSmoothFunctionException.class) public void non_static_function_is_forbidden() throws Exception { createNativeModule(ModuleWithNonStaticFunction.class); } public static class ModuleWithNonStaticFunction { public interface Parameters {} @SmoothFunction public SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test(expected = ParamMethodHasArgumentsException.class) public void method_in_params_interface_cannot_have_parameters() throws Exception { createNativeModule(ModuleWithFunctionWhithParamsInterfaceWithMethodWithParams.class); } public static class ModuleWithFunctionWhithParamsInterfaceWithMethodWithParams { public interface Parameters { SString param(SString notAllowed); } @SmoothFunction public static SString func(NativeApi nativeApi, Parameters params) { return null; } } @Test public void module_with_zero_functions_is_allowed() throws Exception { given(module = createNativeModule(ModuleWithNoFunctions.class)); when(module).availableNames(); thenReturned(Matchers.emptyIterable()); } public static class ModuleWithNoFunctions {} public static Module createNativeModule(Class<?> clazz) throws Exception { File tempJarFile = File.createTempFile("tmp", ".jar"); try (JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tempJarFile))) { jarOutputStream.putNextEntry(new ZipEntry(binaryPath(clazz))); try (InputStream byteCodeInputStream = Classes.byteCodeAsInputStream(clazz)) { ByteStreams.copy(byteCodeInputStream, jarOutputStream); } } return NativeModuleFactory.createNativeModule(tempJarFile.toPath()); } }
fixed test in NativeModuleFactoryTest
src/main/test/org/smoothbuild/lang/module/NativeModuleFactoryTest.java
fixed test in NativeModuleFactoryTest
<ide><path>rc/main/test/org/smoothbuild/lang/module/NativeModuleFactoryTest.java <ide> package org.smoothbuild.lang.module; <ide> <ide> import static org.hamcrest.Matchers.contains; <add>import static org.hamcrest.Matchers.containsInAnyOrder; <ide> import static org.smoothbuild.lang.base.Types.BLOB; <ide> import static org.smoothbuild.lang.base.Types.BLOB_ARRAY; <ide> import static org.smoothbuild.lang.base.Types.FILE; <ide> import org.smoothbuild.lang.plugin.SmoothFunction; <ide> import org.smoothbuild.util.Classes; <ide> <del>import com.google.common.collect.ImmutableList; <ide> import com.google.common.io.ByteStreams; <ide> <ide> public class NativeModuleFactoryTest { <ide> public void function_signature_contains_all_params() throws Exception { <ide> given(module = createNativeModule(ModuleWithTwoParamFunction.class)); <ide> when(module.getFunction(name("func")).parameters()); <del> thenReturned(ImmutableList.of(optionalParameter(STRING, "param1"), optionalParameter(STRING, <add> thenReturned(containsInAnyOrder(optionalParameter(STRING, "param1"), optionalParameter(STRING, <ide> "param2"))); <ide> } <ide>
Java
apache-2.0
c0de2df65989b4c7fcf574fb359866b439e424d1
0
rouazana/james,chibenwa/james,aduprat/james,aduprat/james,chibenwa/james,rouazana/james,chibenwa/james,aduprat/james,rouazana/james,rouazana/james,chibenwa/james,aduprat/james
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.transport.remotedeliverytester; import org.apache.james.test.mock.avalon.MockServiceManager; import org.apache.james.test.mock.avalon.MockStore; import org.apache.james.test.mock.james.InMemorySpoolRepository; import org.apache.james.transport.remotedeliverytester.Tester.TestStatus; import org.apache.mailet.Mail; import javax.mail.MessagingException; import javax.mail.SendFailedException; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import java.util.Random; import junit.framework.AssertionFailedError; import junit.framework.TestCase; public abstract class AbstractRemoteDeliveryTest extends TestCase { private int doTest = 0; private MockServiceManager serviceManager; private InMemorySpoolRepository outgoingSpool; public abstract RemoteDeliveryTestable getDeliverer(); public abstract Properties getParameters(); public void test1() throws Exception { if (doTest == 0 || doTest == 1) doTest1(getDeliverer(), getParameters()); } public void test2_0() throws Exception { if (doTest == 0 || doTest == 2) doTest2_0(getDeliverer(), getParameters()); } public void test2() throws Exception { if (doTest == 0 || doTest == 2) doTest2(getDeliverer(), getParameters()); } public void test3() throws Exception { if (doTest == 0 || doTest == 3) doTest3(getDeliverer(), getParameters()); } public void test4() throws Exception { if (doTest == 0 || doTest == 4) doTest4(getDeliverer(), getParameters()); } public void test5() throws Exception { if (doTest == 0 || doTest == 5) doTest5(getDeliverer(), getParameters()); } public void test6() throws Exception { if (doTest == 0 || doTest == 6) doTest6(getDeliverer(), getParameters()); } public void test7() throws Exception { if (doTest == 0 || doTest == 7) doTest7a(getDeliverer(), getParameters()); if (doTest == 0 || doTest == 7) doTest7b(getDeliverer(), getParameters()); } public void test8() throws Exception { // SOLO REMOTEDELIVERY E REMOTEDELIVERYVOID if (doTest == 0 || doTest == 8) doTest8(getDeliverer(), getParameters()); } public void test9() throws Exception { if (doTest == 0 || doTest == 9) doTest9(getDeliverer(), getParameters()); } public void test10() throws Exception { if (doTest == 0 || doTest == 10) doTest10(getDeliverer(), getParameters()); } /* Temporarily disabled. Maybe this randomly fails * It's not clear if the issue is THIS specific test and if the random * problem is in the RemoteDelivery code or in the test suite. public void testMulti() throws Exception { if (doTest == 0 || doTest == -1) doTestMulti(getDeliverer(), getParameters()); } */ protected void initEnvironment() { // Generate mock environment serviceManager = new MockServiceManager(); MockStore mockStore = new MockStore(); outgoingSpool = new InMemorySpoolRepository(); // new AvalonSpoolRepository(); mockStore.add("outgoing", outgoingSpool); serviceManager.put("org.apache.avalon.cornerstone.services.store.Store", mockStore); } protected Properties getStandardParameters() { Properties parameters = new Properties(); parameters.put("delayTime", "500 msec, 500 msec, 500 msec"); // msec, sec, minute, hour parameters.put("maxRetries", "3"); parameters.put("deliveryThreads", "1"); parameters.put("debug", "true"); parameters.put("sendpartial", "false"); parameters.put("bounceProcessor", "bounce"); // parameters.put("outgoing", "file://var/mail/outgoing_test/"); return parameters; } protected String[][] addServers(Tester tester, String[][] servers, boolean sendValid) { for (int i = 0; i < servers.length; i++) // for (int j = 0; j < servers[1 + i].length; j++) tester.addDomainServer(servers[0][i], servers[1 + i][j], new TransportRule.NameExpression(sendValid)); for (int j = 1; j < servers[i].length; j++) tester.addDomainServer(servers[i][0], servers[i][j], new TransportRule.NameExpression(sendValid)); return servers; } protected int waitEmptySpool(int maxWait) { if (maxWait == 0) maxWait = -1; while (outgoingSpool.size() > 0 && (maxWait > 0 || maxWait == -1)) { synchronized (this) { try { wait(1000); } catch (InterruptedException e) {} } if (maxWait != -1) maxWait -= 1000; } if (outgoingSpool.size() > 0) { Iterator i = outgoingSpool.list(); while (i.hasNext()) { String key = (String) i.next(); Mail m = null; try { m = outgoingSpool.retrieve(key); System.err.println("Still in outgoing: "+key+" S:"+m.getState()+" E:"+m.getErrorMessage()+" F:"+m.getSender()+" T:"+m.getRecipients()+" M:"+m.getMessage().getContent()); } catch (MessagingException e) { e.printStackTrace(); System.err.println("Still in outgoing: "+key+" NULL"); } catch (IOException e) { e.printStackTrace(); System.err.println("Still in outgoing: "+key+" IOException"); } } } return outgoingSpool.size(); } /** * * @param status * @param sends * Email send attempts number. if < 0 will take the minimum number. * @param maxConnection * Max attempts to connect the server. If < 0 defaults to the minimum. */ protected void assertWhole(Tester.TestStatus status, int sends, int maxConnection) { if (sends >= 0) assertEquals(sends, status.getTransportSendCount()); else assertTrue(status.getTransportSendCount() >= -sends); if (maxConnection >= 0) { assertTrue(maxConnection >= status.getTransportConnectionCount()); assertTrue(maxConnection >= status.getTransportCloseCount()); } else { assertTrue(-maxConnection <= status.getTransportConnectionCount()); assertTrue(-maxConnection <= status.getTransportCloseCount()); } assertEquals(status.getTransportConnectionCount(), status .getTransportCloseCount()); } /** * * @param status * @param server * @param sends * Email send attempts number. if < 0 will take the minimum number. * @param maxConnection * Max attempts to connect the server. If < 0 defaults to the minimum. */ protected void assertServer(Tester.TestStatus status, String server, int sends, int maxConnection) { if (sends >= 0) assertEquals(sends, status.getTransportServerSendCount(server)); else assertTrue(status.getTransportServerSendCount(server) >= -sends); if (maxConnection >= 0) { assertTrue(maxConnection >= status.getTransportServerConnectionCount(server)); assertTrue(maxConnection >= status.getTransportServerCloseCount(server)); } else { assertTrue(-maxConnection <= status.getTransportServerConnectionCount(server)); assertTrue(-maxConnection <= status.getTransportServerCloseCount(server)); } assertEquals(status.getTransportServerConnectionCount(server), status.getTransportServerCloseCount(server)); } /** * Assert procmail result. * * @param pmail * @param state * @param sends * Email send attempts number. if < 0 will take the minimum number. * @param minBounce * @param lastServer */ protected void assertProcMail(ProcMail pmail, int state, int sends, int minBounce, String lastServer) { if (sends >= 0) assertEquals(sends, pmail.getSendCount()); else assertTrue(pmail.getSendCount() >= -sends); assertTrue(pmail.getBounceCount() >= minBounce); assertEquals(state, pmail.getState()); assertEquals(lastServer, pmail.getSendCount() > 0 ? pmail.getSendServer(pmail.getSendCount() - 1) : null); assertEquals(0, pmail.getErrorFlags()); } protected void doTest1(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); // test initialization tester.addDomainServer("test.it", "smtp://mail.test.it:25"); ProcMail.Listing mails = tester.service("mail", "[email protected]", "[email protected]", "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // checks assertWhole(tester.getTestStatus(), 1, 1); assertServer(tester.getTestStatus(), "smtp://mail.test.it:25", 1, 1); assertEquals(1, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, "smtp://mail.test.it:25"); } protected void doTest2_0(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); // test initialization tester.addDomainServer("test.it", "smtp://mail.test.it:25", new TransportRule.Default() { public void onConnect(Tester.TestStatus status, String server) throws MessagingException { // Manda una connessione al connect, solo la prima connessione if (status.getTransportServerConnectionCount(server) == 0) throw new MessagingException("Connect"); } }); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody", new TransportRule.Default() { public void onSendMessage(TestStatus status, String server, ProcMail.Listing pmails) throws MessagingException, SendFailedException { // Manda una connessione al send, solo al primo send if (status.getTransportServerSendCount(server) == 0) throw new MessagingException("Send"); } }); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // checks assertWhole(tester.getTestStatus(), 4, 3); assertServer(tester.getTestStatus(), "smtp://mail.test.it:25", 4, 3); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, "smtp://mail.test.it:25"); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, "smtp://mail.test.it:25"); } protected void doTest2(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://mail-me-1-ok.*-me-1-ok.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 4, 3); assertServer(tester.getTestStatus(), servers[0][1], 4, 3); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, servers[0][1]); } /** * Permanent error fo 1/2 addresses. * * @param rd * @throws Exception */ protected void doTest3(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe400.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 2, 1); assertServer(tester.getTestStatus(), servers[0][1], 2, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); } /** * Temporary error for 1/2 addresses. * * @param rd * @throws Exception */ protected void doTest4(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe400V.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(10000)); // Checks assertWhole(tester.getTestStatus(), 5, 4); assertServer(tester.getTestStatus(), servers[0][1], 5, 4); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); } /** * 1 Temporary error + 1 Permanent error * * @param rd * @throws Exception */ protected void doTest5(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe411V.b*-smtpafe500.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(10000)); // Checks try { assertWhole(tester.getTestStatus(), 5, 4); assertServer(tester.getTestStatus(), servers[0][1], 5, 4); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); } catch (AssertionFailedError e) { // TEMPORARILY add a dump stack on failure to // see if we have a deadlock (unlikely) or simply the // notification is not working properly. (see JAMES-850) Thread.dumpStack(); throw e; } } /** * Mixed * * @param rd * @throws Exception */ protected void doTest6(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe400V.b*-smtpafe500.test.it:25" }, { "test2.it", "smtp://s1-ok.a*-smtpafe400V.b*-smtpafe500.test2.it:25" } }, true); ProcMail.Listing mails1 = tester.service("mail1", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test1\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails2 = tester.service("mail2", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test2\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails3 = tester.service("mail3", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test3\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails4 = tester.service("mail4", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test4\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 14, 10); assertServer(tester.getTestStatus(), servers[0][1], 10, 8); assertServer(tester.getTestStatus(), servers[1][1], 4, 2); assertEquals(8, tester.getProcMails().size()); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails2.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[1][1]); assertProcMail(mails2.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[1][1]); assertProcMail(mails3.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails3.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails4.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[1][1]); assertProcMail(mails4.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[1][1]); } /** * NPE during send * * @param rd * @throws Exception */ protected void doTest7a(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-null.test.it:25" }, }, true); ProcMail.Listing mails1 = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test1\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool //assertEquals(0, waitEmptySpool(5000)); assertEquals(0, waitEmptySpool(0)); // Checks assertWhole(tester.getTestStatus(), 2, 1); assertServer(tester.getTestStatus(), servers[0][1], 2, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); } protected void doTest7b(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-null.**-ok.test.it:25" }, }, true); ProcMail.Listing mails1 = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test1\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Controlli assertWhole(tester.getTestStatus(), 0, 1); assertServer(tester.getTestStatus(), servers[0][1], 0, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_IDLE, 0, 1, null); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_IDLE, 0, 1, null); } /** * Multiple mx servers for a single domain. One failing with a 400V on the first reception. * * This test expect the RemoteDelivery to check the next server on a temporary error on the first * server. Other remote delivery implementations could use different strategies. */ protected void doTest8(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { // a.it: all addresses ok. { "a.it", "smtp://s1-ok.a.it:25", "smtp://s2-ok.a.it:25" }, // b.it: one server always reply smtpafe400V, the other works. { "b.it", "smtp://s1-ok.**-smtpafe400V.b.it:25", "smtp://s2-ok.b.it:25" }, }, true); ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); //ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), -2, -2); // Almeno 2 connessioni deve averle fatte assertServer(tester.getTestStatus(), servers[0][1], 1, 1); assertServer(tester.getTestStatus(), servers[1][1], -1, -1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, -1, 0, servers[1][2]); } /** * Multiple MX server for a domain. */ protected void doTest9(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { // a.it: all addresses ok. { "a.it", "smtp://s1-ok.a.it:25", "smtp://s2-ok.a.it:25" }, // b.it: one server always reply smtpsfe500V, the other works. { "b.it", "smtp://s1-me.b.it:25", "smtp://s2-ok.b.it:25" }, }, true); ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); //ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), -2, -3); // Almeno 2 connessioni deve averle fatte assertServer(tester.getTestStatus(), servers[0][1], 1, 1); assertServer(tester.getTestStatus(), servers[1][1], 0, 1); assertServer(tester.getTestStatus(), servers[1][2], 1, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[1][2]); } /** * IO Exception */ protected void doTest10(RemoteDeliveryTestable rd, Properties params) throws Exception { // creazione tester initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { // i.it: ioexception (during connect or send for "a", depending on the server) { "i.it", "smtp://s1-io.i.it:25", "smtp://s2-ok.a*-io.i.it:25"}, }, true); //ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 1, 2); assertServer(tester.getTestStatus(), servers[0][1], 0, 1); assertServer(tester.getTestStatus(), servers[0][2], 1, 1); assertEquals(1, tester.getProcMails().size()); //assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, -1, 0, servers[0][2]); } protected String[][] getTestMultiServers() { return new String[][] { // a.it: ok for every address { "a.it", "smtp://s1-ok.a.it:25", "smtp://s2-ok.a.it:25" }, // b.it: one server throws ME on every call, the other works. //{ "b.it", "smtp://s1-ok.**-smtpafe400V.b.it:25", "smtp://s2-ok.b.it:25" }, <- Questo su MailSender non lo puo' fare { "b.it", "smtp://s1-me.b.it:25", "smtp://s2-ok.b.it:25" }, // c.it: both servers replies smtpafe400V. { "c.it", "smtp://s1-ok.**-smtpafe400V.c.it:25", "smtp://s2-ok.**-smtpafe400V.c.it:25" }, // d.it: Messaging exception once every 2 attempts. { "d.it", "smtp://s1-me-1-ok-1-rpt.*-me-1-ok-1-rpt.d.it:25" }, // e.it: addresses starting with "a" are rejected with a smtpafe400 { "e.it", "smtp://s1-ok.a*-smtpafe400.e.it:25" }, // f.it: addresses starting with "a" are rejected with a smtpafe400V from the first server // the second server do the same with "b" addresses. { "f.it", "smtp://s1-ok.a*-smtpafe400V.f.it:25", "smtp://s2-ok.b*-smtpafe400V.f.it:25" }, // g.it: "a" not accepted (temporary), "b" not accepted (permanent), "c" half temporary exceptions { "g.it", "smtp://s1-ok.a*-smtpafe411V.b*-smtpafe500.test.c*-smtpafe411V-1-ok-1-rpt.g.it:25" }, // h.it: null pointer exception (during connect for one server and during send for the other) { "h.it", "smtp://s1-null.h.it:25", "smtp://s2-ok.**-null.h.it:25"}, // i.it: ioexception during connect on one server, the other works. { "i.it", "smtp://s1-io.i.it:25", "smtp://s2-ok.i.it:25"}, }; } protected String[][] getTestMultiEmails() { return new String[][] { { "a.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "b.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "c.it", "[email protected]", "0", "[email protected]", "0", "[email protected]", "0"}, { "d.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "e.it", "[email protected]", "0", "[email protected]", "1", "[email protected]", "1"}, { "f.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "g.it", "[email protected]", "0", "[email protected]", "0", "[email protected]", "1"}, { "h.it", "[email protected]", "0", "[email protected]", "0", "[email protected]", "0"}, { "i.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, }; } protected void doTestMulti(RemoteDeliveryTestable rd, Properties params) throws Exception { // Number of attempts int loopCount = 20; // Wait time between attempts int loopWait = 0; // Max wait betwen attempts (for the randomization) int loopWaitRandom = 100; // Max number of recipients per mail int maxRecipientsPerEmail = 3; // Probability for the recipients to be in the same domain int probRecipientsSameDomain = 30; // creazione tester initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); // String[][] servers = addServers(tester, getTestMultiServers(), true); String[][] emails = getTestMultiEmails(); Random rnd = new Random(); ProcMail.Listing[] results = new ProcMail.Listing[loopCount]; for (int i = 0; i < loopCount; i++) { // Calcolo recipients ArrayList rcpts = new ArrayList(); int rcptn = rnd.nextInt(maxRecipientsPerEmail) + 1; if (rnd.nextInt(100) < probRecipientsSameDomain) { // same domain int dom = rnd.nextInt(emails.length); // for the domain we don't have more email, takes other domains emails if (rcptn >= (emails[dom].length - 1) / 2) for (int j = 1; j < emails[dom].length; j += 2) rcpts.add(emails[dom][j]); else { boolean[] got = new boolean[(emails[dom].length - 1) / 2]; int done = 0; while (done < rcptn) { int t = rnd.nextInt((emails[dom].length - 1) / 2); if (!got[t]) { rcpts.add(emails[dom][t * 2 + 1]); got[t] = true; done++; } } } } else { // multiple domains boolean got[][] = new boolean[emails.length][]; for (int j = 0; j < emails.length; j++) got[j] = new boolean[1 + (emails[j].length - 1) / 2]; int done = 0; int gotdepth = 0; while (done < rcptn && gotdepth < got.length) { int dom; do {dom = rnd.nextInt(got.length);} while (got[dom][0]); int t; do {t = rnd.nextInt(got[dom].length - 1);} while (got[dom][t + 1]); rcpts.add(emails[dom][t * 2 + 1]); got[dom][t + 1] = true; for (int j = 1; j < got[dom].length && got[dom][j]; j++) if (j == got[dom].length - 1) got[dom][0] = true; done ++; } } System.out.println("------"); for (int j = 0; j < rcpts.size(); j++) System.out.println(rcpts.get(j)); results[i] = tester.service("M" + i, i + "@test.it", (String[]) rcpts.toArray(new String[0]), "Subject: test" + i + "\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); synchronized(this) { if (loopWait > 0) wait(loopWait); if (loopWaitRandom > 0) wait(rnd.nextInt(loopWaitRandom)); } } // Wait for empty spool assertEquals(0, waitEmptySpool(30000)); Hashtable emailsRes = new Hashtable(); for (int i = 0; i < emails.length; i ++) for (int j = 1; j < emails[i].length; j += 2) emailsRes.put(emails[i][j], emails[i][j + 1]); boolean error = false; for (int i = 0; i < results.length; i++) { System.out.println("Call#" + i); for (int j = 0; j < results[i].size(); j++) { ProcMail pmail = results[i].get(j); System.out.print(pmail.getKey() + " status:" + (pmail.getState() == ProcMail.STATE_SENT ? "SENT" : pmail.getState() == ProcMail.STATE_SENT_ERROR ? "ERR" : "" + pmail.getState() ) + " sends:" + pmail.getSendCount()); String res = (String) emailsRes.get(pmail.getRecipient().toString()); if (pmail.getState() == ProcMail.STATE_IDLE) pmail.setState(ProcMail.STATE_SENT_ERROR); if (pmail.getState() != (res.equals("0") ? ProcMail.STATE_SENT_ERROR: ProcMail.STATE_SENT)) { System.out.print(" <<< ERROR"); error = true; } System.out.print("\n"); } } assertFalse(error); } }
trunk/mailets-function/src/test/java/org/apache/james/transport/remotedeliverytester/AbstractRemoteDeliveryTest.java
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.transport.remotedeliverytester; import org.apache.james.test.mock.avalon.MockServiceManager; import org.apache.james.test.mock.avalon.MockStore; import org.apache.james.test.mock.james.InMemorySpoolRepository; import org.apache.james.transport.remotedeliverytester.Tester.TestStatus; import org.apache.mailet.Mail; import javax.mail.MessagingException; import javax.mail.SendFailedException; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import java.util.Random; import junit.framework.TestCase; public abstract class AbstractRemoteDeliveryTest extends TestCase { private int doTest = 0; private MockServiceManager serviceManager; private InMemorySpoolRepository outgoingSpool; public abstract RemoteDeliveryTestable getDeliverer(); public abstract Properties getParameters(); public void test1() throws Exception { if (doTest == 0 || doTest == 1) doTest1(getDeliverer(), getParameters()); } public void test2_0() throws Exception { if (doTest == 0 || doTest == 2) doTest2_0(getDeliverer(), getParameters()); } public void test2() throws Exception { if (doTest == 0 || doTest == 2) doTest2(getDeliverer(), getParameters()); } public void test3() throws Exception { if (doTest == 0 || doTest == 3) doTest3(getDeliverer(), getParameters()); } public void test4() throws Exception { if (doTest == 0 || doTest == 4) doTest4(getDeliverer(), getParameters()); } public void test5() throws Exception { if (doTest == 0 || doTest == 5) doTest5(getDeliverer(), getParameters()); } public void test6() throws Exception { if (doTest == 0 || doTest == 6) doTest6(getDeliverer(), getParameters()); } public void test7() throws Exception { if (doTest == 0 || doTest == 7) doTest7a(getDeliverer(), getParameters()); if (doTest == 0 || doTest == 7) doTest7b(getDeliverer(), getParameters()); } public void test8() throws Exception { // SOLO REMOTEDELIVERY E REMOTEDELIVERYVOID if (doTest == 0 || doTest == 8) doTest8(getDeliverer(), getParameters()); } public void test9() throws Exception { if (doTest == 0 || doTest == 9) doTest9(getDeliverer(), getParameters()); } public void test10() throws Exception { if (doTest == 0 || doTest == 10) doTest10(getDeliverer(), getParameters()); } /* Temporarily disabled. Maybe this randomly fails * It's not clear if the issue is THIS specific test and if the random * problem is in the RemoteDelivery code or in the test suite. public void testMulti() throws Exception { if (doTest == 0 || doTest == -1) doTestMulti(getDeliverer(), getParameters()); } */ protected void initEnvironment() { // Generate mock environment serviceManager = new MockServiceManager(); MockStore mockStore = new MockStore(); outgoingSpool = new InMemorySpoolRepository(); // new AvalonSpoolRepository(); mockStore.add("outgoing", outgoingSpool); serviceManager.put("org.apache.avalon.cornerstone.services.store.Store", mockStore); } protected Properties getStandardParameters() { Properties parameters = new Properties(); parameters.put("delayTime", "500 msec, 500 msec, 500 msec"); // msec, sec, minute, hour parameters.put("maxRetries", "3"); parameters.put("deliveryThreads", "1"); parameters.put("debug", "true"); parameters.put("sendpartial", "false"); parameters.put("bounceProcessor", "bounce"); // parameters.put("outgoing", "file://var/mail/outgoing_test/"); return parameters; } protected String[][] addServers(Tester tester, String[][] servers, boolean sendValid) { for (int i = 0; i < servers.length; i++) // for (int j = 0; j < servers[1 + i].length; j++) tester.addDomainServer(servers[0][i], servers[1 + i][j], new TransportRule.NameExpression(sendValid)); for (int j = 1; j < servers[i].length; j++) tester.addDomainServer(servers[i][0], servers[i][j], new TransportRule.NameExpression(sendValid)); return servers; } protected int waitEmptySpool(int maxWait) { if (maxWait == 0) maxWait = -1; while (outgoingSpool.size() > 0 && (maxWait > 0 || maxWait == -1)) { synchronized (this) { try { wait(1000); } catch (InterruptedException e) {} } if (maxWait != -1) maxWait -= 1000; } if (outgoingSpool.size() > 0) { Iterator i = outgoingSpool.list(); while (i.hasNext()) { String key = (String) i.next(); Mail m = null; try { m = outgoingSpool.retrieve(key); System.err.println("Still in outgoing: "+key+" S:"+m.getState()+" E:"+m.getErrorMessage()+" F:"+m.getSender()+" T:"+m.getRecipients()+" M:"+m.getMessage().getContent()); } catch (MessagingException e) { e.printStackTrace(); System.err.println("Still in outgoing: "+key+" NULL"); } catch (IOException e) { e.printStackTrace(); System.err.println("Still in outgoing: "+key+" IOException"); } } } return outgoingSpool.size(); } /** * * @param status * @param sends * Email send attempts number. if < 0 will take the minimum number. * @param maxConnection * Max attempts to connect the server. If < 0 defaults to the minimum. */ protected void assertWhole(Tester.TestStatus status, int sends, int maxConnection) { if (sends >= 0) assertEquals(sends, status.getTransportSendCount()); else assertTrue(status.getTransportSendCount() >= -sends); if (maxConnection >= 0) { assertTrue(maxConnection >= status.getTransportConnectionCount()); assertTrue(maxConnection >= status.getTransportCloseCount()); } else { assertTrue(-maxConnection <= status.getTransportConnectionCount()); assertTrue(-maxConnection <= status.getTransportCloseCount()); } assertEquals(status.getTransportConnectionCount(), status .getTransportCloseCount()); } /** * * @param status * @param server * @param sends * Email send attempts number. if < 0 will take the minimum number. * @param maxConnection * Max attempts to connect the server. If < 0 defaults to the minimum. */ protected void assertServer(Tester.TestStatus status, String server, int sends, int maxConnection) { if (sends >= 0) assertEquals(sends, status.getTransportServerSendCount(server)); else assertTrue(status.getTransportServerSendCount(server) >= -sends); if (maxConnection >= 0) { assertTrue(maxConnection >= status.getTransportServerConnectionCount(server)); assertTrue(maxConnection >= status.getTransportServerCloseCount(server)); } else { assertTrue(-maxConnection <= status.getTransportServerConnectionCount(server)); assertTrue(-maxConnection <= status.getTransportServerCloseCount(server)); } assertEquals(status.getTransportServerConnectionCount(server), status.getTransportServerCloseCount(server)); } /** * Assert procmail result. * * @param pmail * @param state * @param sends * Email send attempts number. if < 0 will take the minimum number. * @param minBounce * @param lastServer */ protected void assertProcMail(ProcMail pmail, int state, int sends, int minBounce, String lastServer) { if (sends >= 0) assertEquals(sends, pmail.getSendCount()); else assertTrue(pmail.getSendCount() >= -sends); assertTrue(pmail.getBounceCount() >= minBounce); assertEquals(state, pmail.getState()); assertEquals(lastServer, pmail.getSendCount() > 0 ? pmail.getSendServer(pmail.getSendCount() - 1) : null); assertEquals(0, pmail.getErrorFlags()); } protected void doTest1(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); // test initialization tester.addDomainServer("test.it", "smtp://mail.test.it:25"); ProcMail.Listing mails = tester.service("mail", "[email protected]", "[email protected]", "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // checks assertWhole(tester.getTestStatus(), 1, 1); assertServer(tester.getTestStatus(), "smtp://mail.test.it:25", 1, 1); assertEquals(1, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, "smtp://mail.test.it:25"); } protected void doTest2_0(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); // test initialization tester.addDomainServer("test.it", "smtp://mail.test.it:25", new TransportRule.Default() { public void onConnect(Tester.TestStatus status, String server) throws MessagingException { // Manda una connessione al connect, solo la prima connessione if (status.getTransportServerConnectionCount(server) == 0) throw new MessagingException("Connect"); } }); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody", new TransportRule.Default() { public void onSendMessage(TestStatus status, String server, ProcMail.Listing pmails) throws MessagingException, SendFailedException { // Manda una connessione al send, solo al primo send if (status.getTransportServerSendCount(server) == 0) throw new MessagingException("Send"); } }); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // checks assertWhole(tester.getTestStatus(), 4, 3); assertServer(tester.getTestStatus(), "smtp://mail.test.it:25", 4, 3); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, "smtp://mail.test.it:25"); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, "smtp://mail.test.it:25"); } protected void doTest2(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://mail-me-1-ok.*-me-1-ok.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 4, 3); assertServer(tester.getTestStatus(), servers[0][1], 4, 3); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 2, 0, servers[0][1]); } /** * Permanent error fo 1/2 addresses. * * @param rd * @throws Exception */ protected void doTest3(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe400.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 2, 1); assertServer(tester.getTestStatus(), servers[0][1], 2, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); } /** * Temporary error for 1/2 addresses. * * @param rd * @throws Exception */ protected void doTest4(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe400V.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(10000)); // Checks assertWhole(tester.getTestStatus(), 5, 4); assertServer(tester.getTestStatus(), servers[0][1], 5, 4); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); } /** * 1 Temporary error + 1 Permanent error * * @param rd * @throws Exception */ protected void doTest5(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe411V.b*-smtpafe500.test.it:25" } }, true); ProcMail.Listing mails = tester.service("mail", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(10000)); // Checks assertWhole(tester.getTestStatus(), 5, 4); assertServer(tester.getTestStatus(), servers[0][1], 5, 4); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); } /** * Mixed * * @param rd * @throws Exception */ protected void doTest6(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-smtpafe400V.b*-smtpafe500.test.it:25" }, { "test2.it", "smtp://s1-ok.a*-smtpafe400V.b*-smtpafe500.test2.it:25" } }, true); ProcMail.Listing mails1 = tester.service("mail1", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test1\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails2 = tester.service("mail2", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test2\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails3 = tester.service("mail3", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test3\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails4 = tester.service("mail4", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test4\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 14, 10); assertServer(tester.getTestStatus(), servers[0][1], 10, 8); assertServer(tester.getTestStatus(), servers[1][1], 4, 2); assertEquals(8, tester.getProcMails().size()); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails2.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[1][1]); assertProcMail(mails2.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[1][1]); assertProcMail(mails3.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); assertProcMail(mails3.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails4.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[1][1]); assertProcMail(mails4.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[1][1]); } /** * NPE during send * * @param rd * @throws Exception */ protected void doTest7a(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-ok.a*-null.test.it:25" }, }, true); ProcMail.Listing mails1 = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test1\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool //assertEquals(0, waitEmptySpool(5000)); assertEquals(0, waitEmptySpool(0)); // Checks assertWhole(tester.getTestStatus(), 2, 1); assertServer(tester.getTestStatus(), servers[0][1], 2, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); } protected void doTest7b(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { { "test.it", "smtp://s1-null.**-ok.test.it:25" }, }, true); ProcMail.Listing mails1 = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test1\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Controlli assertWhole(tester.getTestStatus(), 0, 1); assertServer(tester.getTestStatus(), servers[0][1], 0, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_IDLE, 0, 1, null); assertProcMail(mails1.get("[email protected]"), ProcMail.STATE_IDLE, 0, 1, null); } /** * Multiple mx servers for a single domain. One failing with a 400V on the first reception. * * This test expect the RemoteDelivery to check the next server on a temporary error on the first * server. Other remote delivery implementations could use different strategies. */ protected void doTest8(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { // a.it: all addresses ok. { "a.it", "smtp://s1-ok.a.it:25", "smtp://s2-ok.a.it:25" }, // b.it: one server always reply smtpafe400V, the other works. { "b.it", "smtp://s1-ok.**-smtpafe400V.b.it:25", "smtp://s2-ok.b.it:25" }, }, true); ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); //ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), -2, -2); // Almeno 2 connessioni deve averle fatte assertServer(tester.getTestStatus(), servers[0][1], 1, 1); assertServer(tester.getTestStatus(), servers[1][1], -1, -1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, -1, 0, servers[1][2]); } /** * Multiple MX server for a domain. */ protected void doTest9(RemoteDeliveryTestable rd, Properties params) throws Exception { initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { // a.it: all addresses ok. { "a.it", "smtp://s1-ok.a.it:25", "smtp://s2-ok.a.it:25" }, // b.it: one server always reply smtpsfe500V, the other works. { "b.it", "smtp://s1-me.b.it:25", "smtp://s2-ok.b.it:25" }, }, true); ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); //ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), -2, -3); // Almeno 2 connessioni deve averle fatte assertServer(tester.getTestStatus(), servers[0][1], 1, 1); assertServer(tester.getTestStatus(), servers[1][1], 0, 1); assertServer(tester.getTestStatus(), servers[1][2], 1, 1); assertEquals(2, tester.getProcMails().size()); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, 1, 0, servers[1][2]); } /** * IO Exception */ protected void doTest10(RemoteDeliveryTestable rd, Properties params) throws Exception { // creazione tester initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); String[][] servers = addServers(tester, new String[][] { // i.it: ioexception (during connect or send for "a", depending on the server) { "i.it", "smtp://s1-io.i.it:25", "smtp://s2-ok.a*-io.i.it:25"}, }, true); //ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]", "[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); ProcMail.Listing mails = tester.service("M0", "[email protected]", new String[] {"[email protected]"}, "Subject: test0\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); // Wait for empty spool assertEquals(0, waitEmptySpool(5000)); // Checks assertWhole(tester.getTestStatus(), 1, 2); assertServer(tester.getTestStatus(), servers[0][1], 0, 1); assertServer(tester.getTestStatus(), servers[0][2], 1, 1); assertEquals(1, tester.getProcMails().size()); //assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 0, servers[0][1]); assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT, -1, 0, servers[0][2]); } protected String[][] getTestMultiServers() { return new String[][] { // a.it: ok for every address { "a.it", "smtp://s1-ok.a.it:25", "smtp://s2-ok.a.it:25" }, // b.it: one server throws ME on every call, the other works. //{ "b.it", "smtp://s1-ok.**-smtpafe400V.b.it:25", "smtp://s2-ok.b.it:25" }, <- Questo su MailSender non lo puo' fare { "b.it", "smtp://s1-me.b.it:25", "smtp://s2-ok.b.it:25" }, // c.it: both servers replies smtpafe400V. { "c.it", "smtp://s1-ok.**-smtpafe400V.c.it:25", "smtp://s2-ok.**-smtpafe400V.c.it:25" }, // d.it: Messaging exception once every 2 attempts. { "d.it", "smtp://s1-me-1-ok-1-rpt.*-me-1-ok-1-rpt.d.it:25" }, // e.it: addresses starting with "a" are rejected with a smtpafe400 { "e.it", "smtp://s1-ok.a*-smtpafe400.e.it:25" }, // f.it: addresses starting with "a" are rejected with a smtpafe400V from the first server // the second server do the same with "b" addresses. { "f.it", "smtp://s1-ok.a*-smtpafe400V.f.it:25", "smtp://s2-ok.b*-smtpafe400V.f.it:25" }, // g.it: "a" not accepted (temporary), "b" not accepted (permanent), "c" half temporary exceptions { "g.it", "smtp://s1-ok.a*-smtpafe411V.b*-smtpafe500.test.c*-smtpafe411V-1-ok-1-rpt.g.it:25" }, // h.it: null pointer exception (during connect for one server and during send for the other) { "h.it", "smtp://s1-null.h.it:25", "smtp://s2-ok.**-null.h.it:25"}, // i.it: ioexception during connect on one server, the other works. { "i.it", "smtp://s1-io.i.it:25", "smtp://s2-ok.i.it:25"}, }; } protected String[][] getTestMultiEmails() { return new String[][] { { "a.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "b.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "c.it", "[email protected]", "0", "[email protected]", "0", "[email protected]", "0"}, { "d.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "e.it", "[email protected]", "0", "[email protected]", "1", "[email protected]", "1"}, { "f.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, { "g.it", "[email protected]", "0", "[email protected]", "0", "[email protected]", "1"}, { "h.it", "[email protected]", "0", "[email protected]", "0", "[email protected]", "0"}, { "i.it", "[email protected]", "1", "[email protected]", "1", "[email protected]", "1"}, }; } protected void doTestMulti(RemoteDeliveryTestable rd, Properties params) throws Exception { // Number of attempts int loopCount = 20; // Wait time between attempts int loopWait = 0; // Max wait betwen attempts (for the randomization) int loopWaitRandom = 100; // Max number of recipients per mail int maxRecipientsPerEmail = 3; // Probability for the recipients to be in the same domain int probRecipientsSameDomain = 30; // creazione tester initEnvironment(); Tester tester = new Tester(rd); tester.init(serviceManager, params); // String[][] servers = addServers(tester, getTestMultiServers(), true); String[][] emails = getTestMultiEmails(); Random rnd = new Random(); ProcMail.Listing[] results = new ProcMail.Listing[loopCount]; for (int i = 0; i < loopCount; i++) { // Calcolo recipients ArrayList rcpts = new ArrayList(); int rcptn = rnd.nextInt(maxRecipientsPerEmail) + 1; if (rnd.nextInt(100) < probRecipientsSameDomain) { // same domain int dom = rnd.nextInt(emails.length); // for the domain we don't have more email, takes other domains emails if (rcptn >= (emails[dom].length - 1) / 2) for (int j = 1; j < emails[dom].length; j += 2) rcpts.add(emails[dom][j]); else { boolean[] got = new boolean[(emails[dom].length - 1) / 2]; int done = 0; while (done < rcptn) { int t = rnd.nextInt((emails[dom].length - 1) / 2); if (!got[t]) { rcpts.add(emails[dom][t * 2 + 1]); got[t] = true; done++; } } } } else { // multiple domains boolean got[][] = new boolean[emails.length][]; for (int j = 0; j < emails.length; j++) got[j] = new boolean[1 + (emails[j].length - 1) / 2]; int done = 0; int gotdepth = 0; while (done < rcptn && gotdepth < got.length) { int dom; do {dom = rnd.nextInt(got.length);} while (got[dom][0]); int t; do {t = rnd.nextInt(got[dom].length - 1);} while (got[dom][t + 1]); rcpts.add(emails[dom][t * 2 + 1]); got[dom][t + 1] = true; for (int j = 1; j < got[dom].length && got[dom][j]; j++) if (j == got[dom].length - 1) got[dom][0] = true; done ++; } } System.out.println("------"); for (int j = 0; j < rcpts.size(); j++) System.out.println(rcpts.get(j)); results[i] = tester.service("M" + i, i + "@test.it", (String[]) rcpts.toArray(new String[0]), "Subject: test" + i + "\r\nContent-Transfer-Encoding: plain\r\n\r\nbody"); synchronized(this) { if (loopWait > 0) wait(loopWait); if (loopWaitRandom > 0) wait(rnd.nextInt(loopWaitRandom)); } } // Wait for empty spool assertEquals(0, waitEmptySpool(30000)); Hashtable emailsRes = new Hashtable(); for (int i = 0; i < emails.length; i ++) for (int j = 1; j < emails[i].length; j += 2) emailsRes.put(emails[i][j], emails[i][j + 1]); boolean error = false; for (int i = 0; i < results.length; i++) { System.out.println("Call#" + i); for (int j = 0; j < results[i].size(); j++) { ProcMail pmail = results[i].get(j); System.out.print(pmail.getKey() + " status:" + (pmail.getState() == ProcMail.STATE_SENT ? "SENT" : pmail.getState() == ProcMail.STATE_SENT_ERROR ? "ERR" : "" + pmail.getState() ) + " sends:" + pmail.getSendCount()); String res = (String) emailsRes.get(pmail.getRecipient().toString()); if (pmail.getState() == ProcMail.STATE_IDLE) pmail.setState(ProcMail.STATE_SENT_ERROR); if (pmail.getState() != (res.equals("0") ? ProcMail.STATE_SENT_ERROR: ProcMail.STATE_SENT)) { System.out.print(" <<< ERROR"); error = true; } System.out.print("\n"); } } assertFalse(error); } }
Add debug to investigate on JAMES-850 git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@681541 13f79535-47bb-0310-9956-ffa450edef68
trunk/mailets-function/src/test/java/org/apache/james/transport/remotedeliverytester/AbstractRemoteDeliveryTest.java
Add debug to investigate on JAMES-850
<ide><path>runk/mailets-function/src/test/java/org/apache/james/transport/remotedeliverytester/AbstractRemoteDeliveryTest.java <ide> import java.util.Properties; <ide> import java.util.Random; <ide> <add>import junit.framework.AssertionFailedError; <ide> import junit.framework.TestCase; <ide> <ide> public abstract class AbstractRemoteDeliveryTest extends TestCase { <ide> assertEquals(0, waitEmptySpool(10000)); <ide> <ide> // Checks <del> assertWhole(tester.getTestStatus(), 5, 4); <del> assertServer(tester.getTestStatus(), servers[0][1], 5, 4); <del> assertEquals(2, tester.getProcMails().size()); <del> assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); <del> assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); <add> try { <add> assertWhole(tester.getTestStatus(), 5, 4); <add> assertServer(tester.getTestStatus(), servers[0][1], 5, 4); <add> assertEquals(2, tester.getProcMails().size()); <add> assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 4, 1, servers[0][1]); <add> assertProcMail(mails.get("[email protected]"), ProcMail.STATE_SENT_ERROR, 1, 1, servers[0][1]); <add> } catch (AssertionFailedError e) { <add> // TEMPORARILY add a dump stack on failure to <add> // see if we have a deadlock (unlikely) or simply the <add> // notification is not working properly. (see JAMES-850) <add> Thread.dumpStack(); <add> throw e; <add> } <ide> } <ide> <ide> /**
Java
apache-2.0
269f73354c9af2d960a8f0f364f85b7d922e3a4d
0
uronce-cc/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,jsimsa/alluxio,aaudiber/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,wwjiang007/alluxio,apc999/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,maobaolong/alluxio,jswudi/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,apc999/alluxio,Reidddddd/alluxio,ShailShah/alluxio,bf8086/alluxio,madanadit/alluxio,WilliamZapata/alluxio,apc999/alluxio,Reidddddd/mo-alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,jsimsa/alluxio,PasaLab/tachyon,aaudiber/alluxio,bf8086/alluxio,jsimsa/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,apc999/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,madanadit/alluxio,riversand963/alluxio,ChangerYoung/alluxio,bf8086/alluxio,Alluxio/alluxio,jsimsa/alluxio,jswudi/alluxio,calvinjia/tachyon,PasaLab/tachyon,ShailShah/alluxio,yuluo-ding/alluxio,riversand963/alluxio,riversand963/alluxio,madanadit/alluxio,jsimsa/alluxio,jswudi/alluxio,Reidddddd/mo-alluxio,riversand963/alluxio,jsimsa/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,calvinjia/tachyon,Alluxio/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,calvinjia/tachyon,bf8086/alluxio,madanadit/alluxio,Reidddddd/alluxio,apc999/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,jswudi/alluxio,Reidddddd/alluxio,ChangerYoung/alluxio,apc999/alluxio,bf8086/alluxio,Reidddddd/alluxio,PasaLab/tachyon,bf8086/alluxio,Alluxio/alluxio,maobaolong/alluxio,apc999/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,ShailShah/alluxio,PasaLab/tachyon,madanadit/alluxio,uronce-cc/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,aaudiber/alluxio,ShailShah/alluxio,maobaolong/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,calvinjia/tachyon,maobaolong/alluxio,calvinjia/tachyon,madanadit/alluxio,riversand963/alluxio,yuluo-ding/alluxio,jswudi/alluxio,WilliamZapata/alluxio,madanadit/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,aaudiber/alluxio,Alluxio/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,aaudiber/alluxio,jswudi/alluxio,aaudiber/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,maboelhassan/alluxio,ShailShah/alluxio,uronce-cc/alluxio,PasaLab/tachyon,PasaLab/tachyon,maobaolong/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,Alluxio/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,calvinjia/tachyon
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.worker.block; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tachyon.Constants; import tachyon.Users; import tachyon.conf.TachyonConf; import tachyon.exception.InvalidStateException; import tachyon.exception.NotFoundException; import tachyon.master.MasterClient; import tachyon.thrift.BlockInfoException; import tachyon.thrift.Command; import tachyon.thrift.NetAddress; import tachyon.util.CommonUtils; import tachyon.util.network.NetworkAddressUtils; import tachyon.util.ThreadFactoryUtils; /** * Task that carries out the necessary block worker to master communications, including register and * heartbeat. This class manages its own {@link tachyon.master.MasterClient}. * * When running, this task first requests a block report from the * {@link tachyon.worker.block.BlockDataManager}, then sends it to the master. The master may * respond to the heartbeat with a command which will be executed. After which, the task will wait * for the elapsed time since its last heartbeat has reached the heartbeat interval. Then the cycle * will continue. * * If the task fails to heartbeat to the master, it will destroy its old master client and recreate * it before retrying. */ public class BlockMasterSync implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); /** The thread pool to remove block */ private static final int DEFAULT_BLOCK_REMOVER_POOL_SIZE = 10; /** Block data manager responsible for interacting with Tachyon and UFS storage */ private final BlockDataManager mBlockDataManager; /** The executor service for the master client thread */ private final ExecutorService mMasterClientExecutorService; /** The net address of the worker */ private final NetAddress mWorkerAddress; /** The configuration values */ private final TachyonConf mTachyonConf; /** Milliseconds between each heartbeat */ private final int mHeartbeatIntervalMs; /** Milliseconds between heartbeats before a timeout */ private final int mHeartbeatTimeoutMs; /** Client for all master communication */ private MasterClient mMasterClient; /** Flag to indicate if the sync should continue */ private volatile boolean mRunning; /** The id of the worker */ private long mWorkerId; private final ExecutorService mFixedExecutionService = Executors.newFixedThreadPool(DEFAULT_BLOCK_REMOVER_POOL_SIZE); BlockMasterSync(BlockDataManager blockDataManager, TachyonConf tachyonConf, NetAddress workerAddress) { mBlockDataManager = blockDataManager; mWorkerAddress = workerAddress; mTachyonConf = tachyonConf; mMasterClientExecutorService = Executors.newFixedThreadPool(1, ThreadFactoryUtils.build("worker-client-heartbeat-%d", true)); mMasterClient = new MasterClient(NetworkAddressUtils.getMasterAddress(mTachyonConf), mMasterClientExecutorService, mTachyonConf); mHeartbeatIntervalMs = mTachyonConf.getInt(Constants.WORKER_TO_MASTER_HEARTBEAT_INTERVAL_MS); mHeartbeatTimeoutMs = mTachyonConf.getInt(Constants.WORKER_HEARTBEAT_TIMEOUT_MS); mRunning = true; mWorkerId = 0; } /** * Gets the worker id, 0 if registerWithMaster has not been called successfully. * * @return the worker id */ public long getWorkerId() { return mWorkerId; } /** * Registers with the Tachyon master. This should be called before the continuous heartbeat thread * begins. The workerId will be set after this method is successful. * * @throws IOException if the registration fails */ public void registerWithMaster() throws IOException { BlockStoreMeta storeMeta = mBlockDataManager.getStoreMeta(); try { mWorkerId = mMasterClient.worker_register(mWorkerAddress, storeMeta.getCapacityBytesOnTiers(), storeMeta.getUsedBytesOnTiers(), storeMeta.getBlockList()); } catch (BlockInfoException bie) { LOG.error("Failed to register with master.", bie); throw new IOException(bie); } } /** * Main loop for the sync, continuously heartbeats to the master node about the change in the * worker's managed space. */ @Override public void run() { long lastHeartbeatMs = System.currentTimeMillis(); while (mRunning) { // Check the time since last heartbeat, and wait until it is within heartbeat interval long lastIntervalMs = System.currentTimeMillis() - lastHeartbeatMs; long toSleepMs = mHeartbeatIntervalMs - lastIntervalMs; if (toSleepMs > 0) { CommonUtils.sleepMs(LOG, toSleepMs); } else { LOG.warn("Heartbeat took: " + lastIntervalMs + ", expected: " + mHeartbeatIntervalMs); } // Prepare metadata for the next heartbeat BlockHeartbeatReport blockReport = mBlockDataManager.getReport(); BlockStoreMeta storeMeta = mBlockDataManager.getStoreMeta(); // Send the heartbeat and execute the response try { Command cmdFromMaster = mMasterClient.worker_heartbeat(mWorkerId, storeMeta.getUsedBytesOnTiers(), blockReport.getRemovedBlocks(), blockReport.getAddedBlocks()); lastHeartbeatMs = System.currentTimeMillis(); handleMasterCommand(cmdFromMaster); } catch (Exception ioe) { // An error occurred, retry after 1 second or error if heartbeat timeout is reached LOG.error("Failed to receive or execute master heartbeat command.", ioe); resetMasterClient(); CommonUtils.sleepMs(LOG, Constants.SECOND_MS); if (System.currentTimeMillis() - lastHeartbeatMs >= mHeartbeatTimeoutMs) { throw new RuntimeException("Master heartbeat timeout exceeded: " + mHeartbeatTimeoutMs); } } } } /** * Stops the sync, once this method is called, the object should be discarded */ public void stop() { mRunning = false; mMasterClient.close(); mMasterClientExecutorService.shutdown(); } /** * Handles a master command. The command is one of Unknown, Nothing, Register, Free, or Delete. * This call will block until the command is complete. * * @param cmd the command to execute. * @throws Exception if an error occurs when executing the command */ // TODO: Evaluate the necessity of each command // TODO: Do this in a non blocking way private void handleMasterCommand(Command cmd) throws Exception { if (cmd == null) { return; } switch (cmd.mCommandType) { // Currently unused case Delete: break; // Master requests blocks to be removed from Tachyon managed space. case Free: for (long block : cmd.mData) { mFixedExecutionService.execute(new BlockRemover(mBlockDataManager, Users.MASTER_COMMAND_USER_ID, block)); } break; // No action required case Nothing: break; // Master requests re-registration case Register: registerWithMaster(); break; // Unknown request case Unknown: LOG.error("Master heartbeat sends unknown command " + cmd); break; default: throw new RuntimeException("Un-recognized command from master " + cmd); } } /** * Closes and creates a new master client, in case the master changes. */ private void resetMasterClient() { mMasterClient.close(); mMasterClient = new MasterClient(NetworkAddressUtils.getMasterAddress(mTachyonConf), mMasterClientExecutorService, mTachyonConf); } /** * Thread to remove block from master */ private class BlockRemover implements Runnable { private BlockDataManager mBlockDataManager; private long mUserId; private long mBlockId; public BlockRemover(BlockDataManager blockDataManager, long userId, long blockId) { mBlockDataManager = blockDataManager; mUserId = userId; mBlockId = blockId; } @Override public void run() { try { mBlockDataManager.removeBlock(mUserId, mBlockId); } catch (IOException ioe) { LOG.warn("Failed master free block cmd for: " + mBlockId + " due to concurrent read."); } catch (InvalidStateException e) { LOG.warn("Failed master free block cmd for: " + mBlockId + " due to block uncommitted."); } catch (NotFoundException e) { LOG.warn("Failed master free block cmd for: " + mBlockId + " due to block not found."); } } } }
servers/src/main/java/tachyon/worker/block/BlockMasterSync.java
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.worker.block; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tachyon.Constants; import tachyon.Users; import tachyon.conf.TachyonConf; import tachyon.exception.InvalidStateException; import tachyon.exception.NotFoundException; import tachyon.master.MasterClient; import tachyon.thrift.BlockInfoException; import tachyon.thrift.Command; import tachyon.thrift.NetAddress; import tachyon.util.CommonUtils; import tachyon.util.network.NetworkAddressUtils; import tachyon.util.ThreadFactoryUtils; /** * Task that carries out the necessary block worker to master communications, including register and * heartbeat. This class manages its own {@link tachyon.master.MasterClient}. * * When running, this task first requests a block report from the * {@link tachyon.worker.block.BlockDataManager}, then sends it to the master. The master may * respond to the heartbeat with a command which will be executed. After which, the task will wait * for the elapsed time since its last heartbeat has reached the heartbeat interval. Then the cycle * will continue. * * If the task fails to heartbeat to the master, it will destroy its old master client and recreate * it before retrying. */ public class BlockMasterSync implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); /** Block data manager responsible for interacting with Tachyon and UFS storage */ private final BlockDataManager mBlockDataManager; /** The executor service for the master client thread */ private final ExecutorService mMasterClientExecutorService; /** The net address of the worker */ private final NetAddress mWorkerAddress; /** The configuration values */ private final TachyonConf mTachyonConf; /** Milliseconds between each heartbeat */ private final int mHeartbeatIntervalMs; /** Milliseconds between heartbeats before a timeout */ private final int mHeartbeatTimeoutMs; /** Client for all master communication */ private MasterClient mMasterClient; /** Flag to indicate if the sync should continue */ private volatile boolean mRunning; /** The id of the worker */ private long mWorkerId; /** The thread pool to remove block */ private static final int DEFAULT_BLOCK_REMOVER_POOL_SIZE = 10; private final ExecutorService mFixedExecutionService = Executors.newFixedThreadPool(DEFAULT_BLOCK_REMOVER_POOL_SIZE); BlockMasterSync(BlockDataManager blockDataManager, TachyonConf tachyonConf, NetAddress workerAddress) { mBlockDataManager = blockDataManager; mWorkerAddress = workerAddress; mTachyonConf = tachyonConf; mMasterClientExecutorService = Executors.newFixedThreadPool(1, ThreadFactoryUtils.build("worker-client-heartbeat-%d", true)); mMasterClient = new MasterClient(NetworkAddressUtils.getMasterAddress(mTachyonConf), mMasterClientExecutorService, mTachyonConf); mHeartbeatIntervalMs = mTachyonConf.getInt(Constants.WORKER_TO_MASTER_HEARTBEAT_INTERVAL_MS); mHeartbeatTimeoutMs = mTachyonConf.getInt(Constants.WORKER_HEARTBEAT_TIMEOUT_MS); mRunning = true; mWorkerId = 0; } /** * Gets the worker id, 0 if registerWithMaster has not been called successfully. * * @return the worker id */ public long getWorkerId() { return mWorkerId; } /** * Registers with the Tachyon master. This should be called before the continuous heartbeat thread * begins. The workerId will be set after this method is successful. * * @throws IOException if the registration fails */ public void registerWithMaster() throws IOException { BlockStoreMeta storeMeta = mBlockDataManager.getStoreMeta(); try { mWorkerId = mMasterClient.worker_register(mWorkerAddress, storeMeta.getCapacityBytesOnTiers(), storeMeta.getUsedBytesOnTiers(), storeMeta.getBlockList()); } catch (BlockInfoException bie) { LOG.error("Failed to register with master.", bie); throw new IOException(bie); } } /** * Main loop for the sync, continuously heartbeats to the master node about the change in the * worker's managed space. */ @Override public void run() { long lastHeartbeatMs = System.currentTimeMillis(); while (mRunning) { // Check the time since last heartbeat, and wait until it is within heartbeat interval long lastIntervalMs = System.currentTimeMillis() - lastHeartbeatMs; long toSleepMs = mHeartbeatIntervalMs - lastIntervalMs; if (toSleepMs > 0) { CommonUtils.sleepMs(LOG, toSleepMs); } else { LOG.warn("Heartbeat took: " + lastIntervalMs + ", expected: " + mHeartbeatIntervalMs); } // Prepare metadata for the next heartbeat BlockHeartbeatReport blockReport = mBlockDataManager.getReport(); BlockStoreMeta storeMeta = mBlockDataManager.getStoreMeta(); // Send the heartbeat and execute the response try { Command cmdFromMaster = mMasterClient.worker_heartbeat(mWorkerId, storeMeta.getUsedBytesOnTiers(), blockReport.getRemovedBlocks(), blockReport.getAddedBlocks()); lastHeartbeatMs = System.currentTimeMillis(); handleMasterCommand(cmdFromMaster); } catch (Exception ioe) { // An error occurred, retry after 1 second or error if heartbeat timeout is reached LOG.error("Failed to receive or execute master heartbeat command.", ioe); resetMasterClient(); CommonUtils.sleepMs(LOG, Constants.SECOND_MS); if (System.currentTimeMillis() - lastHeartbeatMs >= mHeartbeatTimeoutMs) { throw new RuntimeException("Master heartbeat timeout exceeded: " + mHeartbeatTimeoutMs); } } } } /** * Stops the sync, once this method is called, the object should be discarded */ public void stop() { mRunning = false; mMasterClient.close(); mMasterClientExecutorService.shutdown(); } /** * Handles a master command. The command is one of Unknown, Nothing, Register, Free, or Delete. * This call will block until the command is complete. * * @param cmd the command to execute. * @throws Exception if an error occurs when executing the command */ // TODO: Evaluate the necessity of each command // TODO: Do this in a non blocking way private void handleMasterCommand(Command cmd) throws Exception { if (cmd == null) { return; } switch (cmd.mCommandType) { // Currently unused case Delete: break; // Master requests blocks to be removed from Tachyon managed space. case Free: for (long block : cmd.mData) { mFixedExecutionService.execute(new BlockRemover(mBlockDataManager, Users.MASTER_COMMAND_USER_ID, block)); } break; // No action required case Nothing: break; // Master requests re-registration case Register: registerWithMaster(); break; // Unknown request case Unknown: LOG.error("Master heartbeat sends unknown command " + cmd); break; default: throw new RuntimeException("Un-recognized command from master " + cmd); } } /** * Closes and creates a new master client, in case the master changes. */ private void resetMasterClient() { mMasterClient.close(); mMasterClient = new MasterClient(NetworkAddressUtils.getMasterAddress(mTachyonConf), mMasterClientExecutorService, mTachyonConf); } /** * Thread to remove block from master */ private class BlockRemover implements Runnable { private BlockDataManager mBlockDataManager; private long mUserId; private long mBlockId; public BlockRemover(BlockDataManager blockDataManager, long userId, long blockId) { mBlockDataManager = blockDataManager; mUserId = userId; mBlockId = blockId; } @Override public void run() { try { mBlockDataManager.removeBlock(mUserId, mBlockId); } catch (IOException ioe) { LOG.warn("Failed master free block cmd for: " + mBlockId + " due to concurrent read."); } catch (InvalidStateException e) { LOG.warn("Failed master free block cmd for: " + mBlockId + " due to block uncommitted."); } catch (NotFoundException e) { LOG.warn("Failed master free block cmd for: " + mBlockId + " due to block not found."); } } } }
[TACHYON-784] Reorder variable declarations in tachyon.worker.block.BlockMasterSync
servers/src/main/java/tachyon/worker/block/BlockMasterSync.java
[TACHYON-784] Reorder variable declarations in tachyon.worker.block.BlockMasterSync
<ide><path>ervers/src/main/java/tachyon/worker/block/BlockMasterSync.java <ide> */ <ide> public class BlockMasterSync implements Runnable { <ide> private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); <del> <add> /** The thread pool to remove block */ <add> private static final int DEFAULT_BLOCK_REMOVER_POOL_SIZE = 10; <ide> /** Block data manager responsible for interacting with Tachyon and UFS storage */ <ide> private final BlockDataManager mBlockDataManager; <ide> /** The executor service for the master client thread */ <ide> private volatile boolean mRunning; <ide> /** The id of the worker */ <ide> private long mWorkerId; <del> /** The thread pool to remove block */ <del> private static final int DEFAULT_BLOCK_REMOVER_POOL_SIZE = 10; <ide> private final ExecutorService mFixedExecutionService = <ide> Executors.newFixedThreadPool(DEFAULT_BLOCK_REMOVER_POOL_SIZE); <ide>
Java
mit
3eadd4dd640bceb29ddf233ea19d453f472cf0cd
0
dafi/photoshelf
package com.ternaryop.photoshelf.birthday; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.ternaryop.photoshelf.R; import com.ternaryop.photoshelf.activity.BirthdaysPublisherActivity; import com.ternaryop.photoshelf.db.Birthday; import com.ternaryop.photoshelf.db.BirthdayDAO; import com.ternaryop.photoshelf.db.DBHelper; import com.ternaryop.photoshelf.db.PostTag; import com.ternaryop.photoshelf.db.PostTagDAO; import com.ternaryop.tumblr.Tumblr; import com.ternaryop.tumblr.TumblrPhotoPost; import com.ternaryop.utils.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class BirthdayUtils { private static final String BIRTHDAY_NOTIFICATION_TAG = "com.ternaryop.photoshelf.bday"; private static final int BIRTHDAY_NOTIFICATION_ID = 1; public static final String DESKTOP_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0"; public static boolean notifyBirthday(Context context) { BirthdayDAO birthdayDatabaseHelper = DBHelper .getInstance(context.getApplicationContext()) .getBirthdayDAO(); Calendar now = Calendar.getInstance(Locale.US); List<Birthday> list = birthdayDatabaseHelper.getBirthdayByDate(now.getTime()); if (list.isEmpty()) { return false; } int currYear = now.get(Calendar.YEAR); NotificationCompat.Builder builder = new NotificationCompat.Builder( context.getApplicationContext()) .setContentIntent(createPendingIntent(context)) .setSmallIcon(R.drawable.stat_notify_bday); if (list.size() == 1) { Birthday birthday = list.get(0); builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size())); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(birthday.getBirthDate()); int years = currYear - cal.get(Calendar.YEAR); builder.setContentText(context.getString(R.string.birthday_years_old, birthday.getName(), years)); } else { builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size(), list.size())); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(context.getString(R.string.birthday_notification_title)); for (Birthday birthday : list) { Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(birthday.getBirthDate()); int years = currYear - cal.get(Calendar.YEAR); inboxStyle.addLine(context.getString(R.string.birthday_years_old, birthday.getName(), years)); } builder.setStyle(inboxStyle); } // remove notification when user clicks on it builder.setAutoCancel(true); Notification notification = builder.build(); NotificationManager notificationManager = (NotificationManager)context.getApplicationContext() .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(BIRTHDAY_NOTIFICATION_TAG, BIRTHDAY_NOTIFICATION_ID, notification); return true; } private static PendingIntent createPendingIntent(Context context) { // Define Activity to start Intent resultIntent = new Intent(context, BirthdaysPublisherActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack stackBuilder.addParentStack(BirthdaysPublisherActivity.class); // Adds the Intent to the top of the stack stackBuilder.addNextIntent(resultIntent); // Gets a PendingIntent containing the entire back stack PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); return resultPendingIntent; } public static List<TumblrPhotoPost> getPhotoPosts(final Context context, Calendar birthDate) { DBHelper dbHelper = DBHelper .getInstance(context.getApplicationContext()); List<Birthday> birthDays = dbHelper .getBirthdayDAO() .getBirthdayByDate(birthDate.getTime()); ArrayList<TumblrPhotoPost> posts = new ArrayList<TumblrPhotoPost>(); PostTagDAO postTagDAO = dbHelper.getPostTagDAO(); Map<String, String> params = new HashMap<String, String>(2); params.put("type", "photo"); for (Birthday b : birthDays) { PostTag postTag = postTagDAO.getRandomPostByTag(b.getName(), b.getTumblrName()); if (postTag != null) { params.put("id", String.valueOf(postTag.getId())); TumblrPhotoPost post = (TumblrPhotoPost)Tumblr.getSharedTumblr(context) .getPublicPosts(b.getTumblrName(), params).get(0); posts.add(post); } } return posts; } public static void publishedInAgeRange(Context context, int fromAge, int toAge, int daysPeriod, String postTags, String tumblrName) { if (fromAge != 0 && toAge != 0) { throw new IllegalArgumentException("fromAge or toAge can't be both set to 0"); } String message; if (fromAge == 0) { message = context.getString(R.string.week_selection_under_age, toAge); } else if (toAge == 0) { message = context.getString(R.string.week_selection_over_age, fromAge); } else { throw new IllegalArgumentException("fromAge or toAge are both greater than 0"); } final int THUMBS_COUNT = 9; DBHelper dbHelper = DBHelper.getInstance(context); List<Map<String, String>> birthdays = dbHelper.getBirthdayDAO() .getBirthdayByAgeRange(fromAge, toAge == 0 ? Integer.MAX_VALUE : toAge, daysPeriod, tumblrName); Collections.shuffle(birthdays); StringBuilder sb = new StringBuilder(); Map<String, String> params = new HashMap<String, String>(2); TumblrPhotoPost post = null; params.put("type", "photo"); int count = 0; for (Map<String, String> info : birthdays) { params.put("id", info.get("postId")); post = (TumblrPhotoPost)Tumblr.getSharedTumblr(context) .getPublicPosts(tumblrName, params).get(0); String imageUrl = post.getClosestPhotoByWidth(250).getUrl(); sb.append("<a href=\"" + post.getPostUrl() + "\">"); sb.append("<p>" + context.getString(R.string.name_with_age, post.getTags().get(0), info.get("age")) + "</p>"); sb.append("<img style=\"width: 250px !important\" src=\"" + imageUrl + "\"/>"); sb.append("</a>"); sb.append("<br/>"); if (++count > THUMBS_COUNT) { break; } } if (post != null) { message = message + " (" + formatPeriodDate(-daysPeriod) + ")"; Tumblr.getSharedTumblr(context) .draftTextPost(tumblrName, message, sb.toString(), postTags); } } private static String formatPeriodDate(int daysPeriod) { Calendar now = Calendar.getInstance(); Calendar period = Calendar.getInstance(); period.add(Calendar.DAY_OF_MONTH, daysPeriod); SimpleDateFormat sdf = new SimpleDateFormat("MMMM", Locale.US); if (now.get(Calendar.YEAR) == period.get(Calendar.YEAR)) { if (now.get(Calendar.MONTH) == period.get(Calendar.MONTH)) { return period.get(Calendar.DAY_OF_MONTH) + "-" + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + ", " + now.get(Calendar.YEAR); } return period.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(period.getTime()) + " - " + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + ", " + now.get(Calendar.YEAR); } return period.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(period.getTime()) + " " + period.get(Calendar.YEAR) + " - " + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + " " + now.get(Calendar.YEAR); } public static Birthday searchGoogleForBirthday(String name, String blogName) throws IOException, ParseException { String cleanName = name .replaceAll(" ", "+") .replaceAll("\"", ""); String url = "https://www.google.com/search?hl=en&q=" + cleanName; String text = Jsoup.connect(url) .userAgent(DESKTOP_USER_AGENT) .get() .text(); // match only dates in expected format (ie. "Born: month_name day, year") Pattern pattern = Pattern.compile("Born: ([a-zA-Z]+ \\d{1,2}, \\d{4})"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { String textDate = matcher.group(1); SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.US); Date date = dateFormat.parse(textDate); return new Birthday(name, date, blogName); } return null; } public static Birthday searchWikipediaForBirthday(String name, String blogName) throws IOException, ParseException { String cleanName = StringUtils .capitalize(name) .replaceAll(" ", "_") .replaceAll("\"", ""); String url = "http://en.wikipedia.org/wiki/" + cleanName; Document document = Jsoup.connect(url) .userAgent(DESKTOP_USER_AGENT) .get(); // protect against redirect if (document.title().toLowerCase(Locale.US).contains(name)) { Elements el = document.select(".bday"); if (el.size() > 0) { String birthDate = el.get(0).text(); return new Birthday(name, birthDate, blogName); } } return null; } public static Birthday searchBirthday(String name, String blogName) { Birthday birthday = null; try { birthday = BirthdayUtils.searchGoogleForBirthday(name, blogName); } catch (Exception ex) { } if (birthday == null) { try { birthday = BirthdayUtils.searchWikipediaForBirthday(name, blogName); } catch (Exception ex) { } } return birthday; } }
app/src/com/ternaryop/photoshelf/birthday/BirthdayUtils.java
package com.ternaryop.photoshelf.birthday; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.ternaryop.photoshelf.R; import com.ternaryop.photoshelf.activity.BirthdaysPublisherActivity; import com.ternaryop.photoshelf.db.Birthday; import com.ternaryop.photoshelf.db.BirthdayDAO; import com.ternaryop.photoshelf.db.DBHelper; import com.ternaryop.photoshelf.db.PostTag; import com.ternaryop.photoshelf.db.PostTagDAO; import com.ternaryop.tumblr.Tumblr; import com.ternaryop.tumblr.TumblrPhotoPost; import com.ternaryop.utils.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class BirthdayUtils { private static final String BIRTHDAY_NOTIFICATION_TAG = "com.ternaryop.photoshelf.bday"; private static final int BIRTHDAY_NOTIFICATION_ID = 1; public static boolean notifyBirthday(Context context) { BirthdayDAO birthdayDatabaseHelper = DBHelper .getInstance(context.getApplicationContext()) .getBirthdayDAO(); Calendar now = Calendar.getInstance(Locale.US); List<Birthday> list = birthdayDatabaseHelper.getBirthdayByDate(now.getTime()); if (list.isEmpty()) { return false; } long currYear = now.get(Calendar.YEAR); NotificationCompat.Builder builder = new NotificationCompat.Builder( context.getApplicationContext()) .setContentIntent(createPendingIntent(context)) .setSmallIcon(R.drawable.stat_notify_bday); if (list.size() == 1) { Birthday birthday = list.get(0); builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size())); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(birthday.getBirthDate()); long years = currYear - cal.get(Calendar.YEAR); builder.setContentText(context.getString(R.string.birthday_years_old, birthday.getName(), years)); } else { builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size(), list.size())); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(context.getString(R.string.birthday_notification_title)); for (Birthday birthday : list) { Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(birthday.getBirthDate()); long years = currYear - cal.get(Calendar.YEAR); inboxStyle.addLine(context.getString(R.string.birthday_years_old, birthday.getName(), years)); } builder.setStyle(inboxStyle); } // remove notification when user clicks on it builder.setAutoCancel(true); Notification notification = builder.build(); NotificationManager notificationManager = (NotificationManager)context.getApplicationContext() .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(BIRTHDAY_NOTIFICATION_TAG, BIRTHDAY_NOTIFICATION_ID, notification); return true; } private static PendingIntent createPendingIntent(Context context) { // Define Activity to start Intent resultIntent = new Intent(context, BirthdaysPublisherActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack stackBuilder.addParentStack(BirthdaysPublisherActivity.class); // Adds the Intent to the top of the stack stackBuilder.addNextIntent(resultIntent); // Gets a PendingIntent containing the entire back stack PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); return resultPendingIntent; } public static List<TumblrPhotoPost> getPhotoPosts(final Context context, Calendar birthDate) { DBHelper dbHelper = DBHelper .getInstance(context.getApplicationContext()); List<Birthday> birthDays = dbHelper .getBirthdayDAO() .getBirthdayByDate(birthDate.getTime()); ArrayList<TumblrPhotoPost> posts = new ArrayList<TumblrPhotoPost>(); PostTagDAO postTagDAO = dbHelper.getPostTagDAO(); Map<String, String> params = new HashMap<String, String>(2); params.put("type", "photo"); for (Birthday b : birthDays) { PostTag postTag = postTagDAO.getRandomPostByTag(b.getName(), b.getTumblrName()); if (postTag != null) { params.put("id", String.valueOf(postTag.getId())); TumblrPhotoPost post = (TumblrPhotoPost)Tumblr.getSharedTumblr(context) .getPublicPosts(b.getTumblrName(), params).get(0); posts.add(post); } } return posts; } public static void publishedInAgeRange(Context context, int fromAge, int toAge, int daysPeriod, String postTags, String tumblrName) { if (fromAge != 0 && toAge != 0) { throw new IllegalArgumentException("fromAge or toAge can't be both set to 0"); } String message; if (fromAge == 0) { message = context.getString(R.string.week_selection_under_age, toAge); } else if (toAge == 0) { message = context.getString(R.string.week_selection_over_age, fromAge); } else { throw new IllegalArgumentException("fromAge or toAge are both greater than 0"); } final int THUMBS_COUNT = 9; DBHelper dbHelper = DBHelper.getInstance(context); List<Map<String, String>> birthdays = dbHelper.getBirthdayDAO() .getBirthdayByAgeRange(fromAge, toAge == 0 ? Integer.MAX_VALUE : toAge, daysPeriod, tumblrName); Collections.shuffle(birthdays); StringBuilder sb = new StringBuilder(); Map<String, String> params = new HashMap<String, String>(2); TumblrPhotoPost post = null; params.put("type", "photo"); int count = 0; for (Map<String, String> info : birthdays) { params.put("id", info.get("postId")); post = (TumblrPhotoPost)Tumblr.getSharedTumblr(context) .getPublicPosts(tumblrName, params).get(0); String imageUrl = post.getClosestPhotoByWidth(250).getUrl(); sb.append("<a href=\"" + post.getPostUrl() + "\">"); sb.append("<p>" + context.getString(R.string.name_with_age, post.getTags().get(0), info.get("age")) + "</p>"); sb.append("<img style=\"width: 250px !important\" src=\"" + imageUrl + "\"/>"); sb.append("</a>"); sb.append("<br/>"); if (++count > THUMBS_COUNT) { break; } } if (post != null) { message = message + " (" + formatPeriodDate(-daysPeriod) + ")"; Tumblr.getSharedTumblr(context) .draftTextPost(tumblrName, message, sb.toString(), postTags); } } private static String formatPeriodDate(int daysPeriod) { Calendar now = Calendar.getInstance(); Calendar period = Calendar.getInstance(); period.add(Calendar.DAY_OF_MONTH, daysPeriod); SimpleDateFormat sdf = new SimpleDateFormat("MMMM", Locale.US); if (now.get(Calendar.YEAR) == period.get(Calendar.YEAR)) { if (now.get(Calendar.MONTH) == period.get(Calendar.MONTH)) { return period.get(Calendar.DAY_OF_MONTH) + "-" + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + ", " + now.get(Calendar.YEAR); } return period.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(period.getTime()) + " - " + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + ", " + now.get(Calendar.YEAR); } return period.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(period.getTime()) + " " + period.get(Calendar.YEAR) + " - " + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + " " + now.get(Calendar.YEAR); } public static Birthday searchGoogleForBirthday(String name, String blogName) throws IOException, ParseException { String cleanName = name .replaceAll(" ", "+") .replaceAll("\"", ""); String url = "https://www.google.com/search?hl=en&q=" + cleanName; String text = Jsoup.connect(url) .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0") .get() .text(); // match only dates in expected format (ie. "Born: month_name day, year") Pattern pattern = Pattern.compile("Born: ([a-zA-Z]+ \\d{1,2}, \\d{4})"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { String textDate = matcher.group(1); SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.US); Date date = dateFormat.parse(textDate); return new Birthday(name, date, blogName); } return null; } public static Birthday searchWikipediaForBirthday(String name, String blogName) throws IOException, ParseException { String cleanName = StringUtils .capitalize(name) .replaceAll(" ", "_") .replaceAll("\"", ""); String url = "http://en.wikipedia.org/wiki/" + cleanName; Document document = Jsoup.connect(url).get(); // protect against redirect if (document.title().toLowerCase(Locale.US).contains(name)) { Elements el = document.select(".bday"); if (el.size() > 0) { String birthDate = el.get(0).text(); return new Birthday(name, birthDate, blogName); } } return null; } public static Birthday searchBirthday(String name, String blogName) throws IOException, ParseException { Birthday birthday = BirthdayUtils.searchGoogleForBirthday(name, blogName); if (birthday == null) { birthday = BirthdayUtils.searchWikipediaForBirthday(name, blogName); } return birthday; } }
Ignore errors generated from search searchBirthday
app/src/com/ternaryop/photoshelf/birthday/BirthdayUtils.java
Ignore errors generated from search searchBirthday
<ide><path>pp/src/com/ternaryop/photoshelf/birthday/BirthdayUtils.java <ide> import org.jsoup.select.Elements; <ide> <ide> public class BirthdayUtils { <del> private static final String BIRTHDAY_NOTIFICATION_TAG = "com.ternaryop.photoshelf.bday"; <add> private static final String BIRTHDAY_NOTIFICATION_TAG = "com.ternaryop.photoshelf.bday"; <ide> private static final int BIRTHDAY_NOTIFICATION_ID = 1; <del> <del> public static boolean notifyBirthday(Context context) { <add> public static final String DESKTOP_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0"; <add> <add> public static boolean notifyBirthday(Context context) { <ide> BirthdayDAO birthdayDatabaseHelper = DBHelper <ide> .getInstance(context.getApplicationContext()) <ide> .getBirthdayDAO(); <ide> return false; <ide> } <ide> <del> long currYear = now.get(Calendar.YEAR); <add> int currYear = now.get(Calendar.YEAR); <ide> NotificationCompat.Builder builder = new NotificationCompat.Builder( <ide> context.getApplicationContext()) <ide> .setContentIntent(createPendingIntent(context)) <ide> builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size())); <ide> Calendar cal = Calendar.getInstance(Locale.US); <ide> cal.setTime(birthday.getBirthDate()); <del> long years = currYear - cal.get(Calendar.YEAR); <add> int years = currYear - cal.get(Calendar.YEAR); <ide> builder.setContentText(context.getString(R.string.birthday_years_old, birthday.getName(), years)); <ide> } else { <ide> builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size(), list.size())); <ide> for (Birthday birthday : list) { <ide> Calendar cal = Calendar.getInstance(Locale.US); <ide> cal.setTime(birthday.getBirthDate()); <del> long years = currYear - cal.get(Calendar.YEAR); <add> int years = currYear - cal.get(Calendar.YEAR); <ide> inboxStyle.addLine(context.getString(R.string.birthday_years_old, birthday.getName(), years)); <ide> } <ide> builder.setStyle(inboxStyle); <ide> .replaceAll("\"", ""); <ide> String url = "https://www.google.com/search?hl=en&q=" + cleanName; <ide> String text = Jsoup.connect(url) <del> .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0") <add> .userAgent(DESKTOP_USER_AGENT) <ide> .get() <ide> .text(); <ide> // match only dates in expected format (ie. "Born: month_name day, year") <ide> .replaceAll(" ", "_") <ide> .replaceAll("\"", ""); <ide> String url = "http://en.wikipedia.org/wiki/" + cleanName; <del> Document document = Jsoup.connect(url).get(); <add> Document document = Jsoup.connect(url) <add> .userAgent(DESKTOP_USER_AGENT) <add> .get(); <ide> // protect against redirect <ide> if (document.title().toLowerCase(Locale.US).contains(name)) { <ide> Elements el = document.select(".bday"); <ide> return null; <ide> } <ide> <del> public static Birthday searchBirthday(String name, String blogName) throws IOException, ParseException { <del> Birthday birthday = BirthdayUtils.searchGoogleForBirthday(name, blogName); <add> public static Birthday searchBirthday(String name, String blogName) { <add> Birthday birthday = null; <add> <add> try { <add> birthday = BirthdayUtils.searchGoogleForBirthday(name, blogName); <add> } catch (Exception ex) { <add> } <ide> if (birthday == null) { <del> birthday = BirthdayUtils.searchWikipediaForBirthday(name, blogName); <add> try { <add> birthday = BirthdayUtils.searchWikipediaForBirthday(name, blogName); <add> } catch (Exception ex) { <add> } <ide> } <ide> return birthday; <ide> }
Java
apache-2.0
f03c51d04aac543cd503e2d292b1998f387d3180
0
azkaban/azkaban,HappyRay/azkaban,azkaban/azkaban,HappyRay/azkaban,HappyRay/azkaban,azkaban/azkaban,chengren311/azkaban,chengren311/azkaban,azkaban/azkaban,chengren311/azkaban,HappyRay/azkaban,azkaban/azkaban,HappyRay/azkaban,chengren311/azkaban,HappyRay/azkaban,azkaban/azkaban,chengren311/azkaban
/* * Copyright 2017 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package azkaban.execapp; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import azkaban.executor.ExecutableFlow; import azkaban.project.ProjectFileHandler; import azkaban.storage.StorageManager; import azkaban.utils.FileIOUtils; import azkaban.utils.Pair; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class FlowPreparerTest { public static final String SAMPLE_FLOW_01 = "sample_flow_01"; final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private File executionsDir; private File projectsDir; private FlowPreparer instance; private StorageManager createMockStorageManager() { final ClassLoader classLoader = getClass().getClassLoader(); final File file = new File(classLoader.getResource(SAMPLE_FLOW_01 + ".zip").getFile()); final ProjectFileHandler projectFileHandler = mock(ProjectFileHandler.class); when(projectFileHandler.getFileType()).thenReturn("zip"); when(projectFileHandler.getLocalFile()).thenReturn(file); final StorageManager storageManager = mock(StorageManager.class); when(storageManager.getProjectFile(anyInt(), anyInt())).thenReturn(projectFileHandler); return storageManager; } @Before public void setUp() throws Exception { this.executionsDir = this.temporaryFolder.newFolder("executions"); this.projectsDir = this.temporaryFolder.newFolder("projects"); this.instance = spy( new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, this.installedProjects, null)); doNothing().when(this.instance).touchIfExists(any()); } @Test public void testSetupProject() throws Exception { final ProjectVersion pv = new ProjectVersion(12, 34, new File(this.projectsDir, "sample_project_01")); this.instance.setupProject(pv); final long actualDirSize = 1048835; assertThat(pv.getDirSizeInBytes()).isEqualTo(actualDirSize); assertThat(FileIOUtils.readNumberFromFile( Paths.get(pv.getInstalledDir().getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME))) .isEqualTo(actualDirSize); assertTrue(pv.getInstalledDir().exists()); assertTrue(new File(pv.getInstalledDir(), "sample_flow_01").exists()); } @Test public void testSetupProjectTouchesTheDirSizeFile() throws Exception { //verifies setup project touches project dir size file. final ProjectVersion pv = new ProjectVersion(12, 34, new File(this.projectsDir, "sample_project_01")); //setup project 1st time will not do touch this.instance.setupProject(pv); verify(this.instance, never()).touchIfExists( Paths.get(pv.getInstalledDir().getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME)); this.instance.setupProject(pv); verify(this.instance).touchIfExists( Paths.get(pv.getInstalledDir().getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME)); } @Test public void testSetupFlow() throws Exception { final ExecutableFlow executableFlow = mock(ExecutableFlow.class); when(executableFlow.getExecutionId()).thenReturn(12345); when(executableFlow.getProjectId()).thenReturn(12); when(executableFlow.getVersion()).thenReturn(34); this.instance.setup(executableFlow); final File execDir = new File(this.executionsDir, "12345"); assertTrue(execDir.exists()); assertTrue(new File(execDir, SAMPLE_FLOW_01).exists()); } @Test public void testProjectCacheDirCleanerNotEnabled() throws IOException { final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); //given final FlowPreparer flowPreparer = new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, installedProjects, null); //when final List<File> expectedRemainingFiles = new ArrayList<>(); for (int i = 1; i <= 3; i++) { final int projectId = i; final int version = 1; final ProjectVersion pv = new ProjectVersion(projectId, version, null); installedProjects.put(new Pair<>(projectId, version), pv); flowPreparer.setupProject(pv); expectedRemainingFiles.add(pv.getInstalledDir()); } //then assertThat(this.projectsDir.listFiles()).containsExactlyInAnyOrder(expectedRemainingFiles .toArray(new File[expectedRemainingFiles.size()])); } @Test public void testProjectCacheDirCleaner() throws IOException, InterruptedException { final Long projectDirMaxSize = 3L; final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); //given final FlowPreparer flowPreparer = new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, installedProjects, projectDirMaxSize); //when final List<File> expectedRemainingFiles = new ArrayList<>(); for (int i = 1; i <= 3; i++) { final int projectId = i; final int version = 1; final ProjectVersion pv = new ProjectVersion(projectId, version, null); flowPreparer.setupProject(pv); if (i >= 2) { //the first file will be deleted expectedRemainingFiles.add(pv.getInstalledDir()); } // last modified time of millis second granularity of a file is not supported by all file // systems, so sleep for 1 second between creation of each project dir to make their last // modified time different. Thread.sleep(1000); } //then assertThat(this.projectsDir.listFiles()).containsExactlyInAnyOrder(expectedRemainingFiles .toArray(new File[expectedRemainingFiles.size()])); } }
azkaban-exec-server/src/test/java/azkaban/execapp/FlowPreparerTest.java
/* * Copyright 2017 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package azkaban.execapp; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import azkaban.executor.ExecutableFlow; import azkaban.project.ProjectFileHandler; import azkaban.storage.StorageManager; import azkaban.utils.FileIOUtils; import azkaban.utils.Pair; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FlowPreparerTest { public static final String SAMPLE_FLOW_01 = "sample_flow_01"; final File executionsDir = new File("executions"); final File projectsDir = new File("projects"); final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); private FlowPreparer instance; private StorageManager createMockStorageManager() { final ClassLoader classLoader = getClass().getClassLoader(); final File file = new File(classLoader.getResource(SAMPLE_FLOW_01 + ".zip").getFile()); final ProjectFileHandler projectFileHandler = mock(ProjectFileHandler.class); when(projectFileHandler.getFileType()).thenReturn("zip"); when(projectFileHandler.getLocalFile()).thenReturn(file); final StorageManager storageManager = mock(StorageManager.class); when(storageManager.getProjectFile(anyInt(), anyInt())).thenReturn(projectFileHandler); return storageManager; } @Before public void setUp() throws Exception { tearDown(); this.executionsDir.mkdirs(); this.projectsDir.mkdirs(); this.instance = spy( new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, this.installedProjects, null)); doNothing().when(this.instance).touchIfExists(any()); } @After public void tearDown() throws Exception { FileUtils.deleteDirectory(this.executionsDir); FileUtils.deleteDirectory(this.projectsDir); } @Test public void testSetupProject() throws Exception { final ProjectVersion pv = new ProjectVersion(12, 34, new File(this.projectsDir, "sample_project_01")); this.instance.setupProject(pv); final long actualDirSize = 1048835; assertThat(pv.getDirSizeInBytes()).isEqualTo(actualDirSize); assertThat(FileIOUtils.readNumberFromFile( Paths.get(pv.getInstalledDir().getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME))) .isEqualTo(actualDirSize); assertTrue(pv.getInstalledDir().exists()); assertTrue(new File(pv.getInstalledDir(), "sample_flow_01").exists()); } @Test public void testSetupProjectTouchesTheDirSizeFile() throws Exception { //verifies setup project touches project dir size file. final ProjectVersion pv = new ProjectVersion(12, 34, new File(this.projectsDir, "sample_project_01")); //setup project 1st time will not do touch this.instance.setupProject(pv); verify(this.instance, never()).touchIfExists( Paths.get(pv.getInstalledDir().getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME)); this.instance.setupProject(pv); verify(this.instance).touchIfExists( Paths.get(pv.getInstalledDir().getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME)); } @Test public void testSetupFlow() throws Exception { final ExecutableFlow executableFlow = mock(ExecutableFlow.class); when(executableFlow.getExecutionId()).thenReturn(12345); when(executableFlow.getProjectId()).thenReturn(12); when(executableFlow.getVersion()).thenReturn(34); this.instance.setup(executableFlow); final File execDir = new File(this.executionsDir, "12345"); assertTrue(execDir.exists()); assertTrue(new File(execDir, SAMPLE_FLOW_01).exists()); } @Test public void testProjectCacheDirCleanerNotEnabled() throws IOException { final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); //given final FlowPreparer flowPreparer = new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, installedProjects, null); //when final List<File> expectedRemainingFiles = new ArrayList<>(); for (int i = 1; i <= 3; i++) { final int projectId = i; final int version = 1; final ProjectVersion pv = new ProjectVersion(projectId, version, null); installedProjects.put(new Pair<>(projectId, version), pv); flowPreparer.setupProject(pv); expectedRemainingFiles.add(pv.getInstalledDir()); } //then assertThat(this.projectsDir.listFiles()).containsExactlyInAnyOrder(expectedRemainingFiles .toArray(new File[expectedRemainingFiles.size()])); } @Test public void testProjectCacheDirCleaner() throws IOException, InterruptedException { final Long projectDirMaxSize = 3L; final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); //given final FlowPreparer flowPreparer = new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, installedProjects, projectDirMaxSize); //when final List<File> expectedRemainingFiles = new ArrayList<>(); for (int i = 1; i <= 3; i++) { final int projectId = i; final int version = 1; final ProjectVersion pv = new ProjectVersion(projectId, version, null); flowPreparer.setupProject(pv); if (i >= 2) { //the first file will be deleted expectedRemainingFiles.add(pv.getInstalledDir()); } // last modified time of millis second granularity of a file is not supported by all file // systems, so sleep for 1 second between creation of each project dir to make their last // modified time different. Thread.sleep(1000); } //then assertThat(this.projectsDir.listFiles()).containsExactlyInAnyOrder(expectedRemainingFiles .toArray(new File[expectedRemainingFiles.size()])); } }
FlowPreparerTest to use @Rule TemporaryFolder (#1903)
azkaban-exec-server/src/test/java/azkaban/execapp/FlowPreparerTest.java
FlowPreparerTest to use @Rule TemporaryFolder (#1903)
<ide><path>zkaban-exec-server/src/test/java/azkaban/execapp/FlowPreparerTest.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <del>import org.apache.commons.io.FileUtils; <del>import org.junit.After; <ide> import org.junit.Before; <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.TemporaryFolder; <ide> <ide> <ide> public class FlowPreparerTest { <ide> <ide> public static final String SAMPLE_FLOW_01 = "sample_flow_01"; <del> <del> final File executionsDir = new File("executions"); <del> final File projectsDir = new File("projects"); <ide> final Map<Pair<Integer, Integer>, ProjectVersion> installedProjects = new HashMap<>(); <del> <add> @Rule <add> public TemporaryFolder temporaryFolder = new TemporaryFolder(); <add> private File executionsDir; <add> private File projectsDir; <ide> private FlowPreparer instance; <ide> <ide> private StorageManager createMockStorageManager() { <ide> <ide> @Before <ide> public void setUp() throws Exception { <del> tearDown(); <del> <del> this.executionsDir.mkdirs(); <del> this.projectsDir.mkdirs(); <add> this.executionsDir = this.temporaryFolder.newFolder("executions"); <add> this.projectsDir = this.temporaryFolder.newFolder("projects"); <ide> <ide> this.instance = spy( <ide> new FlowPreparer(createMockStorageManager(), this.executionsDir, this.projectsDir, <ide> this.installedProjects, null)); <ide> doNothing().when(this.instance).touchIfExists(any()); <del> } <del> <del> @After <del> public void tearDown() throws Exception { <del> FileUtils.deleteDirectory(this.executionsDir); <del> FileUtils.deleteDirectory(this.projectsDir); <ide> } <ide> <ide> @Test
Java
apache-2.0
62a96d3bd2e76a16666d703f7c4e22a025b024ef
0
googleinterns/step188-2020,googleinterns/step188-2020,googleinterns/step188-2020
package com.google.sps.data; import java.util.HashSet; import java.util.Set; public final class VolunteeringOpportunity { private String name; private Set<String> skillsRequired; private int numSpotsLeft; private Set<User> volunteers; public VolunteeringOpportunity( String name, Set<String> requiredSkills, int numSpotsLeft, Set<User> volunteers) { this.name = name; this.skillsRequired = skillsRequired; this.numSpotsLeft = numSpotsLeft; this.volunteers = new HashSet<User>(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<String> getRequiredSkills() { return this.skillsRequired; } public void setRequiredSkills(Set<String> requiredSkills) { this.skillsRequired = requiredSkills; } public void addRequiredSkill(String requiredSkill) { this.skillsRequired.add(requiredSkill); } public int getNumSpotsLeft() { return this.numSpotsLeft; } public void setNumSpotsLeft(int numSpotsLeft) { this.numSpotsLeft = numSpotsLeft; } public Set<User> getVolunteers() { return this.volunteers; } public void addVolunteer(User volunteer) { this.volunteers.add(volunteer); } }
project/src/main/java/com/google/sps/data/VolunteeringOpportunity.java
package com.google.sps.data; import java.util.Set; import java.util.HashSet; public final class VolunteeringOpportunity { private String name; private Set<String> skillsRequired; private int numSpotsLeft; private Set<User> volunteers; public VolunteeringOpportunity( String name, Set<String> requiredSkills, int numSpotsLeft, Set<User> volunteers) { this.name = name; this.skillsRequired = skillsRequired; this.numSpotsLeft = numSpotsLeft; this.volunteers = new HashSet<User>(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<String> getRequiredSkills() { return this.skillsRequired; } public void setRequiredSkills(Set<String> requiredSkills) { this.skillsRequired = requiredSkills; } public void addRequiredSkill(String requiredSkill) { this.skillsRequired.add(requiredSkill); } public int getNumSpotsLeft() { return this.numSpotsLeft; } public void setNumSpotsLeft(int numSpotsLeft) { this.numSpotsLeft = numSpotsLeft; } public Set<User> getVolunteers() { return this.volunteers; } public void addVolunteer(User volunteer) { this.volunteers.add(volunteer); } }
Fix style.
project/src/main/java/com/google/sps/data/VolunteeringOpportunity.java
Fix style.
<ide><path>roject/src/main/java/com/google/sps/data/VolunteeringOpportunity.java <ide> package com.google.sps.data; <ide> <add>import java.util.HashSet; <ide> import java.util.Set; <del>import java.util.HashSet; <ide> <ide> public final class VolunteeringOpportunity { <ide> private String name;
Java
epl-1.0
9a989b5addef7423a8d82ef4a202e99074b447dd
0
darionct/kura,rohitdubey12/kura,gavinying/kura,ymai/kura,ctron/kura,MMaiero/kura,ctron/kura,markcullen/kura_Windows,darionct/kura,MMaiero/kura,markoer/kura,ctron/kura,markoer/kura,rohitdubey12/kura,unverbraucht/kura,gavinying/kura,nicolatimeus/kura,markoer/kura,markoer/kura,nicolatimeus/kura,MMaiero/kura,ctron/kura,gavinying/kura,ymai/kura,rohitdubey12/kura,MMaiero/kura,cdealti/kura,unverbraucht/kura,MMaiero/kura,amitjoy/kura,unverbraucht/kura,rohitdubey12/kura,unverbraucht/kura,darionct/kura,rohitdubey12/kura,gavinying/kura,markoer/kura,markoer/kura,nicolatimeus/kura,cdealti/kura,MMaiero/kura,nicolatimeus/kura,markcullen/kura_Windows,ymai/kura,nicolatimeus/kura,ctron/kura,unverbraucht/kura,gavinying/kura,cdealti/kura,cdealti/kura,amitjoy/kura,nicolatimeus/kura,ymai/kura,cdealti/kura,ctron/kura,markcullen/kura_Windows,ymai/kura,darionct/kura,amitjoy/kura,ymai/kura,darionct/kura,markcullen/kura_Windows,markcullen/kura_Windows,amitjoy/kura,cdealti/kura,darionct/kura,amitjoy/kura,amitjoy/kura,gavinying/kura
/** * Copyright (c) 2011, 2015 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech */ /* * Copyright (c) 2011 Eurotech Inc. All rights reserved. */ package org.eclipse.kura.core.cloud; import java.io.IOException; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.KuraInvalidMessageException; import org.eclipse.kura.certificate.CertificatesService; import org.eclipse.kura.cloud.CloudClient; import org.eclipse.kura.cloud.CloudConnectionEstablishedEvent; import org.eclipse.kura.cloud.CloudConnectionLostEvent; import org.eclipse.kura.cloud.CloudPayloadProtoBufDecoder; import org.eclipse.kura.cloud.CloudPayloadProtoBufEncoder; import org.eclipse.kura.cloud.CloudService; import org.eclipse.kura.configuration.ConfigurableComponent; import org.eclipse.kura.data.DataService; import org.eclipse.kura.data.DataServiceListener; import org.eclipse.kura.message.KuraPayload; import org.eclipse.kura.message.KuraTopic; import org.eclipse.kura.net.NetworkService; import org.eclipse.kura.net.modem.ModemReadyEvent; import org.eclipse.kura.position.PositionLockedEvent; import org.eclipse.kura.position.PositionService; import org.eclipse.kura.system.SystemAdminService; import org.eclipse.kura.system.SystemService; import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CloudServiceImpl implements CloudService, DataServiceListener, ConfigurableComponent, EventHandler, CloudPayloadProtoBufEncoder, CloudPayloadProtoBufDecoder { private static final Logger s_logger = LoggerFactory.getLogger(CloudServiceImpl.class); private static final String TOPIC_BA_APP = "BA"; private static final String TOPIC_MQTT_APP = "MQTT"; private ComponentContext m_ctx; private CloudServiceOptions m_options; private DataService m_dataService; private SystemService m_systemService; private SystemAdminService m_systemAdminService; private NetworkService m_networkService; private PositionService m_positionService; private EventAdmin m_eventAdmin; private CertificatesService m_certificatesService; // use a synchronized implementation for the list private List<CloudClientImpl> m_cloudClients; // package visibility for LyfeCyclePayloadBuilder String m_imei; String m_iccid; String m_imsi; String m_rssi; private boolean m_subscribed; private boolean m_birthPublished; private AtomicInteger m_messageId; public CloudServiceImpl() { m_cloudClients = new CopyOnWriteArrayList<CloudClientImpl>(); m_messageId = new AtomicInteger(); } // ---------------------------------------------------------------- // // Dependencies // // ---------------------------------------------------------------- public void setDataService(DataService dataService) { this.m_dataService = dataService; } public void unsetDataService(DataService dataService) { this.m_dataService = null; } public DataService getDataService() { return m_dataService; } public void setSystemAdminService(SystemAdminService systemAdminService) { this.m_systemAdminService = systemAdminService; } public void unsetSystemAdminService(SystemAdminService systemAdminService) { this.m_systemAdminService = null; } public SystemAdminService getSystemAdminService() { return m_systemAdminService; } public void setSystemService(SystemService systemService) { this.m_systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.m_systemService = null; } public SystemService getSystemService() { return m_systemService; } public void setNetworkService(NetworkService networkService) { this.m_networkService = networkService; } public void unsetNetworkService(NetworkService networkService) { this.m_networkService = null; } public NetworkService getNetworkService() { return m_networkService; } public void setPositionService(PositionService positionService) { this.m_positionService = positionService; } public void unsetPositionService(PositionService positionService) { this.m_positionService = null; } public PositionService getPositionService() { return m_positionService; } public void setEventAdmin(EventAdmin eventAdmin) { this.m_eventAdmin = eventAdmin; } public void unsetEventAdmin(EventAdmin eventAdmin) { this.m_eventAdmin = null; } // ---------------------------------------------------------------- // // Activation APIs // // ---------------------------------------------------------------- protected void activate(ComponentContext componentContext, Map<String,Object> properties) { s_logger.info("activate..."); // // save the bundle context and the properties m_ctx = componentContext; m_options = new CloudServiceOptions(properties, m_systemService); // // install event listener for GPS locked event Dictionary<String,Object> props = new Hashtable<String,Object>(); String[] eventTopics = {PositionLockedEvent.POSITION_LOCKED_EVENT_TOPIC, ModemReadyEvent.MODEM_EVENT_READY_TOPIC}; props.put(EventConstants.EVENT_TOPIC, eventTopics); m_ctx.getBundleContext().registerService(EventHandler.class.getName(), this, props); // // Usually the cloud connection is setup in the // onConnectionEstablished callback. // Since the callback may be lost if we are activated // too late (the DataService is already connected) we // setup the cloud connection here. if (isConnected()) { try { setupCloudConnection(true); } catch (KuraException e) { s_logger.warn("Cannot setup cloud service connection"); } } } public void updated(Map<String,Object> properties) { s_logger.info("updated...: " + properties); // Update properties and re-publish Birth certificate m_options = new CloudServiceOptions(properties, m_systemService); if (isConnected()) { try { setupCloudConnection(false); } catch (KuraException e) { s_logger.warn("Cannot setup cloud service connection"); } } } protected void deactivate(ComponentContext componentContext) { s_logger.info("deactivate..."); if (isConnected()) { try { publishDisconnectCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish disconnect certificate"); } } // no need to release the cloud clients as the updated app // certificate is already published due the missing dependency // we only need to empty our CloudClient list m_cloudClients.clear(); m_dataService = null; m_systemService = null; m_systemAdminService = null; m_networkService = null; m_positionService = null; m_eventAdmin = null; m_certificatesService = null; } public void handleEvent(Event event) { if (PositionLockedEvent.POSITION_LOCKED_EVENT_TOPIC.contains(event.getTopic())) { // if we get a position locked event, // republish the birth certificate only if we are configured to s_logger.info("Handling PositionLockedEvent"); if (m_dataService.isConnected() && m_options.getRepubBirthCertOnGpsLock()) { try { publishBirthCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish birth certificate", e); } } } else if (ModemReadyEvent.MODEM_EVENT_READY_TOPIC.contains(event.getTopic())) { s_logger.info("Handling ModemReadyEvent"); ModemReadyEvent modemReadyEvent = (ModemReadyEvent) event; // keep these identifiers around until we can publish the certificate m_imei = (String)modemReadyEvent.getProperty(ModemReadyEvent.IMEI); m_imsi = (String)modemReadyEvent.getProperty(ModemReadyEvent.IMSI); m_iccid = (String)modemReadyEvent.getProperty(ModemReadyEvent.ICCID); m_rssi = (String)modemReadyEvent.getProperty(ModemReadyEvent.RSSI); s_logger.trace("handleEvent() :: IMEI={}", m_imei); s_logger.trace("handleEvent() :: IMSI={}", m_imsi); s_logger.trace("handleEvent() :: ICCID={}", m_iccid); s_logger.trace("handleEvent() :: RSSI={}", m_rssi); if (m_dataService.isConnected() && m_options.getRepubBirthCertOnModemDetection()) { if (!(((m_imei == null) || (m_imei.length() == 0) || m_imei.equals("ERROR")) && ((m_imsi == null) || (m_imsi.length() == 0) || m_imsi.equals("ERROR")) && ((m_iccid == null) || (m_iccid.length() == 0) || m_iccid.equals("ERROR")))) { s_logger.debug("handleEvent() :: publishing BIRTH certificate ..."); try { publishBirthCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish birth certificate", e); } } } } } // ---------------------------------------------------------------- // // Service APIs // // ---------------------------------------------------------------- @Override public CloudClient newCloudClient(String applicationId) throws KuraException { // create new instance CloudClientImpl cloudClient = new CloudClientImpl(applicationId, m_dataService, this); m_cloudClients.add(cloudClient); // publish updated birth certificate with list of active apps if (isConnected()) { publishAppCertificate(); } // return return cloudClient; } @Override public String[] getCloudApplicationIdentifiers() { List<String> appIds = new ArrayList<String>(); for (CloudClientImpl cloudClient : m_cloudClients) { appIds.add(cloudClient.getApplicationId()); } return appIds.toArray(new String[0]); } @Override public boolean isConnected() { return (m_dataService != null && m_dataService.isConnected()); } // ---------------------------------------------------------------- // // Package APIs // // ---------------------------------------------------------------- public CloudServiceOptions getCloudServiceOptions() { return m_options; } public void removeCloudClient(CloudClientImpl cloudClient) { // remove the client m_cloudClients.remove(cloudClient); // publish updated birth certificate with updated list of active apps if (isConnected()) { try { publishAppCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish app certificate"); } } } byte[] encodePayload(KuraPayload payload) throws KuraException { byte[] bytes = new byte[0]; if (payload == null) { return bytes; } CloudPayloadEncoder encoder = new CloudPayloadProtoBufEncoderImpl(payload); if (m_options.getEncodeGzip()) { encoder = new CloudPayloadGZipEncoder(encoder); } try { bytes = encoder.getBytes(); return bytes; } catch (IOException e) { throw new KuraException(KuraErrorCode.ENCODE_ERROR, e); } } // ---------------------------------------------------------------- // // DataServiceListener API // // ---------------------------------------------------------------- @Override public void onConnectionEstablished() { try { setupCloudConnection(true); } catch (KuraException e) { s_logger.warn("Cannot setup cloud service connection"); } // raise event m_eventAdmin.postEvent( new CloudConnectionEstablishedEvent( new HashMap<String,Object>())); // notify listeners for (CloudClientImpl cloudClient : m_cloudClients) { cloudClient.onConnectionEstablished(); } } private void setupDeviceSubscriptions(boolean subscribe) throws KuraException { StringBuilder sbDeviceSubscription = new StringBuilder(); sbDeviceSubscription.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicWildCard()); // restore or remove default subscriptions if (subscribe) { m_dataService.subscribe(sbDeviceSubscription.toString(), 1); } else { m_dataService.unsubscribe(sbDeviceSubscription.toString()); } } @Override public void onDisconnecting() { // publish disconnect certificate try { publishDisconnectCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish disconnect certificate"); } } @Override public void onDisconnected() { // raise event m_eventAdmin.postEvent( new CloudConnectionLostEvent( new HashMap<String,Object>())); } @Override public void onConnectionLost(Throwable cause) { // raise event m_eventAdmin.postEvent( new CloudConnectionLostEvent( new HashMap<String,Object>())); // notify listeners for (CloudClientImpl cloudClient : m_cloudClients) { cloudClient.onConnectionLost(); } } @Override public void onMessageArrived(String topic, byte[] payload, int qos, boolean retained) { s_logger.info("Message arrived on topic: {}", topic); // notify listeners KuraTopic kuraTopic = new KuraTopic(topic); if (TOPIC_MQTT_APP.equals(kuraTopic.getApplicationId())|| TOPIC_BA_APP.equals(kuraTopic.getApplicationId())) { s_logger.info("Ignoring feedback message from "+topic); } else { KuraPayload kuraPayload = null; try { // try to decode the message into an KuraPayload kuraPayload = (new CloudPayloadProtoBufDecoderImpl(payload)).buildFromByteArray(); } catch (Exception e) { // Wrap the received bytes payload into an KuraPayload s_logger.debug("Received message on topic "+topic+" that could not be decoded. Wrapping it into an KuraPayload."); kuraPayload = new KuraPayload(); kuraPayload.setBody(payload); } for (CloudClientImpl cloudClient : m_cloudClients) { if (cloudClient.getApplicationId().equals(kuraTopic.getApplicationId())) { try { if (m_options.getTopicControlPrefix().equals(kuraTopic.getPrefix())) { if(m_certificatesService == null){ ServiceReference<CertificatesService> sr= m_ctx.getBundleContext().getServiceReference(CertificatesService.class); if(sr != null){ m_certificatesService= m_ctx.getBundleContext().getService(sr); } } boolean validMessage= false; if(m_certificatesService == null){ validMessage= true; }else if(m_certificatesService.verifySignature(kuraTopic, kuraPayload)){ validMessage= true; } if(validMessage){ cloudClient.onControlMessageArrived(kuraTopic.getDeviceId(), kuraTopic.getApplicationTopic(), kuraPayload, qos, retained); }else{ s_logger.warn("Message verification failed! Not valid signature or message not signed."); } } else { cloudClient.onMessageArrived(kuraTopic.getDeviceId(), kuraTopic.getApplicationTopic(), kuraPayload, qos, retained); } } catch (Exception e) { s_logger.error("Error during CloudClientListener notification.", e); } } } } } @Override public void onMessagePublished(int messageId, String topic) { synchronized (m_messageId) { if (m_messageId.get() != -1 && m_messageId.get() == messageId) { if (m_options.getLifeCycleMessageQos() == 0) { m_messageId.set(-1); } m_messageId.notifyAll(); return; } } // notify listeners KuraTopic kuraTopic = new KuraTopic(topic); for (CloudClientImpl cloudClient : m_cloudClients) { if (cloudClient.getApplicationId().equals(kuraTopic.getApplicationId())) { cloudClient.onMessagePublished(messageId, kuraTopic.getApplicationTopic()); } } } @Override public void onMessageConfirmed(int messageId, String topic) { synchronized (m_messageId) { if (m_messageId.get() != -1 && m_messageId.get() == messageId) { m_messageId.set(-1); m_messageId.notifyAll(); return; } } // notify listeners KuraTopic kuraTopic = new KuraTopic(topic); for (CloudClientImpl cloudClient : m_cloudClients) { if (cloudClient.getApplicationId().equals(kuraTopic.getApplicationId())) { cloudClient.onMessageConfirmed(messageId, kuraTopic.getApplicationTopic()); } } } // ---------------------------------------------------------------- // // CloudPayloadProtoBufEncoder API // // ---------------------------------------------------------------- @Override public byte[] getBytes(KuraPayload kuraPayload, boolean gzipped) throws KuraException { CloudPayloadEncoder encoder = new CloudPayloadProtoBufEncoderImpl(kuraPayload); if (gzipped) { encoder = new CloudPayloadGZipEncoder(encoder); } byte[] bytes; try { bytes = encoder.getBytes(); return bytes; } catch (IOException e) { throw new KuraException(KuraErrorCode.ENCODE_ERROR, e); } } // ---------------------------------------------------------------- // // CloudPayloadProtoBufDecoder API // // ---------------------------------------------------------------- @Override public KuraPayload buildFromByteArray(byte[] payload) throws KuraException { CloudPayloadProtoBufDecoderImpl encoder = new CloudPayloadProtoBufDecoderImpl(payload); KuraPayload kuraPayload; try { kuraPayload = encoder.buildFromByteArray(); return kuraPayload; } catch (KuraInvalidMessageException e) { throw new KuraException(KuraErrorCode.DECODER_ERROR, e); } catch (IOException e) { throw new KuraException(KuraErrorCode.DECODER_ERROR, e); } } // ---------------------------------------------------------------- // // Birth and Disconnect Certificates // // ---------------------------------------------------------------- private void setupCloudConnection(boolean onConnect) throws KuraException { // assume we are not yet subscribed if (onConnect) { m_subscribed = false; } // publish birth certificate unless it has already been published // and republish is disabled boolean publishBirth = true; if (m_birthPublished && m_options.getDisableRepubBirthCertOnReconnect()) { publishBirth = false; s_logger.info("Birth certificate republish is disabled in configuration"); } // publish birth certificate if (publishBirth) { publishBirthCertificate(); m_birthPublished = true; } // restore or remove default subscriptions if (m_options.getDisableDefaultSubscriptions()) { s_logger.info("Default subscriptions are disabled in configuration"); if (m_subscribed) { setupDeviceSubscriptions(false); m_subscribed = false; } } else { if (!m_subscribed) { setupDeviceSubscriptions(true); m_subscribed = true; } } } private void publishBirthCertificate() throws KuraException { StringBuilder sbTopic = new StringBuilder(); sbTopic.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicBirthSuffix()); String topic = sbTopic.toString(); KuraPayload payload = createBirthPayload(); publishLifeCycleMessage(topic, payload); } private void publishDisconnectCertificate() throws KuraException { StringBuilder sbTopic = new StringBuilder(); sbTopic.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicDisconnectSuffix()); String topic = sbTopic.toString(); KuraPayload payload = createDisconnectPayload(); publishLifeCycleMessage(topic, payload); } private void publishAppCertificate() throws KuraException { StringBuilder sbTopic = new StringBuilder(); sbTopic.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAppsSuffix()); String topic = sbTopic.toString(); KuraPayload payload = createBirthPayload(); publishLifeCycleMessage(topic, payload); } private KuraPayload createBirthPayload() { LifeCyclePayloadBuilder payloadBuilder = new LifeCyclePayloadBuilder(this); return payloadBuilder.buildBirthPayload(); } private KuraPayload createDisconnectPayload() { LifeCyclePayloadBuilder payloadBuilder = new LifeCyclePayloadBuilder(this); return payloadBuilder.buildDisconnectPayload(); } private void publishLifeCycleMessage(String topic, KuraPayload payload) throws KuraException { // track the message ID and block until the message // has been published (i.e. written to the socket). synchronized (m_messageId) { m_messageId.set(-1); byte[] encodedPayload = encodePayload(payload); int messageId = m_dataService.publish(topic, encodedPayload, m_options.getLifeCycleMessageQos(), m_options.getLifeCycleMessageRetain(), m_options.getLifeCycleMessagePriority()); m_messageId.set(messageId); try { m_messageId.wait(1000); } catch (InterruptedException e) { s_logger.info("Interrupted while waiting for the message to be published", e); } } } }
kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceImpl.java
/** * Copyright (c) 2011, 2014 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech */ /* * Copyright (c) 2011 Eurotech Inc. All rights reserved. */ package org.eclipse.kura.core.cloud; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.KuraInvalidMessageException; import org.eclipse.kura.certificate.CertificatesService; import org.eclipse.kura.cloud.CloudClient; import org.eclipse.kura.cloud.CloudConnectionEstablishedEvent; import org.eclipse.kura.cloud.CloudConnectionLostEvent; import org.eclipse.kura.cloud.CloudPayloadProtoBufDecoder; import org.eclipse.kura.cloud.CloudPayloadProtoBufEncoder; import org.eclipse.kura.cloud.CloudService; import org.eclipse.kura.configuration.ConfigurableComponent; import org.eclipse.kura.data.DataService; import org.eclipse.kura.data.DataServiceListener; import org.eclipse.kura.message.KuraPayload; import org.eclipse.kura.message.KuraRequestPayload; import org.eclipse.kura.message.KuraResponsePayload; import org.eclipse.kura.message.KuraTopic; import org.eclipse.kura.net.NetworkService; import org.eclipse.kura.net.modem.ModemReadyEvent; import org.eclipse.kura.position.PositionLockedEvent; import org.eclipse.kura.position.PositionService; import org.eclipse.kura.system.SystemAdminService; import org.eclipse.kura.system.SystemService; import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CloudServiceImpl implements CloudService, DataServiceListener, ConfigurableComponent, EventHandler, CloudPayloadProtoBufEncoder, CloudPayloadProtoBufDecoder { private static final Logger s_logger = LoggerFactory.getLogger(CloudServiceImpl.class); private static final String TOPIC_BA_APP = "BA"; private static final String TOPIC_MQTT_APP = "MQTT"; private ComponentContext m_ctx; private CloudServiceOptions m_options; private DataService m_dataService; private SystemService m_systemService; private SystemAdminService m_systemAdminService; private NetworkService m_networkService; private PositionService m_positionService; private EventAdmin m_eventAdmin; private CertificatesService m_certificatesService; // use a synchronized implementation for the list private List<CloudClientImpl> m_cloudClients; // package visibility for LyfeCyclePayloadBuilder String m_imei; String m_iccid; String m_imsi; String m_rssi; private boolean m_subscribed; private boolean m_birthPublished; private AtomicInteger m_messageId; public CloudServiceImpl() { m_cloudClients = new CopyOnWriteArrayList<CloudClientImpl>(); m_messageId = new AtomicInteger(); } // ---------------------------------------------------------------- // // Dependencies // // ---------------------------------------------------------------- public void setDataService(DataService dataService) { this.m_dataService = dataService; } public void unsetDataService(DataService dataService) { this.m_dataService = null; } public DataService getDataService() { return m_dataService; } public void setSystemAdminService(SystemAdminService systemAdminService) { this.m_systemAdminService = systemAdminService; } public void unsetSystemAdminService(SystemAdminService systemAdminService) { this.m_systemAdminService = null; } public SystemAdminService getSystemAdminService() { return m_systemAdminService; } public void setSystemService(SystemService systemService) { this.m_systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.m_systemService = null; } public SystemService getSystemService() { return m_systemService; } public void setNetworkService(NetworkService networkService) { this.m_networkService = networkService; } public void unsetNetworkService(NetworkService networkService) { this.m_networkService = null; } public NetworkService getNetworkService() { return m_networkService; } public void setPositionService(PositionService positionService) { this.m_positionService = positionService; } public void unsetPositionService(PositionService positionService) { this.m_positionService = null; } public PositionService getPositionService() { return m_positionService; } public void setEventAdmin(EventAdmin eventAdmin) { this.m_eventAdmin = eventAdmin; } public void unsetEventAdmin(EventAdmin eventAdmin) { this.m_eventAdmin = null; } // ---------------------------------------------------------------- // // Activation APIs // // ---------------------------------------------------------------- protected void activate(ComponentContext componentContext, Map<String,Object> properties) { s_logger.info("activate..."); // // save the bundle context and the properties m_ctx = componentContext; m_options = new CloudServiceOptions(properties, m_systemService); // // install event listener for GPS locked event Dictionary<String,Object> props = new Hashtable<String,Object>(); String[] eventTopics = {PositionLockedEvent.POSITION_LOCKED_EVENT_TOPIC, ModemReadyEvent.MODEM_EVENT_READY_TOPIC}; props.put(EventConstants.EVENT_TOPIC, eventTopics); m_ctx.getBundleContext().registerService(EventHandler.class.getName(), this, props); // // Usually the cloud connection is setup in the // onConnectionEstablished callback. // Since the callback may be lost if we are activated // too late (the DataService is already connected) we // setup the cloud connection here. if (isConnected()) { try { setupCloudConnection(true); } catch (KuraException e) { s_logger.warn("Cannot setup cloud service connection"); } } } public void updated(Map<String,Object> properties) { s_logger.info("updated...: " + properties); // Update properties and re-publish Birth certificate m_options = new CloudServiceOptions(properties, m_systemService); if (isConnected()) { try { setupCloudConnection(false); } catch (KuraException e) { s_logger.warn("Cannot setup cloud service connection"); } } } protected void deactivate(ComponentContext componentContext) { s_logger.info("deactivate..."); if (isConnected()) { try { publishDisconnectCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish disconnect certificate"); } } // no need to release the cloud clients as the updated app // certificate is already published due the missing dependency // we only need to empty our CloudClient list m_cloudClients.clear(); m_dataService = null; m_systemService = null; m_systemAdminService = null; m_networkService = null; m_positionService = null; m_eventAdmin = null; m_certificatesService = null; } public void handleEvent(Event event) { if (PositionLockedEvent.POSITION_LOCKED_EVENT_TOPIC.contains(event.getTopic())) { // if we get a position locked event, // republish the birth certificate only if we are configured to s_logger.info("Handling PositionLockedEvent"); if (m_dataService.isConnected() && m_options.getRepubBirthCertOnGpsLock()) { try { publishBirthCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish birth certificate", e); } } } else if (ModemReadyEvent.MODEM_EVENT_READY_TOPIC.contains(event.getTopic())) { s_logger.info("Handling ModemReadyEvent"); ModemReadyEvent modemReadyEvent = (ModemReadyEvent) event; // keep these identifiers around until we can publish the certificate m_imei = (String)modemReadyEvent.getProperty(ModemReadyEvent.IMEI); m_imsi = (String)modemReadyEvent.getProperty(ModemReadyEvent.IMSI); m_iccid = (String)modemReadyEvent.getProperty(ModemReadyEvent.ICCID); m_rssi = (String)modemReadyEvent.getProperty(ModemReadyEvent.RSSI); s_logger.trace("handleEvent() :: IMEI={}", m_imei); s_logger.trace("handleEvent() :: IMSI={}", m_imsi); s_logger.trace("handleEvent() :: ICCID={}", m_iccid); s_logger.trace("handleEvent() :: RSSI={}", m_rssi); if (m_dataService.isConnected() && m_options.getRepubBirthCertOnModemDetection()) { if (!(((m_imei == null) || (m_imei.length() == 0) || m_imei.equals("ERROR")) && ((m_imsi == null) || (m_imsi.length() == 0) || m_imsi.equals("ERROR")) && ((m_iccid == null) || (m_iccid.length() == 0) || m_iccid.equals("ERROR")))) { s_logger.debug("handleEvent() :: publishing BIRTH certificate ..."); try { publishBirthCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish birth certificate", e); } } } } } // ---------------------------------------------------------------- // // Service APIs // // ---------------------------------------------------------------- @Override public CloudClient newCloudClient(String applicationId) throws KuraException { // create new instance CloudClientImpl cloudClient = new CloudClientImpl(applicationId, m_dataService, this); m_cloudClients.add(cloudClient); // publish updated birth certificate with list of active apps if (isConnected()) { publishAppCertificate(); } // return return cloudClient; } @Override public String[] getCloudApplicationIdentifiers() { List<String> appIds = new ArrayList<String>(); for (CloudClientImpl cloudClient : m_cloudClients) { appIds.add(cloudClient.getApplicationId()); } return appIds.toArray(new String[0]); } @Override public boolean isConnected() { return (m_dataService != null && m_dataService.isConnected()); } // ---------------------------------------------------------------- // // Package APIs // // ---------------------------------------------------------------- public CloudServiceOptions getCloudServiceOptions() { return m_options; } public void removeCloudClient(CloudClientImpl cloudClient) { // remove the client m_cloudClients.remove(cloudClient); // publish updated birth certificate with updated list of active apps if (isConnected()) { try { publishAppCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish app certificate"); } } } byte[] encodePayload(KuraPayload payload) throws KuraException { byte[] bytes = new byte[0]; if (payload == null) { return bytes; } CloudPayloadEncoder encoder = new CloudPayloadProtoBufEncoderImpl(payload); if (m_options.getEncodeGzip()) { encoder = new CloudPayloadGZipEncoder(encoder); } try { bytes = encoder.getBytes(); return bytes; } catch (IOException e) { throw new KuraException(KuraErrorCode.ENCODE_ERROR, e); } } // ---------------------------------------------------------------- // // DataServiceListener API // // ---------------------------------------------------------------- @Override public void onConnectionEstablished() { try { setupCloudConnection(true); } catch (KuraException e) { s_logger.warn("Cannot setup cloud service connection"); } // raise event m_eventAdmin.postEvent( new CloudConnectionEstablishedEvent( new HashMap<String,Object>())); // notify listeners for (CloudClientImpl cloudClient : m_cloudClients) { cloudClient.onConnectionEstablished(); } } private void setupDeviceSubscriptions(boolean subscribe) throws KuraException { StringBuilder sbDeviceSubscription = new StringBuilder(); sbDeviceSubscription.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicWildCard()); // restore or remove default subscriptions if (subscribe) { m_dataService.subscribe(sbDeviceSubscription.toString(), 1); } else { m_dataService.unsubscribe(sbDeviceSubscription.toString()); } } @Override public void onDisconnecting() { // publish disconnect certificate try { publishDisconnectCertificate(); } catch (KuraException e) { s_logger.warn("Cannot publish disconnect certificate"); } } @Override public void onDisconnected() { // raise event m_eventAdmin.postEvent( new CloudConnectionLostEvent( new HashMap<String,Object>())); } @Override public void onConnectionLost(Throwable cause) { // raise event m_eventAdmin.postEvent( new CloudConnectionLostEvent( new HashMap<String,Object>())); // notify listeners for (CloudClientImpl cloudClient : m_cloudClients) { cloudClient.onConnectionLost(); } } @Override public void onMessageArrived(String topic, byte[] payload, int qos, boolean retained) { s_logger.info("Message arrived on topic: {}", topic); // notify listeners KuraTopic kuraTopic = new KuraTopic(topic); if (TOPIC_MQTT_APP.equals(kuraTopic.getApplicationId())|| TOPIC_BA_APP.equals(kuraTopic.getApplicationId())) { s_logger.info("Ignoring feedback message from "+topic); } else { KuraPayload kuraPayload = null; try { // try to decode the message into an KuraPayload kuraPayload = (new CloudPayloadProtoBufDecoderImpl(payload)).buildFromByteArray(); } catch (Exception e) { // Wrap the received bytes payload into an KuraPayload s_logger.debug("Received message on topic "+topic+" that could not be decoded. Wrapping it into an KuraPayload."); kuraPayload = new KuraPayload(); kuraPayload.setBody(payload); } for (CloudClientImpl cloudClient : m_cloudClients) { if (cloudClient.getApplicationId().equals(kuraTopic.getApplicationId())) { try { if (m_options.getTopicControlPrefix().equals(kuraTopic.getPrefix())) { if(m_certificatesService == null){ ServiceReference<CertificatesService> sr= m_ctx.getBundleContext().getServiceReference(CertificatesService.class); if(sr != null){ m_certificatesService= m_ctx.getBundleContext().getService(sr); } } boolean validMessage= false; if(m_certificatesService == null){ validMessage= true; }else if(m_certificatesService.verifySignature(kuraTopic, kuraPayload)){ validMessage= true; } if(validMessage){ cloudClient.onControlMessageArrived(kuraTopic.getDeviceId(), kuraTopic.getApplicationTopic(), kuraPayload, qos, retained); }else{ s_logger.debug("Message verification failed! Not valid signature or message not signed."); KuraRequestPayload reqPayload = KuraRequestPayload.buildFromKuraPayload(kuraPayload); KuraResponsePayload respPayload = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_ERROR); respPayload.setTimestamp(new Date()); StringBuilder sb = new StringBuilder("REPLY") .append("/") .append(reqPayload.getRequestId()); String requesterClientId = reqPayload.getRequesterClientId(); cloudClient.controlPublish( requesterClientId, sb.toString(), respPayload, 0, false, 1); } } else { cloudClient.onMessageArrived(kuraTopic.getDeviceId(), kuraTopic.getApplicationTopic(), kuraPayload, qos, retained); } } catch (Exception e) { s_logger.error("Error during CloudClientListener notification.", e); } } } } } @Override public void onMessagePublished(int messageId, String topic) { synchronized (m_messageId) { if (m_messageId.get() != -1 && m_messageId.get() == messageId) { if (m_options.getLifeCycleMessageQos() == 0) { m_messageId.set(-1); } m_messageId.notifyAll(); return; } } // notify listeners KuraTopic kuraTopic = new KuraTopic(topic); for (CloudClientImpl cloudClient : m_cloudClients) { if (cloudClient.getApplicationId().equals(kuraTopic.getApplicationId())) { cloudClient.onMessagePublished(messageId, kuraTopic.getApplicationTopic()); } } } @Override public void onMessageConfirmed(int messageId, String topic) { synchronized (m_messageId) { if (m_messageId.get() != -1 && m_messageId.get() == messageId) { m_messageId.set(-1); m_messageId.notifyAll(); return; } } // notify listeners KuraTopic kuraTopic = new KuraTopic(topic); for (CloudClientImpl cloudClient : m_cloudClients) { if (cloudClient.getApplicationId().equals(kuraTopic.getApplicationId())) { cloudClient.onMessageConfirmed(messageId, kuraTopic.getApplicationTopic()); } } } // ---------------------------------------------------------------- // // CloudPayloadProtoBufEncoder API // // ---------------------------------------------------------------- @Override public byte[] getBytes(KuraPayload kuraPayload, boolean gzipped) throws KuraException { CloudPayloadEncoder encoder = new CloudPayloadProtoBufEncoderImpl(kuraPayload); if (gzipped) { encoder = new CloudPayloadGZipEncoder(encoder); } byte[] bytes; try { bytes = encoder.getBytes(); return bytes; } catch (IOException e) { throw new KuraException(KuraErrorCode.ENCODE_ERROR, e); } } // ---------------------------------------------------------------- // // CloudPayloadProtoBufDecoder API // // ---------------------------------------------------------------- @Override public KuraPayload buildFromByteArray(byte[] payload) throws KuraException { CloudPayloadProtoBufDecoderImpl encoder = new CloudPayloadProtoBufDecoderImpl(payload); KuraPayload kuraPayload; try { kuraPayload = encoder.buildFromByteArray(); return kuraPayload; } catch (KuraInvalidMessageException e) { throw new KuraException(KuraErrorCode.DECODER_ERROR, e); } catch (IOException e) { throw new KuraException(KuraErrorCode.DECODER_ERROR, e); } } // ---------------------------------------------------------------- // // Birth and Disconnect Certificates // // ---------------------------------------------------------------- private void setupCloudConnection(boolean onConnect) throws KuraException { // assume we are not yet subscribed if (onConnect) { m_subscribed = false; } // publish birth certificate unless it has already been published // and republish is disabled boolean publishBirth = true; if (m_birthPublished && m_options.getDisableRepubBirthCertOnReconnect()) { publishBirth = false; s_logger.info("Birth certificate republish is disabled in configuration"); } // publish birth certificate if (publishBirth) { publishBirthCertificate(); m_birthPublished = true; } // restore or remove default subscriptions if (m_options.getDisableDefaultSubscriptions()) { s_logger.info("Default subscriptions are disabled in configuration"); if (m_subscribed) { setupDeviceSubscriptions(false); m_subscribed = false; } } else { if (!m_subscribed) { setupDeviceSubscriptions(true); m_subscribed = true; } } } private void publishBirthCertificate() throws KuraException { StringBuilder sbTopic = new StringBuilder(); sbTopic.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicBirthSuffix()); String topic = sbTopic.toString(); KuraPayload payload = createBirthPayload(); publishLifeCycleMessage(topic, payload); } private void publishDisconnectCertificate() throws KuraException { StringBuilder sbTopic = new StringBuilder(); sbTopic.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicDisconnectSuffix()); String topic = sbTopic.toString(); KuraPayload payload = createDisconnectPayload(); publishLifeCycleMessage(topic, payload); } private void publishAppCertificate() throws KuraException { StringBuilder sbTopic = new StringBuilder(); sbTopic.append(m_options.getTopicControlPrefix()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAccountToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicClientIdToken()) .append(m_options.getTopicSeparator()) .append(m_options.getTopicAppsSuffix()); String topic = sbTopic.toString(); KuraPayload payload = createBirthPayload(); publishLifeCycleMessage(topic, payload); } private KuraPayload createBirthPayload() { LifeCyclePayloadBuilder payloadBuilder = new LifeCyclePayloadBuilder(this); return payloadBuilder.buildBirthPayload(); } private KuraPayload createDisconnectPayload() { LifeCyclePayloadBuilder payloadBuilder = new LifeCyclePayloadBuilder(this); return payloadBuilder.buildDisconnectPayload(); } private void publishLifeCycleMessage(String topic, KuraPayload payload) throws KuraException { // track the message ID and block until the message // has been published (i.e. written to the socket). synchronized (m_messageId) { m_messageId.set(-1); byte[] encodedPayload = encodePayload(payload); int messageId = m_dataService.publish(topic, encodedPayload, m_options.getLifeCycleMessageQos(), m_options.getLifeCycleMessageRetain(), m_options.getLifeCycleMessagePriority()); m_messageId.set(messageId); try { m_messageId.wait(1000); } catch (InterruptedException e) { s_logger.info("Interrupted while waiting for the message to be published", e); } } } }
Removed response if message signature verification fails Signed-off-by: MMaiero <[email protected]>
kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceImpl.java
Removed response if message signature verification fails
<ide><path>ura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceImpl.java <ide> /** <del> * Copyright (c) 2011, 2014 Eurotech and/or its affiliates <add> * Copyright (c) 2011, 2015 Eurotech and/or its affiliates <ide> * <ide> * All rights reserved. This program and the accompanying materials <ide> * are made available under the terms of the Eclipse Public License v1.0 <ide> <ide> import java.io.IOException; <ide> import java.util.ArrayList; <del>import java.util.Date; <ide> import java.util.Dictionary; <ide> import java.util.HashMap; <ide> import java.util.Hashtable; <ide> import org.eclipse.kura.data.DataService; <ide> import org.eclipse.kura.data.DataServiceListener; <ide> import org.eclipse.kura.message.KuraPayload; <del>import org.eclipse.kura.message.KuraRequestPayload; <del>import org.eclipse.kura.message.KuraResponsePayload; <ide> import org.eclipse.kura.message.KuraTopic; <ide> import org.eclipse.kura.net.NetworkService; <ide> import org.eclipse.kura.net.modem.ModemReadyEvent; <ide> qos, <ide> retained); <ide> }else{ <del> s_logger.debug("Message verification failed! Not valid signature or message not signed."); <del> <del> KuraRequestPayload reqPayload = KuraRequestPayload.buildFromKuraPayload(kuraPayload); <del> KuraResponsePayload respPayload = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_ERROR); <del> respPayload.setTimestamp(new Date()); <del> <del> StringBuilder sb = new StringBuilder("REPLY") <del> .append("/") <del> .append(reqPayload.getRequestId()); <del> <del> String requesterClientId = reqPayload.getRequesterClientId(); <del> cloudClient.controlPublish( <del> requesterClientId, <del> sb.toString(), <del> respPayload, <del> 0, false, 1); <del> <add> s_logger.warn("Message verification failed! Not valid signature or message not signed."); <ide> } <ide> } <ide> else {
Java
mpl-2.0
32bc6a76a9c84fd3fddb76f2de5b65244a79ad3f
0
sensiasoft/lib-ows
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is the "OGC Service Framework". The Initial Developer of the Original Code is the VAST team at the University of Alabama in Huntsville (UAH). <http://vast.uah.edu> Portions created by the Initial Developer are Copyright (C) 2007 the Initial Developer. All Rights Reserved. Please Contact Mike Botts <[email protected]> for more information. Contributor(s): Alexandre Robin <[email protected]> ******************************* END LICENSE BLOCK ***************************/ package org.vast.ows; import java.io.*; import org.vast.xml.DOMHelper; import org.vast.xml.DOMHelperException; import org.apache.xml.serialize.*; /** * <p><b>Title:</b><br/> * SweResponseSerializer * </p> * * <p><b>Description:</b><br/> * Helper class to handle serialization of SWE XML responses * based on a template document obtained from an input stream. * </p> * * <p>Copyright (c) 2007</p> * @author Alexandre Robin * @since Aug 9, 2005 * @version 1.0 */ public abstract class SweResponseSerializer extends XMLSerializer { protected DOMHelper dom; protected SweDataWriter dataWriter; public SweResponseSerializer() { OutputFormat outFormat = new OutputFormat(); outFormat.setMethod("xml"); outFormat.setIndenting(true); outFormat.setLineWidth(0); this.setOutputFormat(outFormat); } /** * Assign the DataWriter to use for the raw data content. * @param dataWriter */ public void setDataWriter(SweDataWriter dataWriter) { this.dataWriter = dataWriter; } /** * Assign the template as an xml stream * @param baseXML */ public void setTemplate(InputStream baseXML) { try { // preload base observation document DOMHelper newDom = new DOMHelper(baseXML, false); //this.setTemplate(newDom); setTemplate(newDom); } catch (DOMHelperException e) { e.printStackTrace(); } } /** * Assign the template as DOMHelper wrapping a DOM document * @param dom */ public void setTemplate(DOMHelper dom) { this.dom = dom; } /** * Write xml to outputStream */ public void writeResponse() throws IOException { serialize(dom.getRootElement()); } }
src/org/vast/ows/SweResponseSerializer.java
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is the "OGC Service Framework". The Initial Developer of the Original Code is the VAST team at the University of Alabama in Huntsville (UAH). <http://vast.uah.edu> Portions created by the Initial Developer are Copyright (C) 2007 the Initial Developer. All Rights Reserved. Please Contact Mike Botts <[email protected]> for more information. Contributor(s): Alexandre Robin <[email protected]> ******************************* END LICENSE BLOCK ***************************/ package org.vast.ows; import java.io.*; import org.vast.xml.DOMHelper; import org.vast.xml.DOMHelperException; import org.apache.xml.serialize.*; /** * <p><b>Title:</b><br/> * Swe Response Serializer * </p> * * <p><b>Description:</b><br/> * Helper class to handle serialization of SWE XML responses * based on a template document obtained from an input stream. * </p> * * <p>Copyright (c) 2007</p> * @author Alexandre Robin * @since Aug 9, 2005 * @version 1.0 */ public abstract class SweResponseSerializer extends XMLSerializer { protected DOMHelper dom; protected SweDataWriter dataWriter; public SweResponseSerializer() { OutputFormat outFormat = new OutputFormat(); outFormat.setMethod("xml"); outFormat.setIndenting(true); outFormat.setLineWidth(0); this.setOutputFormat(outFormat); } /** * Assign the DataWriter to use for the raw data content. * @param dataWriter */ public void setDataWriter(SweDataWriter dataWriter) { this.dataWriter = dataWriter; } /** * Assign the template as an xml stream * @param baseXML */ public void setTemplate(InputStream baseXML) { try { // preload base observation document DOMHelper newDom = new DOMHelper(baseXML, false); this.setTemplate(newDom); } catch (DOMHelperException e) { e.printStackTrace(); } } /** * Assign the template as DOMHelper wrapping a DOM document * @param dom */ public void setTemplate(DOMHelper dom) { this.dom = dom; } /** * Write xml to outputStream */ public void writeResponse() throws IOException { serialize(dom.getRootElement()); } }
Changed setting of this.dom to just dom, to allow root or derived classes to have the dom changed. git-svn-id: a58f1e388be0b035aaf3ce3f4edf164054050d24@218 65eab6d0-0751-0410-986a-37c5601cf520
src/org/vast/ows/SweResponseSerializer.java
Changed setting of this.dom to just dom, to allow root or derived classes to have the dom changed.
<ide><path>rc/org/vast/ows/SweResponseSerializer.java <ide> <ide> /** <ide> * <p><b>Title:</b><br/> <del> * Swe Response Serializer <add> * SweResponseSerializer <ide> * </p> <ide> * <ide> * <p><b>Description:</b><br/> <ide> { <ide> // preload base observation document <ide> DOMHelper newDom = new DOMHelper(baseXML, false); <del> this.setTemplate(newDom); <add> //this.setTemplate(newDom); <add> setTemplate(newDom); <ide> } <ide> catch (DOMHelperException e) <ide> {
Java
apache-2.0
d0e26129b5be50d8950b0618f245e4529144b336
0
cunningt/camel,adessaigne/camel,pax95/camel,tdiesler/camel,tadayosi/camel,pax95/camel,tadayosi/camel,adessaigne/camel,apache/camel,apache/camel,tdiesler/camel,cunningt/camel,tadayosi/camel,adessaigne/camel,tadayosi/camel,christophd/camel,cunningt/camel,adessaigne/camel,apache/camel,pax95/camel,tadayosi/camel,tdiesler/camel,christophd/camel,tdiesler/camel,apache/camel,adessaigne/camel,pax95/camel,tdiesler/camel,christophd/camel,adessaigne/camel,pax95/camel,pax95/camel,christophd/camel,cunningt/camel,christophd/camel,cunningt/camel,christophd/camel,tdiesler/camel,tadayosi/camel,cunningt/camel,apache/camel,apache/camel
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws2.mq; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.spi.UriPath; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.services.mq.MqClient; @UriParams public class MQ2Configuration implements Cloneable { @UriPath(description = "Logical name") @Metadata(required = true) private String label; @UriParam @Metadata(autowired = true) private MqClient amazonMqClient; @UriParam(label = "security", secret = true) private String accessKey; @UriParam(label = "security", secret = true) private String secretKey; @UriParam @Metadata(required = true) private MQ2Operations operation; @UriParam(enums = "HTTP,HTTPS", defaultValue = "HTTPS") private Protocol proxyProtocol = Protocol.HTTPS; @UriParam private String proxyHost; @UriParam private Integer proxyPort; @UriParam private String region; @UriParam(defaultValue = "false") private boolean pojoRequest; @UriParam(defaultValue = "false") private boolean trustAllCertificates; @UriParam(defaultValue = "false") private boolean overrideEndpoint; @UriParam private String uriEndpointOverride; @UriParam(defaultValue = "false") private boolean useDefaultCredentialsProvider; public MqClient getAmazonMqClient() { return amazonMqClient; } /** * To use a existing configured AmazonMQClient as client */ public void setAmazonMqClient(MqClient amazonMqClient) { this.amazonMqClient = amazonMqClient; } public String getAccessKey() { return accessKey; } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public MQ2Operations getOperation() { return operation; } /** * The operation to perform. It can be listBrokers,createBroker,deleteBroker */ public void setOperation(MQ2Operations operation) { this.operation = operation; } public Protocol getProxyProtocol() { return proxyProtocol; } /** * To define a proxy protocol when instantiating the MQ client */ public void setProxyProtocol(Protocol proxyProtocol) { this.proxyProtocol = proxyProtocol; } public String getProxyHost() { return proxyHost; } /** * To define a proxy host when instantiating the MQ client */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } /** * To define a proxy port when instantiating the MQ client */ public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getRegion() { return region; } /** * The region in which MQ client needs to work. When using this parameter, the configuration will expect the * lowercase name of the region (for example ap-east-1) You'll need to use the name Region.EU_WEST_1.id() */ public void setRegion(String region) { this.region = region; } public boolean isPojoRequest() { return pojoRequest; } /** * If we want to use a POJO request as body or not */ public void setPojoRequest(boolean pojoRequest) { this.pojoRequest = pojoRequest; } public boolean isTrustAllCertificates() { return trustAllCertificates; } /** * If we want to trust all certificates in case of overriding the endpoint */ public void setTrustAllCertificates(boolean trustAllCertificates) { this.trustAllCertificates = trustAllCertificates; } public boolean isOverrideEndpoint() { return overrideEndpoint; } /** * Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride * option */ public void setOverrideEndpoint(boolean overrideEndpoint) { this.overrideEndpoint = overrideEndpoint; } public String getUriEndpointOverride() { return uriEndpointOverride; } /** * Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option */ public void setUriEndpointOverride(String uriEndpointOverride) { this.uriEndpointOverride = uriEndpointOverride; } /** * Set whether the MQ client should expect to load credentials through a default credentials provider or to * expect static credentials to be passed in. */ public void setUseDefaultCredentialsProvider(Boolean useDefaultCredentialsProvider) { this.useDefaultCredentialsProvider = useDefaultCredentialsProvider; } public Boolean isUseDefaultCredentialsProvider() { return useDefaultCredentialsProvider; } // ************************************************* // // ************************************************* public MQ2Configuration copy() { try { return (MQ2Configuration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Configuration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws2.mq; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.spi.UriPath; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.services.mq.MqClient; @UriParams public class MQ2Configuration implements Cloneable { @UriPath(description = "Logical name") @Metadata(required = true) private String label; @UriParam @Metadata(autowired = true) private MqClient amazonMqClient; @UriParam(label = "security", secret = true) private String accessKey; @UriParam(label = "security", secret = true) private String secretKey; @UriParam @Metadata(required = true) private MQ2Operations operation; @UriParam(enums = "HTTP,HTTPS", defaultValue = "HTTPS") private Protocol proxyProtocol = Protocol.HTTPS; @UriParam private String proxyHost; @UriParam private Integer proxyPort; @UriParam private String region; @UriParam(defaultValue = "false") private boolean pojoRequest; @UriParam(defaultValue = "false") private boolean trustAllCertificates; @UriParam(defaultValue = "false") private boolean overrideEndpoint; @UriParam private String uriEndpointOverride; public MqClient getAmazonMqClient() { return amazonMqClient; } /** * To use a existing configured AmazonMQClient as client */ public void setAmazonMqClient(MqClient amazonMqClient) { this.amazonMqClient = amazonMqClient; } public String getAccessKey() { return accessKey; } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public MQ2Operations getOperation() { return operation; } /** * The operation to perform. It can be listBrokers,createBroker,deleteBroker */ public void setOperation(MQ2Operations operation) { this.operation = operation; } public Protocol getProxyProtocol() { return proxyProtocol; } /** * To define a proxy protocol when instantiating the MQ client */ public void setProxyProtocol(Protocol proxyProtocol) { this.proxyProtocol = proxyProtocol; } public String getProxyHost() { return proxyHost; } /** * To define a proxy host when instantiating the MQ client */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } /** * To define a proxy port when instantiating the MQ client */ public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getRegion() { return region; } /** * The region in which MQ client needs to work. When using this parameter, the configuration will expect the * lowercase name of the region (for example ap-east-1) You'll need to use the name Region.EU_WEST_1.id() */ public void setRegion(String region) { this.region = region; } public boolean isPojoRequest() { return pojoRequest; } /** * If we want to use a POJO request as body or not */ public void setPojoRequest(boolean pojoRequest) { this.pojoRequest = pojoRequest; } public boolean isTrustAllCertificates() { return trustAllCertificates; } /** * If we want to trust all certificates in case of overriding the endpoint */ public void setTrustAllCertificates(boolean trustAllCertificates) { this.trustAllCertificates = trustAllCertificates; } public boolean isOverrideEndpoint() { return overrideEndpoint; } /** * Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride * option */ public void setOverrideEndpoint(boolean overrideEndpoint) { this.overrideEndpoint = overrideEndpoint; } public String getUriEndpointOverride() { return uriEndpointOverride; } /** * Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option */ public void setUriEndpointOverride(String uriEndpointOverride) { this.uriEndpointOverride = uriEndpointOverride; } // ************************************************* // // ************************************************* public MQ2Configuration copy() { try { return (MQ2Configuration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
CAMEL-16465 - Camel-AWS: Add useDefaultCredentialProvider option to all the components - MQ Component
components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Configuration.java
CAMEL-16465 - Camel-AWS: Add useDefaultCredentialProvider option to all the components - MQ Component
<ide><path>omponents/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Configuration.java <ide> private boolean overrideEndpoint; <ide> @UriParam <ide> private String uriEndpointOverride; <add> @UriParam(defaultValue = "false") <add> private boolean useDefaultCredentialsProvider; <ide> <ide> public MqClient getAmazonMqClient() { <ide> return amazonMqClient; <ide> this.uriEndpointOverride = uriEndpointOverride; <ide> } <ide> <add> /** <add> * Set whether the MQ client should expect to load credentials through a default credentials provider or to <add> * expect static credentials to be passed in. <add> */ <add> public void setUseDefaultCredentialsProvider(Boolean useDefaultCredentialsProvider) { <add> this.useDefaultCredentialsProvider = useDefaultCredentialsProvider; <add> } <add> <add> public Boolean isUseDefaultCredentialsProvider() { <add> return useDefaultCredentialsProvider; <add> } <ide> // ************************************************* <ide> // <ide> // *************************************************
JavaScript
agpl-3.0
f26f31745ab55ad4e8f99fc3768abffd612073c6
0
OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire
var gsPrefixVieScolaire = 'viescolaire'; var gsPrefixNotes = 'notes'; var gsPrefixAbsences = 'absences'; var gsFormatDate = 'DD-MM-YYYY'; /** Defining internal routes **/ routes.define(function($routeProvider){ $routeProvider .when('/' + gsPrefixVieScolaire + '/' + gsPrefixAbsences + '/appel',{action:'appel'}) .otherwise({ redirectTo : '/' + gsPrefixVieScolaire + '/' + gsPrefixAbsences + '/appel' }); }); /** Wrapper controller ------------------ Main controller. **/ function AbsencesController($scope, $rootScope, model, template, route, date){ $scope.template = template; template.open('absc_teacher_appel_eleves_container', '../modules/' + gsPrefixAbsences + '/template/absc_teacher_appel_eleves'); $scope.detailEleveOpen = false; $scope.appel = { date : {} }; $scope.getHeure = function (timestampDate) { return moment(new Date(timestampDate)).format("HH:mm"); }; /** * Ajout un evenement de type absence pour l'élève passé en paramètre * @param poEleve l'objet élève */ $scope.ajouterEvenementAbsence = function(poEleve) { var evenementAbsence = $scope.getEvenementEleve(poEleve, 1); // creation absence if(evenementAbsence === undefined) { evenementAbsence = new Evenement(); evenementAbsence.id_eleve = poEleve.id; evenementAbsence.id_type = 1; // TODO compléter // TODO à voir si on créé tout d'un coup ou si on créé l'appel puis on met à jour au fur et à mesure evenementAbsence.id_appel = $scope.appel.id; poEleve.evenements.push(evenementAbsence); evenementAbsence.create(function() { poEleve.isAbsent = true; }); // suppression absence } else { evenementAbsence.delete(function() { poEleve.isAbsent = false; poEleve.evenements.remove(evenementAbsence); }); } }; /** * Retourne l'évenement (absence/retard/depart/incident) d'un élève * selon le type passé en parametre. * * @param poEleve l'élève * @param piTypeEvenement type d'évenement (entier) * @returns l'évenement ouo undefined si aucun évenement trouvé. */ $scope.getEvenementEleve = function(poEleve, piTypeEvenement) { var evenementEleve = poEleve.evenements.findWhere({id_type : parseInt(piTypeEvenement)}); return evenementEleve; }; /** * Ouverture d'un appel suite à la sélection d'une date */ $scope.selectAppel = function () { $scope.ouvrirAppel($scope.appel.date); }; /** * Sélection d'un cours : Affiche le panel central de la liste des élèves * @param cours l'objet cours sélectionné */ $scope.selectCours = function(cours) { $scope.currentCours = cours; $scope.currentCours.eleves.sync(); $scope.currentCours.eleves.on('sync', function(){ $scope.currentCours.eleves.each(function (oEleve) { oEleve.evenements.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); oEleve.absencePrevs.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); oEleve.evenements.on('sync', function() { oEleve.isAbsent = oEleve.evenements.findWhere({id_type : 1}) !== undefined; oEleve.hasRetard = oEleve.evenements.findWhere({id_type : 2}) !== undefined; oEleve.hasDepart = oEleve.evenements.findWhere({id_type : 3}) !== undefined; oEleve.hasIncident = oEleve.evenements.findWhere({id_type : 4}) !== undefined; }); }); }); }; /** * Sélection d'un élève : affiche le panel de droit avec la saisie du retard/depart/punition eleve * @param poEleve l'objet eleve sélectionné */ $scope.detailEleveAppel = function(poEleve) { $scope.detailEleveOpen = true; $scope.currentEleve = poEleve; var oEvenementRetard = $scope.getEvenementEleve(poEleve, 2); var bHasRetard = oEvenementRetard !== undefined; if(!bHasRetard) { oEvenementRetard = new Evenement(); } var oEvenementDepart = $scope.getEvenementEleve(poEleve, 3); var bHasDepart = oEvenementDepart !== undefined; if(!bHasDepart) { oEvenementDepart = new Evenement(); } var oEvenementIncident = $scope.getEvenementEleve(poEleve, 4); var bHasIndicent = oEvenementIncident !== undefined; if(!bHasIndicent) { oEvenementIncident = new Evenement(); } var oEvenementObservation = $scope.getEvenementEleve(poEleve, 5); if(oEvenementObservation === undefined) { oEvenementObservation = new Evenement(); } $scope.currentEleve = { hasRetard : bHasRetard, hasDepart : bHasDepart, hasIncident : bHasIndicent, evenementObservation : oEvenementObservation, evenementDepart : oEvenementDepart, evenementRetard : oEvenementRetard, evenementIncident : oEvenementIncident }; template.open('rightSide_absc_eleve_appel_detail', '../modules/' + gsPrefixAbsences + '/template/absc_eleve_appel_detail'); }; /** * Charge un appel * @param pdtDate la date du jour souhaitée */ $scope.ouvrirAppel = function (pdtDate) { // formatage en string //var sDateDebut = "10-02-2016"; var sDateDebut = moment(pdtDate).format(gsFormatDate); $scope.appel.sDateDebut = sDateDebut; // calcul jour suivant var sDateFin = moment(pdtDate).add(1, 'days').format(gsFormatDate); $scope.appel.sDateFin = sDateFin; // booleen pour savoir si la partie droite de la vue est affichée (saisie retard/depart/punition eleve) $scope.detailEleveOpen = false; // chargement des cours de la journée de l'enseignant model.courss.sync(model.me.userId, $scope.appel.sDateDebut, $scope.appel.sDateFin); // chargement des eleves de chaque cours model.courss.on('sync', function(){ // TODO ne charger que lors du clic sur un cours //model.courss.each(function(oCours){ // oCours.eleves.sync(); // // oCours.eleves.on('sync', function(){ // oCours.eleves.each(function (oEleve) { // oEleve.evenements.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); // oEleve.absencePrevs.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); // // oEleve.evenements.on('sync', function() { // var evenementEleve = oEleve.evenements.findWhere({id_type : 1}); // oEleve.isAbsent = evenementEleve !== undefined; // }); // // }); // }); //}) }); $scope.courss = model.courss; }; route({ appel: function (params) { var dtToday = new Date(); $scope.ouvrirAppel(dtToday); template.open('main', '../modules/' + gsPrefixAbsences + '/template/absc_teacher_appel'); } }); }
src/main/resources/public/modules/absences/js/controller/absc_enseignant_ctrl.js
var gsPrefixVieScolaire = 'viescolaire'; var gsPrefixNotes = 'notes'; var gsPrefixAbsences = 'absences'; var gsFormatDate = 'DD-MM-YYYY'; /** Defining internal routes **/ routes.define(function($routeProvider){ $routeProvider .when('/' + gsPrefixVieScolaire + '/' + gsPrefixAbsences + '/appel',{action:'appel'}) .otherwise({ redirectTo : '/' + gsPrefixVieScolaire + '/' + gsPrefixAbsences + '/appel' }); }); /** Wrapper controller ------------------ Main controller. **/ function AbsencesController($scope, $rootScope, model, template, route, date){ $scope.template = template; template.open('absc_teacher_appel_eleves_container', '../modules/' + gsPrefixAbsences + '/template/absc_teacher_appel_eleves'); $scope.detailEleveOpen = false; $scope.appel = { date : {} }; $scope.getHeure = function (timestampDate) { return moment(new Date(timestampDate)).format("HH:mm"); }; /** * Ajout un evenement de type absence pour l'élève passé en paramètre * @param poEleve l'objet élève */ $scope.ajouterEvenementAbsence = function(poEleve) { var evenementAbsence = $scope.getEvenementEleve(poEleve, 1); // creation absence if(evenementAbsence === undefined) { evenementAbsence = new Evenement(); evenementAbsence.id_eleve = poEleve.id; evenementAbsence.id_type = 1; // TODO compléter // TODO à voir si on créé tout d'un coup ou si on créé l'appel puis on met à jour au fur et à mesure evenementAbsence.id_appel = $scope.appel.id; poEleve.evenements.push(evenementAbsence); evenementAbsence.create(function() { poEleve.isAbsent = true; }); // suppression absence } else { evenementAbsence.delete(function() { poEleve.isAbsent = false; poEleve.evenements.remove(evenementAbsence); }); } }; /** * Retourne l'évenement (absence/retard/depart/incident) d'un élève * selon le type passé en parametre. * * @param poEleve l'élève * @param piTypeEvenement type d'évenement (entier) * @returns l'évenement ouo undefined si aucun évenement trouvé. */ $scope.getEvenementEleve = function(poEleve, piTypeEvenement) { var evenementEleve = poEleve.evenements.findWhere({id_type : parseInt(piTypeEvenement)}); return evenementEleve; }; /** * Ouverture d'un appel suite à la sélection d'une date */ $scope.selectAppel = function () { $scope.ouvrirAppel($scope.appel.date); } /** * Sélection d'un cours : Affiche le panel central de la liste des élèves * @param cours l'objet cours sélectionné */ $scope.selectCours = function(cours) { $scope.currentCours = cours; $scope.currentCours.eleves.sync(); $scope.currentCours.eleves.on('sync', function(){ $scope.currentCours.eleves.each(function (oEleve) { oEleve.evenements.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); oEleve.absencePrevs.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); oEleve.evenements.on('sync', function() { oEleve.isAbsent = oEleve.evenements.findWhere({id_type : 1}) !== undefined; oEleve.hasRetard = oEleve.evenements.findWhere({id_type : 2}) !== undefined; oEleve.hasDepart = oEleve.evenements.findWhere({id_type : 3}) !== undefined; oEleve.hasIncident = oEleve.evenements.findWhere({id_type : 4}) !== undefined; }); }); }); }; /** * Sélection d'un élève : affiche le panel de droit avec la saisie du retard/depart/punition eleve * @param poEleve l'objet eleve sélectionné */ $scope.detailEleveAppel = function(poEleve) { $scope.detailEleveOpen = true; $scope.currentEleve = poEleve; var oEvenementRetard = $scope.getEvenementEleve(poEleve, 2); var bHasRetard = oEvenementRetard !== undefined; if(!bHasRetard) { oEvenementRetard = new Evenement(); } var oEvenementDepart = $scope.getEvenementEleve(poEleve, 3); var bHasDepart = oEvenementDepart !== undefined; if(!bHasDepart) { oEvenementDepart = new Evenement(); } var oEvenementIncident = $scope.getEvenementEleve(poEleve, 4); var bHasIndicent = oEvenementIncident !== undefined; if(!bHasIndicent) { oEvenementIncident = new Evenement(); } var oEvenementObservation = $scope.getEvenementEleve(poEleve, 5); if(oEvenementObservation === undefined) { oEvenementObservation = new Evenement(); } $scope.currentEleve = { hasRetard : bHasRetard, hasDepart : bHasDepart, hasIncident : bHasIndicent, evenementObservation : oEvenementObservation, evenementDepart : oEvenementDepart, evenementRetard : oEvenementRetard, evenementIncident : oEvenementIncident } template.open('rightSide_absc_eleve_appel_detail', '../modules/' + gsPrefixAbsences + '/template/absc_eleve_appel_detail'); }; /** * Charge un appel * @param pdtDate la date du jour souhaitée */ $scope.ouvrirAppel = function (pdtDate) { // formatage en string //var sDateDebut = "10-02-2016"; var sDateDebut = moment(pdtDate).format(gsFormatDate); $scope.appel.sDateDebut = sDateDebut; // calcul jour suivant var sDateFin = moment(pdtDate).add(1, 'days').format(gsFormatDate); $scope.appel.sDateFin = sDateFin; // booleen pour savoir si la partie droite de la vue est affichée (saisie retard/depart/punition eleve) $scope.detailEleveOpen = false; // chargement des cours de la journée de l'enseignant model.courss.sync(model.me.userId, $scope.appel.sDateDebut, $scope.appel.sDateFin); // chargement des eleves de chaque cours model.courss.on('sync', function(){ // TODO ne charger que lors du clic sur un cours //model.courss.each(function(oCours){ // oCours.eleves.sync(); // // oCours.eleves.on('sync', function(){ // oCours.eleves.each(function (oEleve) { // oEleve.evenements.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); // oEleve.absencePrevs.sync($scope.appel.sDateDebut, $scope.appel.sDateFin); // // oEleve.evenements.on('sync', function() { // var evenementEleve = oEleve.evenements.findWhere({id_type : 1}); // oEleve.isAbsent = evenementEleve !== undefined; // }); // // }); // }); //}) }); $scope.courss = model.courss; }; route({ appel: function (params) { var dtToday = new Date(); $scope.ouvrirAppel(dtToday); template.open('main', '../modules/' + gsPrefixAbsences + '/template/absc_teacher_appel'); } }); }
Absences enseignant
src/main/resources/public/modules/absences/js/controller/absc_enseignant_ctrl.js
Absences enseignant
<ide><path>rc/main/resources/public/modules/absences/js/controller/absc_enseignant_ctrl.js <ide> */ <ide> $scope.selectAppel = function () { <ide> $scope.ouvrirAppel($scope.appel.date); <del> } <add> }; <ide> <ide> /** <ide> * Sélection d'un cours : Affiche le panel central de la liste des élèves <ide> evenementRetard : oEvenementRetard, <ide> evenementIncident : oEvenementIncident <ide> <del> } <add> }; <ide> <ide> template.open('rightSide_absc_eleve_appel_detail', '../modules/' + gsPrefixAbsences + '/template/absc_eleve_appel_detail'); <ide> };
JavaScript
mit
ca55c75f6986a9263ed625d4dc9704ba77600e44
0
jayroh/thredded,jayroh/thredded,thredded/thredded,jayroh/thredded,thredded/thredded,jayroh/thredded,thredded/thredded,thredded/thredded
(() => { const COMPONENT_SELECTOR = '#thredded--container [data-time-ago]'; const Thredded = window.Thredded; if ('timeago' in window) { const timeago = window.timeago; Thredded.onPageLoad(() => { const threddedContainer = document.querySelector('#thredded--container'); if (!threddedContainer) return; timeago().render( document.querySelectorAll(COMPONENT_SELECTOR), threddedContainer.getAttribute('data-thredded-locale').replace('-', '_')); }); document.addEventListener('turbolinks:before-cache', () => { timeago.cancel(); }); } else if ('jQuery' in window && 'timeago' in jQuery.fn) { const $ = window.jQuery; Thredded.onPageLoad(() => { const allowFutureWas = $.timeago.settings.allowFuture; $.timeago.settings.allowFuture = true; $(COMPONENT_SELECTOR).timeago(); $.timeago.settings.allowFuture = allowFutureWas; }); } })();
app/assets/javascripts/thredded/components/time_stamps.es6
(() => { const COMPONENT_SELECTOR = '#thredded--container [data-time-ago]'; const Thredded = window.Thredded; if ('timeago' in window) { const timeago = window.timeago; Thredded.onPageLoad(() => { const threddedContainer = document.querySelector('#thredded--container'); if (!threddedContainer) return; timeago().render( document.querySelectorAll(COMPONENT_SELECTOR), threddedContainer.getAttribute('data-thredded-locale')); }); document.addEventListener('turbolinks:before-cache', () => { timeago.cancel(); }); } else if ('jQuery' in window && 'timeago' in jQuery.fn) { const $ = window.jQuery; Thredded.onPageLoad(() => { const allowFutureWas = $.timeago.settings.allowFuture; $.timeago.settings.allowFuture = true; $(COMPONENT_SELECTOR).timeago(); $.timeago.settings.allowFuture = allowFutureWas; }); } })();
Fix time_stamps.es6 for locale names with a '-' Fixes #626
app/assets/javascripts/thredded/components/time_stamps.es6
Fix time_stamps.es6 for locale names with a '-'
<ide><path>pp/assets/javascripts/thredded/components/time_stamps.es6 <ide> if (!threddedContainer) return; <ide> timeago().render( <ide> document.querySelectorAll(COMPONENT_SELECTOR), <del> threddedContainer.getAttribute('data-thredded-locale')); <add> threddedContainer.getAttribute('data-thredded-locale').replace('-', '_')); <ide> }); <ide> document.addEventListener('turbolinks:before-cache', () => { <ide> timeago.cancel();
JavaScript
lgpl-2.1
117241bd5c68288a8eed56e3d94c2a6fc57b6858
0
patczar/exist,jessealama/exist,lcahlander/exist,eXist-db/exist,ljo/exist,hungerburg/exist,lcahlander/exist,wshager/exist,eXist-db/exist,lcahlander/exist,shabanovd/exist,MjAbuz/exist,kohsah/exist,adamretter/exist,opax/exist,joewiz/exist,kohsah/exist,RemiKoutcherawy/exist,jessealama/exist,windauer/exist,jensopetersen/exist,jensopetersen/exist,lcahlander/exist,dizzzz/exist,shabanovd/exist,joewiz/exist,windauer/exist,jensopetersen/exist,windauer/exist,wolfgangmm/exist,adamretter/exist,jessealama/exist,ambs/exist,joewiz/exist,jensopetersen/exist,patczar/exist,olvidalo/exist,kohsah/exist,olvidalo/exist,kohsah/exist,dizzzz/exist,windauer/exist,olvidalo/exist,wolfgangmm/exist,adamretter/exist,hungerburg/exist,hungerburg/exist,ljo/exist,wolfgangmm/exist,opax/exist,shabanovd/exist,joewiz/exist,MjAbuz/exist,joewiz/exist,wshager/exist,wolfgangmm/exist,patczar/exist,hungerburg/exist,wolfgangmm/exist,patczar/exist,zwobit/exist,dizzzz/exist,ambs/exist,ljo/exist,shabanovd/exist,jessealama/exist,zwobit/exist,lcahlander/exist,opax/exist,lcahlander/exist,wshager/exist,RemiKoutcherawy/exist,dizzzz/exist,joewiz/exist,jessealama/exist,jessealama/exist,MjAbuz/exist,windauer/exist,shabanovd/exist,eXist-db/exist,dizzzz/exist,patczar/exist,zwobit/exist,MjAbuz/exist,adamretter/exist,wshager/exist,zwobit/exist,olvidalo/exist,kohsah/exist,zwobit/exist,eXist-db/exist,ambs/exist,jensopetersen/exist,ljo/exist,jensopetersen/exist,RemiKoutcherawy/exist,ambs/exist,adamretter/exist,windauer/exist,adamretter/exist,RemiKoutcherawy/exist,zwobit/exist,dizzzz/exist,olvidalo/exist,ambs/exist,ljo/exist,wshager/exist,MjAbuz/exist,wshager/exist,eXist-db/exist,MjAbuz/exist,shabanovd/exist,opax/exist,hungerburg/exist,patczar/exist,wolfgangmm/exist,RemiKoutcherawy/exist,ljo/exist,ambs/exist,opax/exist,kohsah/exist,eXist-db/exist,RemiKoutcherawy/exist
window.onload = init; window.onresize = resize; window.activeTab = null; var PROGRESS_DIALOG = '<div id="progress-inner">' + ' <h1 id="progress-message">Starting ...</h1>' + ' <table cellspacing="20">' + ' <tr>' + ' <td id="progress-passed">0</td>' + ' <td>/</td>' + ' <td id="progress-failed">0</td>' + ' </tr>' + ' </table>' + ' <div id="progressPane">' + ' <div id="progressBar_bg">' + ' <div id="progressBar_outer">' + ' <div id="progressBar"></div>' + ' </div>' + ' <div id="progressBar_txt">0 %</div>' + ' </div>' + ' </div>' + ' <button type="button" id="progress-dismiss">Close</button>' + '</div>'; var timer = null; var progress = null; var progressBar = null; var currentCollection = null; var currentGroup = null; var treeWidget = null; var installWarning; var mode; function init() { resize(); displayTree(); var tabs = YAHOO.util.Dom.getElementsByClassName('tab'); for (var i = 0; i < tabs.length; i++) { YAHOO.util.Event.addListener(tabs[i], 'click', function (ev, tab) { if (window.activeTab) YAHOO.util.Dom.setStyle(window.activeTab, 'display', 'none'); var targetId = tab.id.substring(4); window.activeTab = document.getElementById(targetId); YAHOO.util.Dom.setStyle(window.activeTab, 'display', ''); }, tabs[i] ); } installWarning = new YAHOO.widget.Panel('installation', { height: (YAHOO.util.Dom.getViewportHeight() - 200) + 'px', width: (YAHOO.util.Dom.getViewportWidth() - 200) + 'px', modal: true, underlay: 'shadow', fixedcenter: true, close: false, visible: false, draggable: false }); } function displayTree() { displayMessage('Loading test groups ...'); var callback = { success: treeLoaded, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'report.xql?tree=y', callback); } function treeLoaded(request) { var xml = request.responseXML; var responseRoot = xml.documentElement; var oldTree = null; if (treeWidget) oldTree = treeWidget; treeWidget = new YAHOO.widget.TreeView('navtree'); var rootNode = new YAHOO.widget.TextNode('Suite', treeWidget.getRoot(), true); displayGroup(responseRoot, rootNode, oldTree); treeWidget.draw(); clearMessages(); } function displayGroup(node, treeNode, oldTree) { if (!node.hasChildNodes()) { installWarning.render(document.body); installWarning.show(); return; } for (var i = 0; i < node.childNodes.length; i++) { var child = node.childNodes[i]; if (child.nodeName == 'group') { var name = child.getAttribute('name'); var passed = child.getAttribute('passed'); var failed = child.getAttribute('failed'); var errors = child.getAttribute('errors'); var total = child.getAttribute('total'); var path = child.getAttribute('collection'); var percentage = 0.0; if (total > 0.0) percentage = passed / (total / 100); var display = child.getAttribute('title') + ' [' + passed + '/' + failed + "/" + percentage.toFixed(1) + '%]'; var obj = { label: display, href: "javascript:loadTests('" + path + "', '" + name + "')", group: name }; var expanded = false; if (oldTree != null) { var oldNode = oldTree.getNodeByProperty('group', name); if (node) expanded = oldNode.expanded; } var childTree = new YAHOO.widget.TextNode(obj, treeNode, expanded); if (child.hasChildNodes()) displayGroup(child, childTree, oldTree); } } } function loadTests(collection, group) { displayMessage('Loading tests ...'); var params = 'group=' + collection + '&name=' + group; var callback = { success: function (response) { var tests = document.getElementById('testcases'); tests.innerHTML = response.responseText; resize(); clearMessages(); }, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'report.xql?'+ params, callback); } function details(testName) { var params = 'case=' + testName; var callback = { success: detailsLoaded, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'report.xql?' + params, callback); displayMessage('Loading test details ...'); } function detailsLoaded(request) { document.getElementById('details-content').innerHTML = request.responseText; activeTab = document.getElementById('summary'); clearMessages(); dp.SyntaxHighlighter.HighlightAll('code'); } function runTest(collection, group) { setMode(); if (confirm('Launch test group: ' + group + '?')) { currentCollection = collection; currentGroup = group; progress = new YAHOO.widget.Panel('progress', { width: '400px', height: '250px', modal: true, underlay: 'shadow', fixedcenter: true, close: false, visible: false, draggable: false }); progress.setHeader('Running tests on ' + (mode == 'true' ? 'in-memory nodes' : 'persistent nodes') + '...'); progress.setBody(PROGRESS_DIALOG); progress.render(document.body); document.getElementById('progress-dismiss').disabled = true; YAHOO.util.Event.addListener('progress-dismiss', 'click', function (ev, progress) { progressBar = null; progress.hide(); progress.destroy(); }, progress ); progress.show(); var params = 'group=' + group + '&mode=' + mode; var callback = { success: testCompleted, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'xqts.xql?' + params, callback); timer = setTimeout('reportProgress()', 5000); } } function setMode() { var select = document.getElementsByTagName('*')['processing']; mode = select.options[select.selectedIndex].value; } function testCompleted(request) { if (timer) { clearTimeout(timer); timer = null; } reportProgress(); displayTree(); loadTests(currentCollection, currentGroup); clearMessages(); if (progress) { document.getElementById('progress-dismiss').disabled = false; progressBar.finish(); progressBar = null; } } function reportProgress() { var callback = { success: displayProgress, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'progress.xql', callback); } function displayProgress(request) { if (timer) clearTimeout(timer); var xml = request.responseXML; var responseRoot = xml.documentElement; var done = responseRoot.getAttribute('done'); var total = responseRoot.getAttribute('total'); var passed = responseRoot.getAttribute('passed'); var failed = responseRoot.getAttribute('failed'); document.getElementById('progress-message').innerHTML = 'Processed ' + done + ' out of ' + total + ' tests...'; document.getElementById('progress-passed').innerHTML = passed; document.getElementById('progress-failed').innerHTML = failed; if (progressBar == null) { progressBar = new ProgressBar(total); } progressBar.move(done); if (timer) timer = setTimeout('reportProgress()', 5000); } function requestFailed(request) { displayMessage("Request to the server failed!"); if (timer) { clearTimeout(timer); timer = null; } } function resize() { var $S = YAHOO.util.Dom.setStyle; var content = document.getElementById('content'); $S(content, 'height', (YAHOO.util.Dom.getViewportHeight() - content.offsetTop) + 'px'); var left = document.getElementById('panel-left'); var tree = document.getElementById('navtree'); var h = (left.offsetHeight - tree.offsetTop - 15); $S(tree, 'height', h + 'px'); var panel = document.getElementById('panel-right'); var div = document.getElementById('tests'); h = (left.offsetHeight - div.offsetTop); $S(div, 'height', h + 'px'); panel = document.getElementById('details'); div = document.getElementById('details-content'); var tabs = document.getElementById('tabs'); h = (panel.offsetHeight - tabs.offsetHeight - 8); $S(div, 'height', h + 'px'); } function displayMessage(message) { var messages = document.getElementById('messages'); messages.innerHTML = message; } function clearMessages() { document.getElementById('messages').innerHTML = ''; } ProgressBar = function (max) { this.progressbar_steps = max; } ProgressBar.prototype.move = function (steps) { var progressBar_bg = document.getElementById('progressBar_bg'); var progressbarWidth = progressBar_bg.clientWidth; var width = Math.ceil(progressbarWidth * (steps / this.progressbar_steps)); YAHOO.util.Dom.setStyle('progressBar_outer', 'width', width + 'px'); var percent = Math.ceil((steps / this.progressbar_steps)*100); document.getElementById('progressBar_txt').innerHTML = percent + '%'; } ProgressBar.prototype.finish = function () { var progressBar_bg = document.getElementById('progressBar_bg'); var progressbarWidth = progressBar_bg.clientWidth; YAHOO.util.Dom.setStyle('progressBar_outer', 'width', progressbarWidth + 'px'); document.getElementById('progressBar_txt').innerHTML = '100%'; }
webapp/xqts/scripts/report.js
window.onload = init; window.onresize = resize; window.activeTab = null; var PROGRESS_DIALOG = '<div id="progress-inner">' + ' <h1 id="progress-message">Starting ...</h1>' + ' <table cellspacing="20">' + ' <tr>' + ' <td id="progress-passed">0</td>' + ' <td>/</td>' + ' <td id="progress-failed">0</td>' + ' </tr>' + ' </table>' + ' <div id="progressPane">' + ' <div id="progressBar_bg">' + ' <div id="progressBar_outer">' + ' <div id="progressBar"></div>' + ' </div>' + ' <div id="progressBar_txt">0 %</div>' + ' </div>' + ' </div>' + ' <button type="button" id="progress-dismiss">Close</button>' + '</div>'; var timer = null; var progress = null; var progressBar = null; var currentCollection = null; var currentGroup = null; var treeWidget = null; var installWarning; var mode; function init() { resize(); displayTree(); var tabs = YAHOO.util.Dom.getElementsByClassName('tab'); for (var i = 0; i < tabs.length; i++) { YAHOO.util.Event.addListener(tabs[i], 'click', function (ev, tab) { if (window.activeTab) YAHOO.util.Dom.setStyle(window.activeTab, 'display', 'none'); var targetId = tab.id.substring(4); window.activeTab = document.getElementById(targetId); YAHOO.util.Dom.setStyle(window.activeTab, 'display', ''); }, tabs[i] ); } installWarning = new YAHOO.widget.Panel('installation', { height: (YAHOO.util.Dom.getViewportHeight() - 200) + 'px', width: (YAHOO.util.Dom.getViewportWidth() - 200) + 'px', modal: true, underlay: 'shadow', fixedcenter: true, close: false, visible: false, draggable: false }); } function displayTree() { displayMessage('Loading test groups ...'); var callback = { success: treeLoaded, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'report.xql?tree=y', callback); } function treeLoaded(request) { var xml = request.responseXML; var responseRoot = xml.documentElement; var oldTree = null; if (treeWidget) oldTree = treeWidget; treeWidget = new YAHOO.widget.TreeView('navtree'); var rootNode = new YAHOO.widget.TextNode('Suite', treeWidget.getRoot(), true); displayGroup(responseRoot, rootNode, oldTree); treeWidget.draw(); clearMessages(); } function displayGroup(node, treeNode, oldTree) { if (!node.hasChildNodes()) { installWarning.render(document.body); installWarning.show(); return; } for (var i = 0; i < node.childNodes.length; i++) { var child = node.childNodes[i]; if (child.nodeName == 'group') { var name = child.getAttribute('name'); var passed = child.getAttribute('passed'); var failed = child.getAttribute('failed'); var errors = child.getAttribute('errors'); var total = child.getAttribute('total'); var path = child.getAttribute('collection'); var percentage = 0.0; if (total > 0.0) percentage = passed / (total / 100); var display = child.getAttribute('title') + ' [' + passed + '/' + failed + "/" + percentage.toFixed(1) + '%]'; var obj = { label: display, href: "javascript:loadTests('" + path + "', '" + name + "')", group: name }; var expanded = false; if (oldTree != null) { var oldNode = oldTree.getNodeByProperty('group', name); if (node) expanded = oldNode.expanded; } var childTree = new YAHOO.widget.TextNode(obj, treeNode, expanded); if (child.hasChildNodes()) displayGroup(child, childTree, oldTree); } } } function loadTests(collection, group) { displayMessage('Loading tests ...'); var params = 'group=' + collection + '&name=' + group; var callback = { success: function (response) { var tests = document.getElementById('testcases'); tests.innerHTML = response.responseText; resize(); clearMessages(); }, failure: requestFailed } YAHOO.util.Connect.asyncRequest('POST', 'report.xql', callback, params); } function details(testName) { var params = 'case=' + testName; var callback = { success: detailsLoaded, failure: requestFailed } YAHOO.util.Connect.asyncRequest('POST', 'report.xql', callback, params); displayMessage('Loading test details ...'); } function detailsLoaded(request) { document.getElementById('details-content').innerHTML = request.responseText; activeTab = document.getElementById('summary'); clearMessages(); dp.SyntaxHighlighter.HighlightAll('code'); } function runTest(collection, group) { setMode(); if (confirm('Launch test group: ' + group + '?')) { currentCollection = collection; currentGroup = group; progress = new YAHOO.widget.Panel('progress', { width: '400px', height: '250px', modal: true, underlay: 'shadow', fixedcenter: true, close: false, visible: false, draggable: false }); progress.setHeader('Running tests on ' + (mode == 'true' ? 'in-memory nodes' : 'persistent nodes') + '...'); progress.setBody(PROGRESS_DIALOG); progress.render(document.body); document.getElementById('progress-dismiss').disabled = true; YAHOO.util.Event.addListener('progress-dismiss', 'click', function (ev, progress) { progressBar = null; progress.hide(); progress.destroy(); }, progress ); progress.show(); var params = 'group=' + group + '&mode=' + mode; var callback = { success: testCompleted, failure: requestFailed } YAHOO.util.Connect.asyncRequest('POST', 'xqts.xql', callback, params); timer = setTimeout('reportProgress()', 5000); } } function setMode() { var select = document.getElementsByTagName('*')['processing']; mode = select.options[select.selectedIndex].value; } function testCompleted(request) { if (timer) { clearTimeout(timer); timer = null; } reportProgress(); displayTree(); loadTests(currentCollection, currentGroup); clearMessages(); if (progress) { document.getElementById('progress-dismiss').disabled = false; progressBar.finish(); progressBar = null; } } function reportProgress() { var callback = { success: displayProgress, failure: requestFailed } YAHOO.util.Connect.asyncRequest('GET', 'progress.xql', callback); } function displayProgress(request) { if (timer) clearTimeout(timer); var xml = request.responseXML; var responseRoot = xml.documentElement; var done = responseRoot.getAttribute('done'); var total = responseRoot.getAttribute('total'); var passed = responseRoot.getAttribute('passed'); var failed = responseRoot.getAttribute('failed'); document.getElementById('progress-message').innerHTML = 'Processed ' + done + ' out of ' + total + ' tests...'; document.getElementById('progress-passed').innerHTML = passed; document.getElementById('progress-failed').innerHTML = failed; if (progressBar == null) { progressBar = new ProgressBar(total); } progressBar.move(done); if (timer) timer = setTimeout('reportProgress()', 5000); } function requestFailed(request) { displayMessage("Request to the server failed!"); if (timer) { clearTimeout(timer); timer = null; } } function resize() { var $S = YAHOO.util.Dom.setStyle; var content = document.getElementById('content'); $S(content, 'height', (YAHOO.util.Dom.getViewportHeight() - content.offsetTop) + 'px'); var left = document.getElementById('panel-left'); var tree = document.getElementById('navtree'); var h = (left.offsetHeight - tree.offsetTop - 15); $S(tree, 'height', h + 'px'); var panel = document.getElementById('panel-right'); var div = document.getElementById('tests'); h = (left.offsetHeight - div.offsetTop); $S(div, 'height', h + 'px'); panel = document.getElementById('details'); div = document.getElementById('details-content'); var tabs = document.getElementById('tabs'); h = (panel.offsetHeight - tabs.offsetHeight - 8); $S(div, 'height', h + 'px'); } function displayMessage(message) { var messages = document.getElementById('messages'); messages.innerHTML = message; } function clearMessages() { document.getElementById('messages').innerHTML = ''; } ProgressBar = function (max) { this.progressbar_steps = max; } ProgressBar.prototype.move = function (steps) { var progressBar_bg = document.getElementById('progressBar_bg'); var progressbarWidth = progressBar_bg.clientWidth; var width = Math.ceil(progressbarWidth * (steps / this.progressbar_steps)); YAHOO.util.Dom.setStyle('progressBar_outer', 'width', width + 'px'); var percent = Math.ceil((steps / this.progressbar_steps)*100); document.getElementById('progressBar_txt').innerHTML = percent + '%'; } ProgressBar.prototype.finish = function () { var progressBar_bg = document.getElementById('progressBar_bg'); var progressbarWidth = progressBar_bg.clientWidth; YAHOO.util.Dom.setStyle('progressBar_outer', 'width', progressbarWidth + 'px'); document.getElementById('progressBar_txt').innerHTML = '100%'; }
[bugfix] XQTS: had to replace all POST requests with GET in report.js, otherwise the XQTS could not be executed. Maybe we should update the javascript library used? The XQTS test runner is still based on some old prototype version. svn path=/trunk/eXist/; revision=8766
webapp/xqts/scripts/report.js
[bugfix] XQTS: had to replace all POST requests with GET in report.js, otherwise the XQTS could not be executed. Maybe we should update the javascript library used? The XQTS test runner is still based on some old prototype version.
<ide><path>ebapp/xqts/scripts/report.js <ide> }, <ide> failure: requestFailed <ide> } <del> YAHOO.util.Connect.asyncRequest('POST', 'report.xql', callback, params); <add> YAHOO.util.Connect.asyncRequest('GET', 'report.xql?'+ params, callback); <ide> } <ide> <ide> function details(testName) { <ide> success: detailsLoaded, <ide> failure: requestFailed <ide> } <del> YAHOO.util.Connect.asyncRequest('POST', 'report.xql', callback, params); <add> YAHOO.util.Connect.asyncRequest('GET', 'report.xql?' + params, callback); <ide> displayMessage('Loading test details ...'); <ide> } <ide> <ide> success: testCompleted, <ide> failure: requestFailed <ide> } <del> YAHOO.util.Connect.asyncRequest('POST', 'xqts.xql', callback, params); <add> YAHOO.util.Connect.asyncRequest('GET', 'xqts.xql?' + params, callback); <ide> timer = setTimeout('reportProgress()', 5000); <ide> } <ide> }
JavaScript
mpl-2.0
cc9c04dcd2ef26bf3ef9524c05f9f3813257c900
0
jondos/jondofox,jondos/jondofox
var prefs = require("../preferences.js"); exports["testing on_pref_change"] = function(assert, done){ prefs.SPref.init(); if(prefs.SPref.check_installation() != 0){ assert.equal(true, false, "[!] ShadowPref check_installation() failed - something is really wrong..."); done(); } prefs.SPref.add("test_pref", "", "test_our_value", true, 0); if(prefs.SPref.important_prefs[prefs.SPref.important_prefs.length-1][1] != "" || prefs.SPref.important_prefs[prefs.SPref.important_prefs.length-1][2] != "test_our_value"){ assert.equal(true, false, "[!] ShadowPref add() failed."); done(); } if(prefs.SPref.getSPValue("test_pref", 0) != "" || prefs.SPref.getSPValue("test_pref", 1) != "test_our_value"){ assert.equal(true, false, "[!] ShadowPref getSPValue() failed."); done(); } prefs.SPref.setSPValue("test_pref", 0, "test_user_value"); if(prefs.SPref.getSPValue("test_pref", 0) != "test_user_value"){ assert.equal(true, false, "[!] ShadowPref setSPValue() failed."); done(); } if(require("sdk/preferences/service").get(prefs.SPref.important_prefs[7][0]) != prefs.SPref.getSPValue(prefs.SPref.important_prefs[7][0], 0)){ assert.equal(true, false, "[!] ShadowPref getCurrUserVal() failed."); done(); } prefs.SPref.install(); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") != prefs.SPref.getSPValue("test_pref", 1)){ assert.equal(true, false, "[!] ShadowPref install() failed."); done(); } prefs.SPref.setSPValue("test_pref", 1, "test_our_new_value"); prefs.SPref.fix_missing(false); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") == "test_our_new_value"){ assert.equal(true, false, "[!] ShadowPref fix_missing() failed!"); done(); } prefs.SPref.fix_missing(true); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") != "test_our_new_value"){ assert.equal(true, false, "[!] ShadowPref fix_missing() failed!"); done(); } prefs.SPref.setSPValue("test_pref", 1, "test_our_old_value"); require("sdk/preferences/service").set("extensions.jondofox.test_pref", ""); prefs.SPref.fix_missing(false); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") != "test_our_old_value"){ assert.equal(true, false, "[!] ShadowPref fix_missing() failed!"); done(); } prefs.SPref.activate("", true, 0); for(var i = 0; i < prefs.SPref.important_prefs.length; i++){ if(prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 2) == true && prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 3) == 0){ if(require("sdk/preferences/service").get(prefs.SPref.important_prefs[i][0]) != require("sdk/preferences/service").get("extensions.jondofox." + prefs.SPref.important_prefs[i][0])){ assert.equal(true, false, "[!] ShadowPref activate() failed!"); done(); } } } prefs.SPref.disable("", true, 0, false); for(var i = 0; i < prefs.SPref.important_prefs.length; i++){ if(prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 2) == true && prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 3) == 0){ if(prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 0) != require("sdk/preferences/service").get(prefs.SPref.important_prefs[i][0])){ assert.equal(true, false, "[!] ShadowPref disable() failed!"); done(); } } } require("sdk/preferences/service").set("extensions.jondofox.test_pref", "wolo!"); prefs.SPref.config_readSPValue(); if(prefs.SPref.getSPValue("test_pref", 1) != "wolo!"){ assert.equal(true, false, "[!] ShadowPref config_readSPValue() failed!"); done(); } prefs.SPref.backup_for_crash(); for(var i = 0; i < prefs.SPref.important_prefs.length; i++){ if(require("sdk/preferences/service").get("extensions.jondofox.crashbackup." + prefs.SPref.important_prefs[i][0]) != undefined && prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 0) != ""){ if(require("sdk/preferences/service").get("extensions.jondofox.crashbackup." + prefs.SPref.important_prefs[i][0]) != prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 0)){ assert.equal(true, false, "[!] ShadowPref backup_for_crash() failed!"); done(); } } } assert.equal(true, true, "[i] ShadowPrefs are working!"); done(); } require("sdk/test").run(exports);
test/test-preferences.js
var prefs = require("../preferences.js"); exports["testing on_pref_change"] = function(assert, done){ prefs.SPref.init(); if(prefs.SPref.check_installation() != 0){ assert.equal(true, false, "[!] ShadowPref check_installation() failed - something is really wrong..."); done(); } prefs.SPref.add("test_pref", "", "test_our_value", true, 0); if(prefs.SPref.important_prefs[prefs.SPref.important_prefs.length-1][1] != "" || prefs.SPref.important_prefs[prefs.SPref.important_prefs.length-1][2] != "test_our_value"){ assert.equal(true, false, "[!] ShadowPref add() failed."); done(); } if(prefs.SPref.getSPValue("test_pref", 0) != "" || prefs.SPref.getSPValue("test_pref", 1) != "test_our_value"){ assert.equal(true, false, "[!] ShadowPref getSPValue() failed."); done(); } prefs.SPref.setSPValue("test_pref", 0, "test_user_value"); if(prefs.SPref.getSPValue("test_pref", 0) != "test_user_value"){ assert.equal(true, false, "[!] ShadowPref setSPValue() failed."); done(); } if(require("sdk/preferences/service").get(prefs.SPref.important_prefs[7][0]) != prefs.SPref.getSPValue(prefs.SPref.important_prefs[7][0], 0)){ assert.equal(true, false, "[!] ShadowPref getCurrUserVal() failed."); done(); } prefs.SPref.install(); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") != prefs.SPref.getSPValue("test_pref", 1)){ assert.equal(true, false, "[!] ShadowPref install() failed."); done(); } prefs.SPref.setSPValue("test_pref", 1, "test_our_new_value"); prefs.SPref.fix_missing(false); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") == "test_our_new_value"){ assert.equal(true, false, "[!] ShadowPref fix_missing() failed!"); done(); } prefs.SPref.fix_missing(true); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") != "test_our_new_value"){ assert.equal(true, false, "[!] ShadowPref fix_missing() failed!"); done(); } prefs.SPref.setSPValue("test_pref", 1, "test_our_old_value"); require("sdk/preferences/service").set("extensions.jondofox.test_pref", ""); prefs.SPref.fix_missing(false); if(require("sdk/preferences/service").get("extensions.jondofox.test_pref") != "test_our_old_value"){ assert.equal(true, false, "[!] ShadowPref fix_missing() failed!"); done(); } prefs.SPref.activate("", true, 0); for(var i = 0; i < prefs.SPref.important_prefs.length; i++){ if(prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 2) == true && prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 3) == 0){ if(require("sdk/preferences/service").get(prefs.SPref.important_prefs[i][0]) != require("sdk/preferences/service").get("extensions.jondofox." + prefs.SPref.important_prefs[i][0])){ assert.equal(true, false, "[!] ShadowPref activate() failed!"); done(); } } } assert.equal(true, true, "[i] ShadowPrefs are working!"); done(); } require("sdk/test").run(exports);
#1263 unit test update finished
test/test-preferences.js
#1263 unit test update finished
<ide><path>est/test-preferences.js <ide> <ide> } <ide> <add> prefs.SPref.disable("", true, 0, false); <add> <add> for(var i = 0; i < prefs.SPref.important_prefs.length; i++){ <add> <add> if(prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 2) == true && prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 3) == 0){ <add> <add> if(prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 0) != require("sdk/preferences/service").get(prefs.SPref.important_prefs[i][0])){ <add> <add> assert.equal(true, false, "[!] ShadowPref disable() failed!"); <add> done(); <add> <add> } <add> <add> } <add> <add> } <add> <add> require("sdk/preferences/service").set("extensions.jondofox.test_pref", "wolo!"); <add> prefs.SPref.config_readSPValue(); <add> <add> if(prefs.SPref.getSPValue("test_pref", 1) != "wolo!"){ <add> <add> assert.equal(true, false, "[!] ShadowPref config_readSPValue() failed!"); <add> done(); <add> <add> } <add> <add> prefs.SPref.backup_for_crash(); <add> <add> for(var i = 0; i < prefs.SPref.important_prefs.length; i++){ <add> <add> if(require("sdk/preferences/service").get("extensions.jondofox.crashbackup." + prefs.SPref.important_prefs[i][0]) != undefined && prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 0) != ""){ <add> <add> if(require("sdk/preferences/service").get("extensions.jondofox.crashbackup." + prefs.SPref.important_prefs[i][0]) != prefs.SPref.getSPValue(prefs.SPref.important_prefs[i][0], 0)){ <add> <add> assert.equal(true, false, "[!] ShadowPref backup_for_crash() failed!"); <add> done(); <add> <add> } <add> <add> } <add> <add> } <add> <ide> assert.equal(true, true, "[i] ShadowPrefs are working!"); <ide> done(); <ide>
JavaScript
mit
732104d763a6bdeb49506032913d7a857bd2c6e2
0
arkis/arkis.io,arkis/arkis.io
const jump1 = require('../../../node_modules/jump.js/dist/jump'); function jump(a, b) { window.mobileMenu.close(); return jump1(a, b); } let topBar; window.jumpToTop = () => jump( -window.scrollY, { duration: Math.abs }, ); window.jumpToTeam = () => jump( '.team-section', { duration: Math.abs, offset: -topBar.offsetHeight }, ); window.jumpToContact = () => jump( '#map', { duration: Math.abs, offset: -topBar.offsetHeight }, ); document.addEventListener('DOMContentLoaded', () => { topBar = document.querySelector('.top-bar'); });
app/src/home/nav-links.js
const jump = require('../../../node_modules/jump.js/dist/jump'); let topBar; window.jumpToTop = () => jump( -window.scrollY, { duration: Math.abs }, ); window.jumpToTeam = () => jump( '.team-section', { duration: Math.abs, offset: -topBar.offsetHeight }, ); window.jumpToContact = () => jump( '#map', { duration: Math.abs, offset: -topBar.offsetHeight }, ); document.addEventListener('DOMContentLoaded', () => { topBar = document.querySelector('.top-bar'); });
Automatically close mobile menu when links clicked
app/src/home/nav-links.js
Automatically close mobile menu when links clicked
<ide><path>pp/src/home/nav-links.js <del>const jump = require('../../../node_modules/jump.js/dist/jump'); <add>const jump1 = require('../../../node_modules/jump.js/dist/jump'); <add> <add>function jump(a, b) { <add> window.mobileMenu.close(); <add> return jump1(a, b); <add>} <ide> <ide> let topBar; <ide>
Java
apache-2.0
697a83d7f45538b4eecaa590e12f7245561f9485
0
systemincloud/sic-examples-ext-vip,systemincloud/sic-examples-ext-vip,systemincloud/sic-examples-ext-vip
package com.systemincloud.ext.vip.examples.webcamclient.java; import javax.swing.JFrame; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JButton; import com.systemincloud.sdk.java.msg.MachineType; import com.systemincloud.sdk.java.msg.Provider; import com.systemincloud.sdk.java.msg.Region; public class NewMachineFrame extends JFrame { private static final long serialVersionUID = 1L; private JPanel mainPanel = new JPanel(); private final JPanel comboPanel = new JPanel(); private final JLabel lblProvider = new JLabel("Provider"); private final JComboBox<String> comboProvider = new JComboBox<>(); private final JLabel lblRegion = new JLabel("Region"); private final JComboBox<String> comboRegion = new JComboBox<>(); private final JLabel lblType = new JLabel("Type"); private final JComboBox<String> comboType = new JComboBox<>(); private final JPanel buttonsPanel = new JPanel(); private final JButton btnCreate = new JButton("Create"); private final JButton btnCancel = new JButton("Cancel"); public NewMachineFrame() { setAlwaysOnTop(true); setSize(700, 100); initLayout(); initComponents(); initButtons(); getContentPane().add(mainPanel, BorderLayout.CENTER); setLocationRelativeTo(null); } private void initLayout() { comboPanel.add(lblProvider); comboPanel.add(comboProvider); comboPanel.add(lblRegion); comboPanel.add(comboRegion); comboPanel.add(lblType); comboPanel.add(comboType); buttonsPanel.add(btnCreate); buttonsPanel.add(btnCancel); mainPanel.setLayout(new BorderLayout()); mainPanel.add(comboPanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); } private void initComponents() { for(Provider p : Provider.values()) comboProvider.addItem(p.getFullName()); comboProvider.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if(event.getStateChange() == ItemEvent.SELECTED) { fillRegions(Provider.getByFullName((String) event.getItem())); } } }); fillRegions(Provider.getByFullName((String) comboProvider.getSelectedItem())); comboRegion.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if(event.getStateChange() == ItemEvent.SELECTED) { fillMachineTypes(Region.getByName((String) event.getItem())); } } }); } private void fillRegions(Provider provider) { comboRegion.removeAllItems(); for(Region r : Region.getForProvider(provider)) comboRegion.addItem(r.getName()); } private void fillMachineTypes(Region byName) { comboType.removeAllItems(); } private void initButtons() { btnCreate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NewMachineFrame.this.dispose(); } }); } }
com.systemincloud.ext.vip.examples.webcamclient.java/src/main/java/com/systemincloud/ext/vip/examples/webcamclient/java/NewMachineFrame.java
package com.systemincloud.ext.vip.examples.webcamclient.java; import javax.swing.JFrame; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JButton; import com.systemincloud.sdk.java.msg.MachineType; import com.systemincloud.sdk.java.msg.Provider; import com.systemincloud.sdk.java.msg.Region; public class NewMachineFrame extends JFrame { private static final long serialVersionUID = 1L; private JPanel mainPanel = new JPanel(); private final JPanel comboPanel = new JPanel(); private final JLabel lblProvider = new JLabel("Provider"); private final JComboBox<String> comboProvider = new JComboBox<>(); private final JLabel lblRegion = new JLabel("Region"); private final JComboBox<String> comboRegion = new JComboBox<>(); private final JLabel lblType = new JLabel("Type"); private final JComboBox<String> comboType = new JComboBox<>(); private final JPanel buttonsPanel = new JPanel(); private final JButton btnCreate = new JButton("Create"); private final JButton btnCancel = new JButton("Cancel"); public NewMachineFrame() { setAlwaysOnTop(true); setSize(500, 100); initLayout(); initComponents(); initButtons(); getContentPane().add(mainPanel, BorderLayout.CENTER); setLocationRelativeTo(null); } private void initLayout() { comboPanel.add(lblProvider); comboPanel.add(comboProvider); comboPanel.add(lblRegion); comboPanel.add(comboRegion); comboPanel.add(lblType); comboPanel.add(comboType); buttonsPanel.add(btnCreate); buttonsPanel.add(btnCancel); mainPanel.setLayout(new BorderLayout()); mainPanel.add(comboPanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); } private void initComponents() { for(Provider p : Provider.values()) comboProvider.addItem(p.getFullName()); comboProvider.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if(event.getStateChange() == ItemEvent.SELECTED) { fillRegions(Provider.getByFullName((String) event.getItem())); } } }); fillRegions(Provider.getByFullName((String) comboProvider.getSelectedItem())); comboRegion.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if(event.getStateChange() == ItemEvent.SELECTED) { fillMachineTypes(Region.getByName((String) event.getItem())); } } }); } private void fillRegions(Provider provider) { } private void fillMachineTypes(Region byName) { } private void initButtons() { btnCreate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NewMachineFrame.this.dispose(); } }); } }
Fill regions in new machine window
com.systemincloud.ext.vip.examples.webcamclient.java/src/main/java/com/systemincloud/ext/vip/examples/webcamclient/java/NewMachineFrame.java
Fill regions in new machine window
<ide><path>om.systemincloud.ext.vip.examples.webcamclient.java/src/main/java/com/systemincloud/ext/vip/examples/webcamclient/java/NewMachineFrame.java <ide> <ide> public NewMachineFrame() { <ide> setAlwaysOnTop(true); <del> setSize(500, 100); <add> setSize(700, 100); <ide> <ide> initLayout(); <ide> initComponents(); <ide> } <ide> <ide> private void fillRegions(Provider provider) { <del> <add> comboRegion.removeAllItems(); <add> for(Region r : Region.getForProvider(provider)) comboRegion.addItem(r.getName()); <ide> } <ide> <ide> private void fillMachineTypes(Region byName) { <del> <add> comboType.removeAllItems(); <ide> } <ide> <ide> private void initButtons() {
Java
apache-2.0
25e3e2c834a385bf4a1826398d3c77ae7ecd32b8
0
millecker/applications,millecker/applications,millecker/applications,millecker/applications,millecker/applications
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.illecker.hadoop.rootbeer.examples.matrixmultiplication.gpu; import org.trifort.rootbeer.runtime.Kernel; import org.trifort.rootbeer.runtime.RootbeerGpu; public class MatrixMultiplicationMapperKernel implements Kernel { private double[] m_matrixA; // matrix A is transposed private double[] m_matrixB; private double[] m_matrixC; private int m_N; private int m_M; private int m_L; private int m_gridSize; private int m_blockSize; private int m_tileWidth; private int m_subMatricesPerThread; public MatrixMultiplicationMapperKernel(double[] transposedmatrixA, double[] matrixB, double[] matrixC, int n, int m, int l, int gridSize, int blockSize, int tileWidth, int subMatricesPerThread) { m_matrixA = transposedmatrixA; // m x n m_matrixB = matrixB; // m x l m_matrixC = matrixC; // n x l m_N = n; m_M = m; m_L = l; m_gridSize = gridSize; m_blockSize = blockSize; m_tileWidth = tileWidth; // 32 by default m_subMatricesPerThread = subMatricesPerThread; } // SharedMemory per block // blockSize = 1024 // => 12 (needed by Rootbeer) + (2 * 1024 * 8 (double)) = 16396 bytes // // based on // http://www.shodor.org/media/content//petascale/materials/UPModules/matrixMultiplication/moduleDocument.pdf // public void gpuMethod() { // get local blockIdx and threadIdx int block_idxx = RootbeerGpu.getBlockIdxx(); int thread_idxx = RootbeerGpu.getThreadIdxx(); // store fields into local variables // each read from a field hits global ram while a local variable // is most likely stored in a register // int gridSize = m_gridSize; // int blockSize = m_blockSize; // int N = m_N; int M = m_M; int L = m_L; int tileWidth = m_tileWidth; int subMatricesPerThread = m_subMatricesPerThread; // store pointers to arrays in local variable double[] matrixA = m_matrixA; double[] matrixB = m_matrixB; double[] matrixC = m_matrixC; // Convert block_idxx to a two dimensional index int blockRow = block_idxx / (L / tileWidth); int blockCol = block_idxx % (L / tileWidth); // Convert thread_idxx to a two dimensional index within submatrix int threadRow = thread_idxx / tileWidth; int threadCol = thread_idxx % tileWidth; // Calculate the index of the destination row and col within submatrix int destRow = (blockRow * tileWidth) + threadRow; int destCol = (blockCol * tileWidth) + threadCol; // print(RootbeerGpu.getThreadId(), colA, colB, 0, 0, 0); double sum = 0; // Loop over all the sub-matrices of A and B that are // required to compute Csub // Multiply each pair of sub-matrices together // and accumulate the results for (int m = 0; m < subMatricesPerThread; m++) { int aRowIndex = (m * tileWidth) + threadRow; int aColIndex = (blockRow * tileWidth) + threadCol; int aValueIndex = (aRowIndex * M) + aColIndex; int bRowIndex = (m * tileWidth) + threadRow; int bColIndex = destCol; int bValueIndex = (bRowIndex * L) + bColIndex; double aValue = matrixA[aValueIndex]; double bValue = matrixB[bValueIndex]; // store the aValue into shared memory at location RootbeerGpu.setSharedDouble(thread_idxx * 8, aValue); // store the bValue into shared memory at location // 1024 is the offset for the row of matrix A RootbeerGpu.setSharedDouble(1024 + (thread_idxx * 8), bValue); // sync threads within a block to make sure the sub-matrices are loaded RootbeerGpu.syncthreads(); // loop over all of aValues and bValues for (int k = 0; k < tileWidth; k++) { // read the aValue from shared memory aValue = RootbeerGpu.getSharedDouble((k * tileWidth + threadRow) * 8); // read the bValue from shared memory bValue = RootbeerGpu .getSharedDouble(1024 + (k * tileWidth + threadCol) * 8); // multiply aValue and bValue and accumulate sum += aValue * bValue; } // sync threads within a block to make sure that the preceding // computation is done before loading two new // sub-matrices of A and B in the next iteration RootbeerGpu.syncthreads(); } int cValueIndex = destRow * L + destCol; // update the target cValue with the sum matrixC[cValueIndex] = sum; } public static void main(String[] args) { // Dummy constructor invocation // to keep kernel constructor in // rootbeer transformation new MatrixMultiplicationMapperKernel(null, null, null, 0, 0, 0, 0, 0, 0, 0); } }
hadoop/rootbeer/matrixmultiplication/src/at/illecker/hadoop/rootbeer/examples/matrixmultiplication/gpu/MatrixMultiplicationMapperKernel.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.illecker.hadoop.rootbeer.examples.matrixmultiplication.gpu; import org.trifort.rootbeer.runtime.Kernel; import org.trifort.rootbeer.runtime.RootbeerGpu; public class MatrixMultiplicationMapperKernel implements Kernel { // input private double[] vector; private double multiplier; // output public int row; public double[] results; // debug public double multiplierVal; public double[] vectorVal; public int thread_idxx; public MatrixMultiplicationMapperKernel(int row, double multiplier, double[] vector) { this.row = row; this.multiplier = multiplier; this.vector = vector; this.results = new double[this.vector.length]; } public void gpuMethod() { // int blockSize = RootbeerGpu.getBlockDimx(); // int gridSize = RootbeerGpu.getGridDimx(); // int block_idxx = RootbeerGpu.getBlockIdxx(); thread_idxx = RootbeerGpu.getThreadIdxx(); // int globalThreadIndex = block_idxx * blockSize + thread_idxx; int vectorStartIndex = 0; // shared memory size // shared-mem-size = (vector.length * 8) // TODO setting up shared memory only within first thread of block does not // work! // if (thread_idxx == 0) { // Put vector to share memory for (int i = 0; i < this.vector.length; i++) { RootbeerGpu.setSharedDouble(vectorStartIndex + i * 8, this.vector[i]); } // } // Sync all kernels, until shared memory was established RootbeerGpu.syncthreads(); // debug multiplierVal = multiplier; vectorVal = new double[this.vector.length]; // Scalar Multiplication (Vector x Element) for (int i = 0; i < this.vector.length; i++) { double vectorElement = RootbeerGpu.getSharedDouble(vectorStartIndex + i * 8); vectorVal[i] = vectorElement; results[i] = vectorElement * multiplier; } } public static void main(String[] args) { // Dummy constructor invocation // to keep kernel constructor in // rootbeer transformation new MatrixMultiplicationMapperKernel(0, 0, null); } }
Update Hadoop MatrixMultiplicationMapperKernel
hadoop/rootbeer/matrixmultiplication/src/at/illecker/hadoop/rootbeer/examples/matrixmultiplication/gpu/MatrixMultiplicationMapperKernel.java
Update Hadoop MatrixMultiplicationMapperKernel
<ide><path>adoop/rootbeer/matrixmultiplication/src/at/illecker/hadoop/rootbeer/examples/matrixmultiplication/gpu/MatrixMultiplicationMapperKernel.java <ide> <ide> public class MatrixMultiplicationMapperKernel implements Kernel { <ide> <del> // input <del> private double[] vector; <del> private double multiplier; <del> // output <del> public int row; <del> public double[] results; <add> private double[] m_matrixA; // matrix A is transposed <add> private double[] m_matrixB; <add> private double[] m_matrixC; <add> private int m_N; <add> private int m_M; <add> private int m_L; <add> private int m_gridSize; <add> private int m_blockSize; <add> private int m_tileWidth; <add> private int m_subMatricesPerThread; <ide> <del> // debug <del> public double multiplierVal; <del> public double[] vectorVal; <del> public int thread_idxx; <del> <del> public MatrixMultiplicationMapperKernel(int row, double multiplier, <del> double[] vector) { <del> this.row = row; <del> this.multiplier = multiplier; <del> this.vector = vector; <del> this.results = new double[this.vector.length]; <add> public MatrixMultiplicationMapperKernel(double[] transposedmatrixA, <add> double[] matrixB, double[] matrixC, int n, int m, int l, int gridSize, <add> int blockSize, int tileWidth, int subMatricesPerThread) { <add> m_matrixA = transposedmatrixA; // m x n <add> m_matrixB = matrixB; // m x l <add> m_matrixC = matrixC; // n x l <add> m_N = n; <add> m_M = m; <add> m_L = l; <add> m_gridSize = gridSize; <add> m_blockSize = blockSize; <add> m_tileWidth = tileWidth; // 32 by default <add> m_subMatricesPerThread = subMatricesPerThread; <ide> } <ide> <add> // SharedMemory per block <add> // blockSize = 1024 <add> // => 12 (needed by Rootbeer) + (2 * 1024 * 8 (double)) = 16396 bytes <add> // <add> // based on <add> // http://www.shodor.org/media/content//petascale/materials/UPModules/matrixMultiplication/moduleDocument.pdf <add> // <ide> public void gpuMethod() { <add> // get local blockIdx and threadIdx <add> int block_idxx = RootbeerGpu.getBlockIdxx(); <add> int thread_idxx = RootbeerGpu.getThreadIdxx(); <ide> <del> // int blockSize = RootbeerGpu.getBlockDimx(); <del> // int gridSize = RootbeerGpu.getGridDimx(); <del> // int block_idxx = RootbeerGpu.getBlockIdxx(); <del> thread_idxx = RootbeerGpu.getThreadIdxx(); <del> // int globalThreadIndex = block_idxx * blockSize + thread_idxx; <add> // store fields into local variables <add> // each read from a field hits global ram while a local variable <add> // is most likely stored in a register <add> // int gridSize = m_gridSize; <add> // int blockSize = m_blockSize; <add> // int N = m_N; <add> int M = m_M; <add> int L = m_L; <add> int tileWidth = m_tileWidth; <add> int subMatricesPerThread = m_subMatricesPerThread; <ide> <del> int vectorStartIndex = 0; <add> // store pointers to arrays in local variable <add> double[] matrixA = m_matrixA; <add> double[] matrixB = m_matrixB; <add> double[] matrixC = m_matrixC; <ide> <del> // shared memory size <del> // shared-mem-size = (vector.length * 8) <add> // Convert block_idxx to a two dimensional index <add> int blockRow = block_idxx / (L / tileWidth); <add> int blockCol = block_idxx % (L / tileWidth); <ide> <del> // TODO setting up shared memory only within first thread of block does not <del> // work! <del> // if (thread_idxx == 0) { <del> // Put vector to share memory <del> for (int i = 0; i < this.vector.length; i++) { <del> RootbeerGpu.setSharedDouble(vectorStartIndex + i * 8, this.vector[i]); <del> } <del> // } <add> // Convert thread_idxx to a two dimensional index within submatrix <add> int threadRow = thread_idxx / tileWidth; <add> int threadCol = thread_idxx % tileWidth; <ide> <del> // Sync all kernels, until shared memory was established <del> RootbeerGpu.syncthreads(); <add> // Calculate the index of the destination row and col within submatrix <add> int destRow = (blockRow * tileWidth) + threadRow; <add> int destCol = (blockCol * tileWidth) + threadCol; <ide> <del> // debug <del> multiplierVal = multiplier; <del> vectorVal = new double[this.vector.length]; <add> // print(RootbeerGpu.getThreadId(), colA, colB, 0, 0, 0); <ide> <del> // Scalar Multiplication (Vector x Element) <del> for (int i = 0; i < this.vector.length; i++) { <add> double sum = 0; <ide> <del> double vectorElement = RootbeerGpu.getSharedDouble(vectorStartIndex + i <del> * 8); <add> // Loop over all the sub-matrices of A and B that are <add> // required to compute Csub <add> // Multiply each pair of sub-matrices together <add> // and accumulate the results <add> for (int m = 0; m < subMatricesPerThread; m++) { <add> int aRowIndex = (m * tileWidth) + threadRow; <add> int aColIndex = (blockRow * tileWidth) + threadCol; <add> int aValueIndex = (aRowIndex * M) + aColIndex; <ide> <del> vectorVal[i] = vectorElement; <del> results[i] = vectorElement * multiplier; <add> int bRowIndex = (m * tileWidth) + threadRow; <add> int bColIndex = destCol; <add> int bValueIndex = (bRowIndex * L) + bColIndex; <add> <add> double aValue = matrixA[aValueIndex]; <add> double bValue = matrixB[bValueIndex]; <add> <add> // store the aValue into shared memory at location <add> RootbeerGpu.setSharedDouble(thread_idxx * 8, aValue); <add> // store the bValue into shared memory at location <add> // 1024 is the offset for the row of matrix A <add> RootbeerGpu.setSharedDouble(1024 + (thread_idxx * 8), bValue); <add> <add> // sync threads within a block to make sure the sub-matrices are loaded <add> RootbeerGpu.syncthreads(); <add> <add> // loop over all of aValues and bValues <add> for (int k = 0; k < tileWidth; k++) { <add> // read the aValue from shared memory <add> aValue = RootbeerGpu.getSharedDouble((k * tileWidth + threadRow) * 8); <add> // read the bValue from shared memory <add> bValue = RootbeerGpu <add> .getSharedDouble(1024 + (k * tileWidth + threadCol) * 8); <add> <add> // multiply aValue and bValue and accumulate <add> sum += aValue * bValue; <add> } <add> <add> // sync threads within a block to make sure that the preceding <add> // computation is done before loading two new <add> // sub-matrices of A and B in the next iteration <add> RootbeerGpu.syncthreads(); <ide> } <ide> <add> int cValueIndex = destRow * L + destCol; <add> // update the target cValue with the sum <add> matrixC[cValueIndex] = sum; <ide> } <ide> <ide> public static void main(String[] args) { <ide> // Dummy constructor invocation <ide> // to keep kernel constructor in <ide> // rootbeer transformation <del> new MatrixMultiplicationMapperKernel(0, 0, null); <add> new MatrixMultiplicationMapperKernel(null, null, null, 0, 0, 0, 0, 0, 0, 0); <ide> } <ide> }
Java
apache-2.0
error: pathspec 'core/src/test/java/org/wso2/carbon/transports/transporter/CustomCarbonTransport.java' did not match any file(s) known to git
f00b6bc0c43ab5b567f6c9f38ed1afccb49fa20a
1
Niranjan-K/carbon-kernel,Niranjan-K/carbon-kernel,ChanakaCooray/carbon-kernel,daneshk/carbon-kernel,ChanakaCooray/carbon-kernel,nuwandi-kernel/carbon-kernel,daneshk/carbon-kernel,cnapagoda/carbon4-kernel,laki88/carbon-kernel,nuwandi-kernel/carbon-kernel,thusithathilina/carbon-kernel,wso2/carbon-kernel,jsdjayanga/carbon-kernel,daneshk/carbon-kernel,nilminiwso2/carbon-kernel-1,wso2/carbon-kernel,nilminiwso2/carbon-kernel-1,jsdjayanga/carbon-kernel,laki88/carbon-kernel,cnapagoda/carbon4-kernel,nilminiwso2/carbon-kernel-1,laki88/carbon-kernel,cnapagoda/carbon4-kernel,thusithathilina/carbon-kernel,thusithathilina/carbon-kernel,Niranjan-K/carbon-kernel,jsdjayanga/carbon-kernel,nuwandi-kernel/carbon-kernel,ChanakaCooray/carbon-kernel,wso2/carbon-kernel
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.transports.transporter; import org.wso2.carbon.transports.CarbonTransport; public class CustomCarbonTransport extends CarbonTransport { public CustomCarbonTransport(String id) { super(id); } @Override public void start() { } @Override protected void stop() { } @Override protected void beginMaintenance() { } @Override protected void endMaintenance() { } }
core/src/test/java/org/wso2/carbon/transports/transporter/CustomCarbonTransport.java
CARBON-15553: Wrote unit test for classes in org.wso2.carbon.core.transports
core/src/test/java/org/wso2/carbon/transports/transporter/CustomCarbonTransport.java
CARBON-15553: Wrote unit test for classes in org.wso2.carbon.core.transports
<ide><path>ore/src/test/java/org/wso2/carbon/transports/transporter/CustomCarbonTransport.java <add>/* <add> * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.wso2.carbon.transports.transporter; <add> <add>import org.wso2.carbon.transports.CarbonTransport; <add> <add>public class CustomCarbonTransport extends CarbonTransport { <add> <add> public CustomCarbonTransport(String id) { <add> super(id); <add> } <add> <add> @Override <add> public void start() { <add> <add> } <add> <add> @Override <add> protected void stop() { <add> <add> } <add> <add> @Override <add> protected void beginMaintenance() { <add> <add> } <add> <add> @Override <add> protected void endMaintenance() { <add> <add> } <add>}
Java
apache-2.0
error: pathspec 'src/test/java/org/skyscreamer/nevado/jms/metadata/JMSDeliveryModeTest.java' did not match any file(s) known to git
47d9540ef100723248b56096253395b0d14d928f
1
glaucio-melo-movile/nevado,keithsjohnson/nevado,Movile/nevado,Movile/nevado,glaucio-melo-movile/nevado,bitsofinfo/nevado,skyscreamer/nevado,keithsjohnson/nevado
package org.skyscreamer.nevado.jms.metadata; import org.junit.Assert; import org.junit.Test; import org.skyscreamer.nevado.jms.AbstractJMSTest; import javax.jms.DeliveryMode; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; /** * Created by IntelliJ IDEA. * User: Carter Page * Date: 3/28/12 * Time: 9:56 PM */ public class JMSDeliveryModeTest extends AbstractJMSTest { @Test public void testDefault() throws JMSException { clearTestQueue(); Message msg = getSession().createMessage(); Message msgOut = sendAndReceive(msg); Assert.assertEquals(Message.DEFAULT_DELIVERY_MODE, msg.getJMSDeliveryMode()); Assert.assertEquals(Message.DEFAULT_DELIVERY_MODE, msgOut.getJMSDeliveryMode()); } @Test public void testAssign() throws JMSException { Message msg1 = getSession().createMessage(); MessageProducer msgProducer = getSession().createProducer(getTestQueue()); msgProducer.send(msg1, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); Message msgOut = getSession().createConsumer(getTestQueue()).receive(); Assert.assertNotNull("Got null message back", msgOut); msgOut.acknowledge(); Assert.assertEquals(DeliveryMode.NON_PERSISTENT, msg1.getJMSDeliveryMode()); Assert.assertEquals(DeliveryMode.NON_PERSISTENT, msgOut.getJMSDeliveryMode()); Message msg2 = getSession().createMessage(); msgProducer.send(msg2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); msgOut = getSession().createConsumer(getTestQueue()).receive(); Assert.assertNotNull("Got null message back", msgOut); msgOut.acknowledge(); Assert.assertEquals(DeliveryMode.PERSISTENT, msg2.getJMSDeliveryMode()); Assert.assertEquals(DeliveryMode.PERSISTENT, msgOut.getJMSDeliveryMode()); } }
src/test/java/org/skyscreamer/nevado/jms/metadata/JMSDeliveryModeTest.java
Added JMSDestination
src/test/java/org/skyscreamer/nevado/jms/metadata/JMSDeliveryModeTest.java
Added JMSDestination
<ide><path>rc/test/java/org/skyscreamer/nevado/jms/metadata/JMSDeliveryModeTest.java <add>package org.skyscreamer.nevado.jms.metadata; <add> <add>import org.junit.Assert; <add>import org.junit.Test; <add>import org.skyscreamer.nevado.jms.AbstractJMSTest; <add> <add>import javax.jms.DeliveryMode; <add>import javax.jms.JMSException; <add>import javax.jms.Message; <add>import javax.jms.MessageProducer; <add> <add>/** <add> * Created by IntelliJ IDEA. <add> * User: Carter Page <add> * Date: 3/28/12 <add> * Time: 9:56 PM <add> */ <add>public class JMSDeliveryModeTest extends AbstractJMSTest { <add> @Test <add> public void testDefault() throws JMSException { <add> clearTestQueue(); <add> Message msg = getSession().createMessage(); <add> Message msgOut = sendAndReceive(msg); <add> Assert.assertEquals(Message.DEFAULT_DELIVERY_MODE, msg.getJMSDeliveryMode()); <add> Assert.assertEquals(Message.DEFAULT_DELIVERY_MODE, msgOut.getJMSDeliveryMode()); <add> } <add> <add> @Test <add> public void testAssign() throws JMSException { <add> Message msg1 = getSession().createMessage(); <add> MessageProducer msgProducer = getSession().createProducer(getTestQueue()); <add> msgProducer.send(msg1, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); <add> Message msgOut = getSession().createConsumer(getTestQueue()).receive(); <add> Assert.assertNotNull("Got null message back", msgOut); <add> msgOut.acknowledge(); <add> Assert.assertEquals(DeliveryMode.NON_PERSISTENT, msg1.getJMSDeliveryMode()); <add> Assert.assertEquals(DeliveryMode.NON_PERSISTENT, msgOut.getJMSDeliveryMode()); <add> <add> Message msg2 = getSession().createMessage(); <add> msgProducer.send(msg2, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); <add> msgOut = getSession().createConsumer(getTestQueue()).receive(); <add> Assert.assertNotNull("Got null message back", msgOut); <add> msgOut.acknowledge(); <add> Assert.assertEquals(DeliveryMode.PERSISTENT, msg2.getJMSDeliveryMode()); <add> Assert.assertEquals(DeliveryMode.PERSISTENT, msgOut.getJMSDeliveryMode()); <add> } <add>}
Java
bsd-3-clause
21cc79e1684e31aa7c0753640de4a6fdf9b2d9e7
0
Civcraft/CivMenu,Maxopoly/CivMenu,BlackXnt/CivMenu
package vg.civcraft.mc.civmenu.datamanager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import vg.civcraft.mc.civmenu.CivMenu; import vg.civcraft.mc.civmenu.TermObject; import vg.civcraft.mc.civmenu.database.Database; import vg.civcraft.mc.civmodcore.Config; import vg.civcraft.mc.civmodcore.annotations.CivConfig; import vg.civcraft.mc.civmodcore.annotations.CivConfigType; import vg.civcraft.mc.civmodcore.annotations.CivConfigs; public class MysqlManager implements ISaveLoad{ private CivMenu plugin; private Config config; private Database db; private String insertData, getAllData; private Map<UUID, TermObject> registeredPlayers = new HashMap<UUID, TermObject>(); public MysqlManager(CivMenu plugin) { this.plugin = plugin; config = plugin.GetConfig(); initializeStrings(); } private void initializeStrings() { insertData = "insert into civ_menu_data(uuid, term) values (?,?);"; getAllData = "select * from civ_menu_data;"; } @CivConfigs({ @CivConfig(name = "mysql.username", def = "bukkit", type = CivConfigType.String), @CivConfig(name = "mysql.password", def = "", type = CivConfigType.String), @CivConfig(name = "mysql.host", def = "localhost", type = CivConfigType.String), @CivConfig(name = "mysql.dbname", def = "bukkit", type = CivConfigType.String), @CivConfig(name = "mysql.port", def = "3306", type = CivConfigType.Int) }) private void loadDB() { String username = config.get("mysql.username").getString(); String password = config.get("mysql.password").getString(); String host = config.get("mysql.host").getString(); String dbname = config.get("mysql.dbname").getString(); int port = config.get("mysql.port").getInt(); db = new Database(host, port, dbname, username, password, plugin.getLogger()); if (!db.connect()) { plugin.getLogger().log(Level.INFO, "Mysql could not connect, shutting down."); Bukkit.getPluginManager().disablePlugin(plugin); } createTables(); } private void createTables() { db.execute("create table if not exists civ_menu_data(" + "uuid varchar(36) not null," + "term varchar(255) not null," + "primary key uuid_info(uuid, info));"); } @Override public void load() { loadDB(); PreparedStatement playerData = db.prepareStatement(getAllData); ResultSet set; try { set = playerData.executeQuery(); while (set.next()) { UUID uuid = UUID.fromString(set.getString("uuid")); if (!registeredPlayers.containsKey(uuid)) registeredPlayers.put(uuid, new TermObject(uuid)); registeredPlayers.get(uuid).addTerm(set.getString("term")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void save() { // No need to save, all done on playeradd. } @Override public void addPlayer(Player p, String term) { if (!registeredPlayers.containsKey(p.getUniqueId())) registeredPlayers.put(p.getUniqueId(), new TermObject(p.getUniqueId())); registeredPlayers.get(p.getUniqueId()).addTerm(term); PreparedStatement addPlayer = db.prepareStatement(insertData); try { addPlayer.setString(1, p.getUniqueId().toString()); addPlayer.setString(2, term); addPlayer.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean isAddedPlayer(Player p, String term) { return registeredPlayers.get(p.getUniqueId()) != null && registeredPlayers.get(p.getUniqueId()).hasTerm(term); } }
src/vg/civcraft/mc/civmenu/datamanager/MysqlManager.java
package vg.civcraft.mc.civmenu.datamanager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import vg.civcraft.mc.civmenu.CivMenu; import vg.civcraft.mc.civmenu.TermObject; import vg.civcraft.mc.civmenu.database.Database; import vg.civcraft.mc.civmodcore.Config; import vg.civcraft.mc.civmodcore.annotations.CivConfig; import vg.civcraft.mc.civmodcore.annotations.CivConfigType; import vg.civcraft.mc.civmodcore.annotations.CivConfigs; public class MysqlManager implements ISaveLoad{ private CivMenu plugin; private Config config; private Database db; private String insertData, getAllData; private Map<UUID, TermObject> registeredPlayers = new HashMap<UUID, TermObject>(); public MysqlManager(CivMenu plugin) { this.plugin = plugin; config = plugin.GetConfig(); initializeStrings(); } private void initializeStrings() { insertData = "insert into civ_menu_data(uuid, term) values (?,?);"; getAllData = "select * from civ_menu_data;"; } @CivConfigs({ @CivConfig(name = "mysql.username", def = "bukkit", type = CivConfigType.String), @CivConfig(name = "mysql.password", def = "", type = CivConfigType.String), @CivConfig(name = "mysql.host", def = "localhost", type = CivConfigType.String), @CivConfig(name = "mysql.dbname", def = "bukkit", type = CivConfigType.String), @CivConfig(name = "mysql.port", def = "3306", type = CivConfigType.Int) }) private void loadDB() { String username = config.get("mysql.username").getString(); String password = config.get("mysql.password").getString(); String host = config.get("mysql.host").getString(); String dbname = config.get("mysql.dbname").getName(); int port = config.get("mysql.port").getInt(); db = new Database(host, port, dbname, username, password, plugin.getLogger()); if (!db.connect()) { plugin.getLogger().log(Level.INFO, "Mysql could not connect, shutting down."); Bukkit.getPluginManager().disablePlugin(plugin); } createTables(); } private void createTables() { db.execute("create table if not exists civ_menu_data(" + "uuid varchar(36) not null," + "term varchar(255) not null," + "primary key uuid_info(uuid, info));"); } @Override public void load() { loadDB(); PreparedStatement playerData = db.prepareStatement(getAllData); ResultSet set; try { set = playerData.executeQuery(); while (set.next()) { UUID uuid = UUID.fromString(set.getString("uuid")); if (!registeredPlayers.containsKey(uuid)) registeredPlayers.put(uuid, new TermObject(uuid)); registeredPlayers.get(uuid).addTerm(set.getString("term")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void save() { // No need to save, all done on playeradd. } @Override public void addPlayer(Player p, String term) { if (!registeredPlayers.containsKey(p.getUniqueId())) registeredPlayers.put(p.getUniqueId(), new TermObject(p.getUniqueId())); registeredPlayers.get(p.getUniqueId()).addTerm(term); PreparedStatement addPlayer = db.prepareStatement(insertData); try { addPlayer.setString(1, p.getUniqueId().toString()); addPlayer.setString(2, term); addPlayer.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean isAddedPlayer(Player p, String term) { return registeredPlayers.get(p.getUniqueId()) != null && registeredPlayers.get(p.getUniqueId()).hasTerm(term); } }
Fix anotehr minor msitake
src/vg/civcraft/mc/civmenu/datamanager/MysqlManager.java
Fix anotehr minor msitake
<ide><path>rc/vg/civcraft/mc/civmenu/datamanager/MysqlManager.java <ide> String username = config.get("mysql.username").getString(); <ide> String password = config.get("mysql.password").getString(); <ide> String host = config.get("mysql.host").getString(); <del> String dbname = config.get("mysql.dbname").getName(); <add> String dbname = config.get("mysql.dbname").getString(); <ide> int port = config.get("mysql.port").getInt(); <ide> db = new Database(host, port, dbname, username, password, plugin.getLogger()); <ide> if (!db.connect()) {
Java
apache-2.0
1c3231868a247dc581028cfd56f8736755bf244b
0
nknize/elasticsearch,GlenRSmith/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.watcher.history; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.xpack.core.watcher.execution.ExecutionState; import org.elasticsearch.xpack.core.watcher.history.HistoryStoreField; import org.elasticsearch.xpack.core.watcher.transport.actions.put.PutWatchRequestBuilder; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction; import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder; import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.interval; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /** * This test makes sure that the index action response `index` field in the watch_record action result is * not analyzed so it can be used in aggregations */ public class HistoryTemplateIndexActionMappingsTests extends AbstractWatcherIntegrationTestCase { @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/65091") public void testIndexActionFields() throws Exception { String index = "the-index"; PutWatchResponse putWatchResponse = new PutWatchRequestBuilder(client(), "_id").setSource(watchBuilder() .trigger(schedule(interval("5m"))) .addAction("index", indexAction(index))) .get(); assertThat(putWatchResponse.isCreated(), is(true)); timeWarp().trigger("_id"); flush(); refresh(); // the action should fail as no email server is available assertWatchWithMinimumActionsCount("_id", ExecutionState.EXECUTED, 1); flush(); refresh(); SearchResponse response = client().prepareSearch(HistoryStoreField.DATA_STREAM + "*").setSource(searchSource() .aggregation(terms("index_action_indices").field("result.actions.index.response.index"))) .get(); assertThat(response, notNullValue()); assertThat(response.getHits().getTotalHits().value, is(1L)); Aggregations aggs = response.getAggregations(); assertThat(aggs, notNullValue()); Terms terms = aggs.get("index_action_indices"); assertThat(terms, notNullValue()); assertThat(terms.getBuckets().size(), is(1)); assertThat(terms.getBucketByKey(index), notNullValue()); assertThat(terms.getBucketByKey(index).getDocCount(), is(1L)); } }
x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/history/HistoryTemplateIndexActionMappingsTests.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.watcher.history; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.xpack.core.watcher.execution.ExecutionState; import org.elasticsearch.xpack.core.watcher.history.HistoryStoreField; import org.elasticsearch.xpack.core.watcher.transport.actions.put.PutWatchRequestBuilder; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction; import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder; import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.interval; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /** * This test makes sure that the index action response `index` field in the watch_record action result is * not analyzed so it can be used in aggregations */ public class HistoryTemplateIndexActionMappingsTests extends AbstractWatcherIntegrationTestCase { public void testIndexActionFields() throws Exception { String index = "the-index"; PutWatchResponse putWatchResponse = new PutWatchRequestBuilder(client(), "_id").setSource(watchBuilder() .trigger(schedule(interval("5m"))) .addAction("index", indexAction(index))) .get(); assertThat(putWatchResponse.isCreated(), is(true)); timeWarp().trigger("_id"); flush(); refresh(); // the action should fail as no email server is available assertWatchWithMinimumActionsCount("_id", ExecutionState.EXECUTED, 1); flush(); refresh(); SearchResponse response = client().prepareSearch(HistoryStoreField.DATA_STREAM + "*").setSource(searchSource() .aggregation(terms("index_action_indices").field("result.actions.index.response.index"))) .get(); assertThat(response, notNullValue()); assertThat(response.getHits().getTotalHits().value, is(1L)); Aggregations aggs = response.getAggregations(); assertThat(aggs, notNullValue()); Terms terms = aggs.get("index_action_indices"); assertThat(terms, notNullValue()); assertThat(terms.getBuckets().size(), is(1)); assertThat(terms.getBucketByKey(index), notNullValue()); assertThat(terms.getBucketByKey(index).getDocCount(), is(1L)); } }
[TEST] Mute HistoryTemplateIndexActionMappingsTests.testIndexActionFields (#65092) Relates #65091
x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/history/HistoryTemplateIndexActionMappingsTests.java
[TEST] Mute HistoryTemplateIndexActionMappingsTests.testIndexActionFields (#65092)
<ide><path>-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/history/HistoryTemplateIndexActionMappingsTests.java <ide> */ <ide> public class HistoryTemplateIndexActionMappingsTests extends AbstractWatcherIntegrationTestCase { <ide> <add> @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/65091") <ide> public void testIndexActionFields() throws Exception { <ide> String index = "the-index"; <ide>
Java
apache-2.0
1252f6ee32b9c41f043169f36ee7fce2b6fa9e20
0
tteofili/samplett,tteofili/samplett,tteofili/samplett
package com.github.tteofili.looseen; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.classification.CachingNaiveBayesClassifier; import org.apache.lucene.classification.Classifier; import org.apache.lucene.classification.KNearestNeighborClassifier; import org.apache.lucene.classification.SimpleNaiveBayesClassifier; import org.apache.lucene.classification.utils.ConfusionMatrixGenerator; import org.apache.lucene.classification.utils.DatasetSplitter; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.SlowCompositeReaderWrapper; import org.apache.lucene.search.similarities.AfterEffectB; import org.apache.lucene.search.similarities.AfterEffectL; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.search.similarities.BasicModelG; import org.apache.lucene.search.similarities.BasicModelP; import org.apache.lucene.search.similarities.ClassicSimilarity; import org.apache.lucene.search.similarities.DFRSimilarity; import org.apache.lucene.search.similarities.DistributionLL; import org.apache.lucene.search.similarities.DistributionSPL; import org.apache.lucene.search.similarities.IBSimilarity; import org.apache.lucene.search.similarities.LMDirichletSimilarity; import org.apache.lucene.search.similarities.LMJelinekMercerSimilarity; import org.apache.lucene.search.similarities.LambdaDF; import org.apache.lucene.search.similarities.LambdaTTF; import org.apache.lucene.search.similarities.Normalization; import org.apache.lucene.search.similarities.NormalizationH1; import org.apache.lucene.search.similarities.NormalizationH3; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; import org.junit.Test; @LuceneTestCase.SuppressSysoutChecks(bugUrl = "none") public final class Test20NewsgroupsClassification extends LuceneTestCase { private static final String PREFIX = "/Users/teofili/data"; private static final String INDEX = PREFIX + "/20n/index"; private static final String CATEGORY_FIELD = "category"; private static final String BODY_FIELD = "body"; private static final String SUBJECT_FIELD = "subject"; private static boolean index = false; private static boolean split = true; @Test public void test20Newsgroups() throws Exception { String indexProperty = System.getProperty("index"); if (indexProperty != null) { try { index = Boolean.valueOf(indexProperty); } catch (Exception e) { // ignore } } String splitProperty = System.getProperty("split"); if (splitProperty != null) { try { split = Boolean.valueOf(splitProperty); } catch (Exception e) { // ignore } } Path mainIndexPath = Paths.get(INDEX + "/original"); Directory directory = FSDirectory.open(mainIndexPath); Path trainPath = Paths.get(INDEX + "/train"); Path testPath = Paths.get(INDEX + "/test"); Path cvPath = Paths.get(INDEX + "/cv"); FSDirectory cv = null; FSDirectory test = null; FSDirectory train = null; DirectoryReader testReader = null; if (split) { cv = FSDirectory.open(cvPath); test = FSDirectory.open(testPath); train = FSDirectory.open(trainPath); } if (index) { delete(mainIndexPath); if (split) { delete(trainPath, testPath, cvPath); } } IndexReader reader = null; try { Analyzer analyzer = new StandardAnalyzer(); if (index) { System.out.format("Indexing 20 Newsgroups...%n"); long startIndex = System.currentTimeMillis(); IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(analyzer)); buildIndex(new File(PREFIX + "/20n/20_newsgroups"), indexWriter); long endIndex = System.currentTimeMillis(); System.out.format("Indexed %d pages in %ds %n", indexWriter.maxDoc(), (endIndex - startIndex) / 1000); indexWriter.close(); } if (split && !index) { reader = DirectoryReader.open(train); } else { reader = DirectoryReader.open(directory); } if (index && split) { // split the index System.out.format("Splitting the index...%n"); long startSplit = System.currentTimeMillis(); DatasetSplitter datasetSplitter = new DatasetSplitter(0.1, 0); LeafReader originalIndex = SlowCompositeReaderWrapper.wrap(reader); datasetSplitter.split(originalIndex, train, test, cv, analyzer, false, CATEGORY_FIELD, BODY_FIELD, SUBJECT_FIELD, CATEGORY_FIELD); reader.close(); reader = DirectoryReader.open(train); // using the train index from now on long endSplit = System.currentTimeMillis(); System.out.format("Splitting done in %ds %n", (endSplit - startSplit) / 1000); } final LeafReader ar = SlowCompositeReaderWrapper.wrap(reader); final long startTime = System.currentTimeMillis(); List<Classifier<BytesRef>> classifiers = new LinkedList<>(); classifiers.add(new KNearestNeighborClassifier(ar, new ClassicSimilarity(), analyzer, null, 1, 0, 0, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new ClassicSimilarity(), analyzer, null, 3, 0, 0, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new ClassicSimilarity(), analyzer, null, 3, 2, 4, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new LMDirichletSimilarity(), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new LMJelinekMercerSimilarity(0.3f), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new BM25Similarity(), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new DFRSimilarity(new BasicModelG(), new AfterEffectB(), new NormalizationH1()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH3()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new IBSimilarity(new DistributionSPL(), new LambdaDF(), new Normalization.NoNormalization()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new IBSimilarity(new DistributionLL(), new LambdaTTF(), new NormalizationH1()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new CachingNaiveBayesClassifier(ar, analyzer, null, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new SimpleNaiveBayesClassifier(ar, analyzer, null, CATEGORY_FIELD, BODY_FIELD)); int maxdoc; LeafReader testLeafReader; if (split) { testReader = DirectoryReader.open(test); testLeafReader = SlowCompositeReaderWrapper.wrap(testReader); maxdoc = testReader.maxDoc(); } else { testLeafReader = null; maxdoc = reader.maxDoc(); } System.out.format("Starting evaluation on %d docs...%n", maxdoc); ExecutorService service = Executors.newCachedThreadPool(); List<Future<String>> futures = new LinkedList<>(); for (Classifier<BytesRef> classifier : classifiers) { futures.add(service.submit(() -> { ConfusionMatrixGenerator.ConfusionMatrix confusionMatrix; if (split) { confusionMatrix = ConfusionMatrixGenerator.getConfusionMatrix(testLeafReader, classifier, CATEGORY_FIELD, BODY_FIELD); } else { confusionMatrix = ConfusionMatrixGenerator.getConfusionMatrix(ar, classifier, CATEGORY_FIELD, BODY_FIELD); } final long endTime = System.currentTimeMillis(); final int elapse = (int) (endTime - startTime) / 1000; System.out.println(confusionMatrix.getLinearizedMatrix().size() + " classes"); System.out.format("Generated confusion matrix:\n %s \n in %ds %n", confusionMatrix.toString(), elapse); return classifier + " -> *** accuracy = " + confusionMatrix.getAccuracy() + "; precision = " + confusionMatrix.getPrecision() + "; recall = " + confusionMatrix.getRecall() + "; f1-measure = " + confusionMatrix.getF1Measure() + "; avgClassificationTime = " + confusionMatrix.getAvgClassificationTime() + "; time = " + elapse + " (sec)\n "; })); } for (Future<String> f : futures) { System.out.println(f.get()); } Thread.sleep(10000); service.shutdown(); } finally { if (reader != null) { reader.close(); } directory.close(); if (test != null) { test.close(); } if (train != null) { train.close(); } if (cv != null) { cv.close(); } if (testReader != null) { testReader.close(); } } } private void delete(Path... paths) throws IOException { for (Path path : paths) { if (Files.isDirectory(path)) { Stream<Path> pathStream = Files.list(path); Iterator<Path> iterator = pathStream.iterator(); while (iterator.hasNext()) { Files.delete(iterator.next()); } } } } void buildIndex(File indexDir, IndexWriter indexWriter) throws IOException { File[] groupsDir = indexDir.listFiles(); if (groupsDir != null) { for (File group : groupsDir) { String groupName = group.getName(); File[] posts = group.listFiles(); if (posts != null) { for (File postFile : posts) { String number = postFile.getName(); NewsPost post = parse(postFile, groupName, number); Document d = new Document(); d.add(new TextField(CATEGORY_FIELD, post.getGroup(), Field.Store.YES)); d.add(new TextField(SUBJECT_FIELD, post.getSubject(), Field.Store.YES)); d.add(new TextField(BODY_FIELD, post.getBody(), Field.Store.YES)); indexWriter.addDocument(d); } } } } indexWriter.commit(); } private NewsPost parse(File postFile, String groupName, String number) throws IOException { StringBuilder body = new StringBuilder(); String subject = ""; FileInputStream stream = new FileInputStream(postFile); boolean inBody = false; for (String line : IOUtils.readLines(stream)) { if (line.startsWith("Subject:")) { subject = line.substring(8); } else { if (inBody) { if (body.length() > 0) { body.append("\n"); } body.append(line); } else if (line.isEmpty() || line.trim().length() == 0) { inBody = true; } } } return new NewsPost(body.toString(), subject, groupName, number); } private class NewsPost { private final String body; private final String subject; private final String group; private final String number; private NewsPost(String body, String subject, String group, String number) { this.body = body; this.subject = subject; this.group = group; this.number = number; } public String getBody() { return body; } public String getSubject() { return subject; } public String getGroup() { return group; } public String getNumber() { return number; } } }
looseen/src/test/java/com/github/tteofili/looseen/Test20NewsgroupsClassification.java
package com.github.tteofili.looseen; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.classification.CachingNaiveBayesClassifier; import org.apache.lucene.classification.Classifier; import org.apache.lucene.classification.KNearestNeighborClassifier; import org.apache.lucene.classification.SimpleNaiveBayesClassifier; import org.apache.lucene.classification.utils.ConfusionMatrixGenerator; import org.apache.lucene.classification.utils.DatasetSplitter; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.SlowCompositeReaderWrapper; import org.apache.lucene.search.similarities.AfterEffectB; import org.apache.lucene.search.similarities.AfterEffectL; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.search.similarities.BasicModelG; import org.apache.lucene.search.similarities.BasicModelP; import org.apache.lucene.search.similarities.ClassicSimilarity; import org.apache.lucene.search.similarities.DFRSimilarity; import org.apache.lucene.search.similarities.DistributionLL; import org.apache.lucene.search.similarities.DistributionSPL; import org.apache.lucene.search.similarities.IBSimilarity; import org.apache.lucene.search.similarities.LMDirichletSimilarity; import org.apache.lucene.search.similarities.LMJelinekMercerSimilarity; import org.apache.lucene.search.similarities.LambdaDF; import org.apache.lucene.search.similarities.LambdaTTF; import org.apache.lucene.search.similarities.Normalization; import org.apache.lucene.search.similarities.NormalizationH1; import org.apache.lucene.search.similarities.NormalizationH3; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; import org.junit.Test; @LuceneTestCase.SuppressSysoutChecks(bugUrl = "none") public final class Test20NewsgroupsClassification extends LuceneTestCase { private static final String PREFIX = "/Users/teofili/data"; private static final String INDEX = PREFIX + "/20n/index"; private static final String CATEGORY_FIELD = "category"; private static final String BODY_FIELD = "body"; private static final String SUBJECT_FIELD = "subject"; private static boolean index = false; private static boolean split = true; @Test public void test20Newsgroups() throws Exception { String indexProperty = System.getProperty("index"); if (indexProperty != null) { try { index = Boolean.valueOf(indexProperty); } catch (Exception e) { // ignore } } String splitProperty = System.getProperty("split"); if (splitProperty != null) { try { split = Boolean.valueOf(splitProperty); } catch (Exception e) { // ignore } } Path mainIndexPath = Paths.get(INDEX + "/original"); Directory directory = FSDirectory.open(mainIndexPath); Path trainPath = Paths.get(INDEX + "/train"); Path testPath = Paths.get(INDEX + "/test"); Path cvPath = Paths.get(INDEX + "/cv"); FSDirectory cv = null; FSDirectory test = null; FSDirectory train = null; DirectoryReader testReader = null; if (split) { cv = FSDirectory.open(cvPath); test = FSDirectory.open(testPath); train = FSDirectory.open(trainPath); } if (index) { delete(mainIndexPath); if (split) { delete(trainPath, testPath, cvPath); } } IndexReader reader = null; try { Analyzer analyzer = new StandardAnalyzer(); if (index) { System.out.format("Indexing 20 Newsgroups...%n"); long startIndex = System.currentTimeMillis(); IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(analyzer)); buildIndex(new File(PREFIX + "/20n/20_newsgroups"), indexWriter); long endIndex = System.currentTimeMillis(); System.out.format("Indexed %d pages in %ds %n", indexWriter.maxDoc(), (endIndex - startIndex) / 1000); indexWriter.close(); } if (split && !index) { reader = DirectoryReader.open(train); } else { reader = DirectoryReader.open(directory); } if (index && split) { // split the index System.out.format("Splitting the index...%n"); long startSplit = System.currentTimeMillis(); DatasetSplitter datasetSplitter = new DatasetSplitter(0.1, 0); LeafReader originalIndex = SlowCompositeReaderWrapper.wrap(reader); datasetSplitter.split(originalIndex, train, test, cv, analyzer, false, "title", BODY_FIELD, SUBJECT_FIELD, CATEGORY_FIELD); reader.close(); reader = DirectoryReader.open(train); // using the train index from now on long endSplit = System.currentTimeMillis(); System.out.format("Splitting done in %ds %n", (endSplit - startSplit) / 1000); } final LeafReader ar = SlowCompositeReaderWrapper.wrap(reader); final long startTime = System.currentTimeMillis(); List<Classifier<BytesRef>> classifiers = new LinkedList<>(); classifiers.add(new KNearestNeighborClassifier(ar, new ClassicSimilarity(), analyzer, null, 1, 0, 0, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new ClassicSimilarity(), analyzer, null, 3, 0, 0, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new ClassicSimilarity(), analyzer, null, 3, 2, 4, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new LMDirichletSimilarity(), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new LMJelinekMercerSimilarity(0.3f), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new BM25Similarity(), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new DFRSimilarity(new BasicModelG(), new AfterEffectB(), new NormalizationH1()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH3()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new IBSimilarity(new DistributionSPL(), new LambdaDF(), new Normalization.NoNormalization()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new KNearestNeighborClassifier(ar, new IBSimilarity(new DistributionLL(), new LambdaTTF(), new NormalizationH1()), analyzer, null, 3, 1, 1, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new CachingNaiveBayesClassifier(ar, analyzer, null, CATEGORY_FIELD, BODY_FIELD)); classifiers.add(new SimpleNaiveBayesClassifier(ar, analyzer, null, CATEGORY_FIELD, BODY_FIELD)); int maxdoc; LeafReader testLeafReader; if (split) { testReader = DirectoryReader.open(test); testLeafReader = SlowCompositeReaderWrapper.wrap(testReader); maxdoc = testReader.maxDoc(); } else { testLeafReader = null; maxdoc = reader.maxDoc(); } System.out.format("Starting evaluation on %d docs...%n", maxdoc); ExecutorService service = Executors.newCachedThreadPool(); List<Future<String>> futures = new LinkedList<>(); for (Classifier<BytesRef> classifier : classifiers) { futures.add(service.submit(() -> { ConfusionMatrixGenerator.ConfusionMatrix confusionMatrix; if (split) { confusionMatrix = ConfusionMatrixGenerator.getConfusionMatrix(testLeafReader, classifier, CATEGORY_FIELD, BODY_FIELD); } else { confusionMatrix = ConfusionMatrixGenerator.getConfusionMatrix(ar, classifier, CATEGORY_FIELD, BODY_FIELD); } final long endTime = System.currentTimeMillis(); final int elapse = (int) (endTime - startTime) / 1000; System.out.println(confusionMatrix.getLinearizedMatrix().size() + " classes"); System.out.format("Generated confusion matrix:\n %s \n in %ds %n", confusionMatrix.toString(), elapse); return classifier + " -> *** accuracy = " + confusionMatrix.getAccuracy() + "; precision = " + confusionMatrix.getPrecision() + "; recall = " + confusionMatrix.getRecall() + "; f1-measure = " + confusionMatrix.getF1Measure() + "; avgClassificationTime = " + confusionMatrix.getAvgClassificationTime() + "; time = " + elapse + " (sec)\n "; })); } for (Future<String> f : futures) { System.out.println(f.get()); } Thread.sleep(10000); service.shutdown(); } finally { if (reader != null) { reader.close(); } directory.close(); if (test != null) { test.close(); } if (train != null) { train.close(); } if (cv != null) { cv.close(); } if (testReader != null) { testReader.close(); } } } private void delete(Path... paths) throws IOException { for (Path path : paths) { if (Files.isDirectory(path)) { Stream<Path> pathStream = Files.list(path); Iterator<Path> iterator = pathStream.iterator(); while (iterator.hasNext()) { Files.delete(iterator.next()); } } } } void buildIndex(File indexDir, IndexWriter indexWriter) throws IOException { File[] groupsDir = indexDir.listFiles(); if (groupsDir != null) { for (File group : groupsDir) { String groupName = group.getName(); File[] posts = group.listFiles(); if (posts != null) { for (File postFile : posts) { String number = postFile.getName(); NewsPost post = parse(postFile, groupName, number); Document d = new Document(); d.add(new TextField(CATEGORY_FIELD, post.getGroup(), Field.Store.YES)); d.add(new TextField(SUBJECT_FIELD, post.getSubject(), Field.Store.YES)); d.add(new TextField(BODY_FIELD, post.getBody(), Field.Store.YES)); indexWriter.addDocument(d); } } } } indexWriter.commit(); } private NewsPost parse(File postFile, String groupName, String number) throws IOException { StringBuilder body = new StringBuilder(); String subject = ""; FileInputStream stream = new FileInputStream(postFile); boolean inBody = false; for (String line : IOUtils.readLines(stream)) { if (line.startsWith("Subject:")) { subject = line.substring(8); } else { if (inBody) { if (body.length() > 0) { body.append("\n"); } body.append(line); } else if (line.isEmpty() || line.trim().length() == 0) { inBody = true; } } } return new NewsPost(body.toString(), subject, groupName, number); } private class NewsPost { private final String body; private final String subject; private final String group; private final String number; private NewsPost(String body, String subject, String group, String number) { this.body = body; this.subject = subject; this.group = group; this.number = number; } public String getBody() { return body; } public String getSubject() { return subject; } public String getGroup() { return group; } public String getNumber() { return number; } } }
adjusting data splitter usage
looseen/src/test/java/com/github/tteofili/looseen/Test20NewsgroupsClassification.java
adjusting data splitter usage
<ide><path>ooseen/src/test/java/com/github/tteofili/looseen/Test20NewsgroupsClassification.java <ide> long startSplit = System.currentTimeMillis(); <ide> DatasetSplitter datasetSplitter = new DatasetSplitter(0.1, 0); <ide> LeafReader originalIndex = SlowCompositeReaderWrapper.wrap(reader); <del> datasetSplitter.split(originalIndex, train, test, cv, analyzer, false, "title", BODY_FIELD, SUBJECT_FIELD, CATEGORY_FIELD); <add> datasetSplitter.split(originalIndex, train, test, cv, analyzer, false, CATEGORY_FIELD, BODY_FIELD, SUBJECT_FIELD, CATEGORY_FIELD); <ide> reader.close(); <ide> reader = DirectoryReader.open(train); // using the train index from now on <ide> long endSplit = System.currentTimeMillis();
JavaScript
mit
7ebb7e38a81855a50ccb22bbb9a3ee344e313fc5
0
assetize/madagascar
#!/usr/bin/env node var web3 = require("web3"), fs = require("fs"); var cFile = process.argv[2]; if(!cFile){ usage(); process.exit(); } web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545')); var cCode = fs.readFileSync(cFile).toString(), compiled = web3.eth.compile.solidity(cCode); console.log("ABI:",JSON.stringify(compiled.info.abiDefinition, null, 2)); //TODO: calculate total cost and ask to confirm web3.eth.sendTransaction({ from: web3.eth.coinbase, data: compiled.code, gas: "1000000", gasPrice: web3.eth.gasPrice.toString() }, function(err, addr){ if(err) throw err; console.log("Deploying contract at:", addr); web3.eth.filter("latest", { address: addr }).watch(function(){ if(web3.eth.getCode(addr).length > 2){ console.log("Contract deployed successfully"); process.exit(); }else{ console.log("Not deployed yet, waiting for the next block ..."); } }); }); function usage(){ console.log("Usage:" + "$deploy_contract.js <path-to-contract>"); }
script/deploy-contract.js
#!/usr/bin/env node var web3 = require("web3"), fs = require("fs"); var cFile = process.argv[2]; if(!cFile){ usage(); process.exit(); } web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545')); var cCode = fs.readFileSync(cFile).toString(), compiled = web3.eth.compile.solidity(cCode); console.log("ABI:",JSON.stringify(compiled.info.abiDefinition, null, 2)); var block = web3.eth.blockNumber; web3.eth.sendTransaction({ from: web3.eth.coinbase, data: compiled.code, gas: "1000000", gasPrice: "10000" }, function(err, addr){ if(err) throw err; console.log("Deploying contract at:", addr); web3.eth.filter("latest", { address: addr }).watch(function(){ if(web3.eth.getCode(addr).length > 2){ console.log("Contract deployed successfully"); process.exit(); }else{ console.log("Not deployed yet, waiting for the next block ..."); } }); }); function usage(){ console.log("Usage:" + "$deploy_contract.js <path-to-contract>"); }
dynamically getting gasPrice
script/deploy-contract.js
dynamically getting gasPrice
<ide><path>cript/deploy-contract.js <ide> <ide> console.log("ABI:",JSON.stringify(compiled.info.abiDefinition, null, 2)); <ide> <del>var block = web3.eth.blockNumber; <del> <add>//TODO: calculate total cost and ask to confirm <ide> <ide> web3.eth.sendTransaction({ <ide> from: web3.eth.coinbase, <ide> data: compiled.code, <ide> gas: "1000000", <del> gasPrice: "10000" <add> gasPrice: web3.eth.gasPrice.toString() <ide> }, function(err, addr){ <ide> if(err) throw err; <ide> console.log("Deploying contract at:", addr);
JavaScript
agpl-3.0
5e36026347fa6b57b1bc8082ee74b675bdc535d0
0
inaes-tic/mbc-mosto
var config = require("mbc-common").config.Mosto.Mongo, Playlist = require('../../api/Playlist'), Media = require('../../api/Media'), mubsub = require("mubsub"), moment = require("moment"), mbc = require('mbc-common'), async = require('async'), events = require ('events'), util = require ('util'), _ = require('underscore'); function drop_err(callback, err_handler) { return function(err,v) { if( !err ) callback(v); else if( err_handler ) err_handler(err); }; } function mongo_driver(conf) { var self = this; events.EventEmitter.call (this); this.window = {}; console.log("mongo-driver: [INFO] Creating mongodb playlists driver"); mongo_driver.prototype.start = function(timeSpan) { var db = mbc.db(conf && conf.db); var channel = mbc.pubsub(); console.log("mongo-driver: [INFO] Starting mongo playlists driver"); self.scheds = db.collection('scheds'); self.lists = db.collection('lists'); self.setWindow({timeSpan: timeSpan}); channel.subscribe({backend: 'schedbackend', method: 'create'}, function(msg) { if( self.inTime(msg.model) ) { self.createPlaylist(msg.model, 'create'); } }); channel.subscribe({backend: 'schedbackend', method: 'update'}, function(msg) { // I forward all create messages self.createPlaylist(msg.model, 'update'); }); channel.subscribe({backend: 'schedbackend', method: 'delete'}, function(msg) { self.emit ("delete", msg.model._id); }); }; mongo_driver.prototype.getWindow = function(from, to) { // Notice that if from = to = undefined then time window is // set to undefined, and settings file is used again if( to === undefined ) { if( from === undefined ) { // use defaults from config file var now = moment(new Date()); var until = moment(new Date()); var timeSpan = config.load_time * 60 * 1000; until.add(timeSpan); return { from: now, to: until, timeSpan: timeSpan }; } else { // assume from = { from: date, to: date } var window = from; var ret = _.clone(window); if( window.from === undefined ) { // I assume from = now ret.from = new moment(); } else { ret.from = moment(window.from); } if( !(window.to || window.timeSpan) ) { // if neither is present, we use the currently set // value, or default to the config file ret.timeSpan = self.window.timeSpan || config.load_time * 60 * 1000; } if( window.to === undefined ) { // we asume timeSpan is present and calculate it ret.to = new moment(ret.from); ret.to.add(ret.timeSpan); } else { ret.to = moment(window.to); } if( ret.timeSpan === undefined ) { // if we got here, it means window.to was defined // we calculate it using from and to ret.timeSpan = ret.to.diff(ret.from); } else { // this got copied in the _.clone, but it's in minutes ret.timeSpan = window.timeSpan * 60 * 1000; } return ret; } } else { var window = { from: moment(from), to: moment(to), }; window.timeSpan = window.to.diff(window.from); return window; } }; mongo_driver.prototype.setWindow = function(from, to) { self.window = self.getWindow(from, to); return self.window; }; mongo_driver.prototype.inTime = function(sched) { var window = self.getWindow(); return (sched.start <= window.to.unix() && sched.end >= window.from.unix()); }; mongo_driver.prototype.getPlaylists = function(ops, callback) { // read playlists from the database /* * This gets the database's 'scheds' and 'lists' collections * and turn them into a mosto.api.Playlist. Then return one by one to callback * which defaults to self.newPlaylistCallback */ var window; if (ops == undefined) { window = self.getWindow(); } else if ( ops.setWindow ) { window = self.setWindow(ops.from, ops.to); } else { window = self.getWindow(ops.from, ops.to); } console.log("mongo-driver: [INFO] getPlaylists" + window); self.scheds.findItems({ start: { $lte: window.to.unix()}, end: { $gte: window.from.unix() } }, function(err, scheds) { if( err ) { console.log(err); } else if( scheds ) { console.log("Processing sched list:", scheds); async.map(scheds, self.createPlaylist, function(err, playlists) { if( callback ) callback(playlists); else playlists.forEach(function(playlist) { self.emit ("create", playlist); }); }); } else { console.log('Done'); } }); }; mongo_driver.prototype.createPlaylist = function(sched, method) { // method can be either an event name to emit, or a callback. // If it's a callback, no signal will be emitted (except 'error') var callback = undefined; if( typeof(method) == 'function' ) { callback = method; } console.log("mongo-driver: [INFO] Create Playlist:", sched); self.lists.findById(sched.list, function(err, list) { if( err ) { self.emit ("error", err); if( callback ) callback(err); return err; } console.log("mongo-driver: [INFO] Processing list:", list); var startDate = new Date(sched.start * 1000); var endDate = new Date(sched.end * 1000); var name = sched.title; var playlist_id = (sched._id.toHexString && sched._id.toHexString()) || sched._id; var medias = []; list.models.forEach(function(block, order) { var block_id = (block._id.toHexString && block._id.toHexString()) || block._id; var orig_order = order; var actual_order = undefined; var clip_name = block.name; // TODO: don't know what goes in type var type = "default"; var file = block.file; var length = block.durationraw; var fps = block.fps; medias.push(new Media(block_id, orig_order, actual_order, playlist_id, clip_name, type, file, length, parseFloat(fps))); }); var playlist = new Playlist(playlist_id, name, startDate, medias, endDate, "snap"); if( callback ) callback(err, playlist); else self.emit(method, playlist); }); }; } exports = module.exports = function(conf) { util.inherits (mongo_driver, events.EventEmitter); var driver = new mongo_driver(conf); return driver; };
drivers/playlists/mongo-driver.js
var config = require("mbc-common").config.Mosto.Mongo, Playlist = require('../../api/Playlist'), Media = require('../../api/Media'), mubsub = require("mubsub"), moment = require("moment"), mbc = require('mbc-common'), async = require('async'), events = require ('events'), util = require ('util'), _ = require('underscore'); function drop_err(callback, err_handler) { return function(err,v) { if( !err ) callback(v); else if( err_handler ) err_handler(err); }; } function mongo_driver(conf) { var self = this; events.EventEmitter.call (this); this.window = {}; console.log("mongo-driver: [INFO] Creating mongodb playlists driver"); mongo_driver.prototype.start = function(timeSpan) { var db = mbc.db(conf && conf.db); var channel = mbc.pubsub(); console.log("mongo-driver: [INFO] Starting mongo playlists driver"); self.scheds = db.collection('scheds'); self.lists = db.collection('lists'); self.setWindow({timeSpan: timeSpan}); channel.subscribe({backend: 'schedbackend', method: 'create'}, function(msg) { if( self.inTime(msg.model) ) { self.createPlaylist(msg.model, 'create'); } }); channel.subscribe({backend: 'schedbackend', method: 'update'}, function(msg) { // I forward all create messages self.createPlaylist(msg.model, 'update'); }); channel.subscribe({backend: 'schedbackend', method: 'delete'}, function(msg) { self.emit ("delete", msg.model._id); }); }; mongo_driver.prototype.getWindow = function(from, to) { // Notice that if from = to = undefined then time window is // set to undefined, and settings file is used again if( to === undefined ) { if( from === undefined ) { // use defaults from config file var now = moment(new Date()); var until = moment(new Date()); var timeSpan = config.load_time * 60 * 1000; until.add(timeSpan); return { from: now, to: until, timeSpan: timeSpan }; } else { // assume from = { from: date, to: date } var window = from; var ret = _.clone(window); if( window.from === undefined ) { // I assume from = now ret.from = new moment(); } else { ret.from = moment(window.from); } if( !(window.to || window.timeSpan) ) { // if neither is present, we use the currently set // value, or default to the config file ret.timeSpan = self.window.timeSpan || config.load_time * 60 * 1000; } if( window.to === undefined ) { // we asume timeSpan is present and calculate it ret.to = new moment(ret.from); ret.to.add(ret.timeSpan); } else { ret.to = moment(window.to); } if( ret.timeSpan === undefined ) { // if we got here, it means window.to was defined // we calculate it using from and to ret.timeSpan = ret.to.diff(ret.from); } else { // this got copied in the _.clone, but it's in minutes ret.timeSpan = window.timeSpan * 60 * 1000; } return ret; } } else { var window = { from: moment(from), to: moment(to), }; window.timeSpan = window.to.diff(window.from); return window; } }; mongo_driver.prototype.setWindow = function(from, to) { self.window = self.getWindow(from, to); return self.window; }; mongo_driver.prototype.inTime = function(sched) { var window = self.getWindow(); return (sched.start <= window.to.unix() && sched.end >= window.from.unix()); }; mongo_driver.prototype.getPlaylists = function(ops, callback) { // read playlists from the database /* * This gets the database's 'scheds' and 'lists' collections * and turn them into a mosto.api.Playlist. Then return one by one to callback * which defaults to self.newPlaylistCallback */ var window; if (ops == undefined) { window = self.getWindow(); } else if ( ops.setWindow ) { window = self.setWindow(ops.from, ops.to); } else { window = self.getWindow(ops.from, ops.to); } console.log("mongo-driver: [INFO] getPlaylists" + window); self.scheds.findItems({ start: { $lte: window.to.unix()}, end: { $gte: window.from.unix() } }, function(err, scheds) { if( err ) { console.log(err); } else if( scheds ) { console.log("Processing sched list:", scheds); async.map(scheds, self.createPlaylist, function(err, playlists) { if( callback ) callback(playlists); else playlists.forEach(function(playlist) { self.emit ("create", playlist); }); }); } else { console.log('Done'); } }); }; mongo_driver.prototype.createPlaylist = function(sched, callback, method) { console.log("mongo-driver: [INFO] Create Playlist:", sched); self.lists.findById(sched.list, function(err, list) { if( err ) { self.emit ("error", err); if( callback ) callback(err); return err; } console.log("mongo-driver: [INFO] Processing list:", list); var startDate = new Date(sched.start * 1000); var endDate = new Date(sched.end * 1000); var name = sched.title; var playlist_id = (sched._id.toHexString && sched._id.toHexString()) || sched._id; var medias = []; list.models.forEach(function(block, order) { var block_id = (block._id.toHexString && block._id.toHexString()) || block._id; var orig_order = order; var actual_order = undefined; var clip_name = block.name; // TODO: don't know what goes in type var type = "default"; var file = block.file; var length = block.durationraw; var fps = block.fps; medias.push(new Media(block_id, orig_order, actual_order, playlist_id, clip_name, type, file, length, parseFloat(fps))); }); var playlist = new Playlist(playlist_id, name, startDate, medias, endDate, "snap"); self.emit (method, playlist); if( callback ) callback(err, playlist); else return playlist; }); }; } exports = module.exports = function(conf) { util.inherits (mongo_driver, events.EventEmitter); var driver = new mongo_driver(conf); return driver; };
allow for "method" to be either an event name or a function Signed-off-by: Tomas Neme <[email protected]>
drivers/playlists/mongo-driver.js
allow for "method" to be either an event name or a function
<ide><path>rivers/playlists/mongo-driver.js <ide> }); <ide> }; <ide> <del> mongo_driver.prototype.createPlaylist = function(sched, callback, method) { <add> mongo_driver.prototype.createPlaylist = function(sched, method) { <add> // method can be either an event name to emit, or a callback. <add> // If it's a callback, no signal will be emitted (except 'error') <add> var callback = undefined; <add> if( typeof(method) == 'function' ) { <add> callback = method; <add> } <add> <ide> console.log("mongo-driver: [INFO] Create Playlist:", sched); <ide> self.lists.findById(sched.list, function(err, list) { <ide> if( err ) { <ide> }); <ide> <ide> var playlist = new Playlist(playlist_id, name, startDate, medias, endDate, "snap"); <del> self.emit (method, playlist); <ide> <ide> if( callback ) <ide> callback(err, playlist); <ide> else <del> return playlist; <add> self.emit(method, playlist); <ide> }); <ide> }; <ide> }
JavaScript
mit
ad508af670f2bafdf33007c51a73ca760a6f85d0
0
2Rainbow/Dollchan-Extension-Tools,miku-nyan/Dollchan-Extension-Tools,SthephanShinkufag/Dollchan-Extension-Tools,lisanyan/Dollchan-Extension-Tools,SthephanShinkufag/Dollchan-Extension-Tools,wakaber/Dollchan-Extension-Tools,aslian/Dollchan-Extension-Tools,Y0ba/Dollchan-Extension-Tools,Y0ba/Dollchan-Extension-Tools
// ==UserScript== // @name Dollchan Extension Tools // @version 14.7.25.0 // @namespace http://www.freedollchan.org/scripts/* // @author Sthephan Shinkufag @ FreeDollChan // @copyright (C)2084, Bender Bending Rodriguez // @description Doing some profit for imageboards // @icon https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Icon.png // @updateURL https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js // @run-at document-start // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_openInTab // @grant GM_xmlhttpRequest // @grant GM_log // @grant unsafeWindow // @include * // ==/UserScript== (function de_main_func(scriptStorage) { 'use strict'; var version = '14.7.25.0', defaultCfg = { 'disabled': 0, // script enabled by default 'language': 0, // script language [0=ru, 1=en] 'hideBySpell': 1, // hide posts by spells 'spells': '', // user defined spells 'sortSpells': 0, // sort spells when applying 'menuHiddBtn': 1, // menu on hide button 'hideRefPsts': 0, // hide post with references to hidden posts 'delHiddPost': 0, // delete hidden posts 'ajaxUpdThr': 1, // auto update threads 'updThrDelay': 60, // threads update interval in sec 'noErrInTitle': 0, // don't show error number in title except 404 'favIcoBlink': 0, // favicon blinking, if new posts detected 'markNewPosts': 1, // new posts marking on page focus 'desktNotif': 0, // desktop notifications, if new posts detected 'expandPosts': 2, // expand shorted posts [0=off, 1=auto, 2=on click] 'postBtnsCSS': 2, // post buttons style [0=text, 1=classic, 2=solid grey] 'noSpoilers': 1, // open spoilers 'noPostNames': 0, // hide post names 'noPostScrl': 1, // no scroll in posts 'correctTime': 0, // correct time in posts 'timeOffset': '+0', // offset in hours 'timePattern': '', // find pattern 'timeRPattern': '', // replace pattern 'expandImgs': 2, // expand images by click [0=off, 1=in post, 2=by center] 'resizeImgs': 1, // resize large images 'webmControl': 1, // control bar fow webm files 'webmVolume': 100, // default volume for webm files 'maskImgs': 0, // mask images 'preLoadImgs': 0, // pre-load images 'findImgFile': 0, // detect built-in files in images 'openImgs': 0, // open images in posts 'openGIFs': 0, // open only GIFs in posts 'imgSrcBtns': 1, // add image search buttons 'linksNavig': 2, // navigation by >>links [0=off, 1=no map, 2=+refmap] 'linksOver': 100, // delay appearance in ms 'linksOut': 1500, // delay disappearance in ms 'markViewed': 0, // mark viewed posts 'strikeHidd': 0, // strike >>links to hidden posts 'noNavigHidd': 0, // don't show previews for hidden posts 'crossLinks': 0, // replace http: to >>/b/links 'insertNum': 1, // insert >>link on postnumber click 'addMP3': 1, // embed mp3 links 'addImgs': 0, // embed links to images 'addYouTube': 3, // embed YouTube links [0=off, 1=onclick, 2=player, 3=preview+player, 4=only preview] 'YTubeType': 0, // player type [0=flash, 1=HTML5] 'YTubeWidth': 360, // player width 'YTubeHeigh': 270, // player height 'YTubeHD': 0, // hd video quality 'YTubeTitles': 0, // convert links to titles 'addVimeo': 1, // embed vimeo links 'ajaxReply': 2, // posting with AJAX (0=no, 1=iframe, 2=HTML5) 'postSameImg': 1, // ability to post same images 'removeEXIF': 1, // remove EXIF data from JPEGs 'removeFName': 0, // remove file name 'sendErrNotif': 1, // inform about post send error if page is blurred 'scrAfterRep': 0, // scroll to the bottom after reply 'addPostForm': 2, // postform displayed [0=at top, 1=at bottom, 2=hidden, 3=hanging] 'favOnReply': 1, // add thread to favorites on reply 'warnSubjTrip': 0, // warn if subject field contains tripcode 'fileThumb': 1, // file preview area instead of file button 'addSageBtn': 1, // email field -> sage button 'saveSage': 1, // remember sage 'sageReply': 0, // reply with sage 'captchaLang': 1, // language input in captcha [0=off, 1=en, 2=ru] 'addTextBtns': 1, // text format buttons [0=off, 1=graphics, 2=text, 3=usual] 'txtBtnsLoc': 0, // located at [0=top, 1=bottom] 'passwValue': '', // user password value 'userName': 0, // user name 'nameValue': '', // value 'noBoardRule': 1, // hide board rules 'noGoto': 1, // hide goto field 'noPassword': 1, // hide password field 'scriptStyle': 0, // script style [0=glass black, 1=glass blue, 2=solid grey] 'userCSS': 0, // user style 'userCSSTxt': '', // css text 'expandPanel': 0, // show full main panel 'attachPanel': 1, // attach main panel 'panelCounter': 1, // posts/images counter in script panel 'rePageTitle': 1, // replace page title in threads 'animation': 1, // CSS3 animation in script 'closePopups': 0, // auto-close popups 'keybNavig': 1, // keyboard navigation 'loadPages': 1, // number of pages that are loaded on F5 'updScript': 1, // check for script's update 'scrUpdIntrv': 1, // check interval in days (every val+1 day) 'turnOff': 0, // enable script only for this site 'textaWidth': 500, // textarea width 'textaHeight': 160 // textarea height }, Lng = { cfg: { 'hideBySpell': ['Заклинания: ', 'Magic spells: '], 'sortSpells': ['Сортировать спеллы и удалять дубликаты', 'Sort spells and delete duplicates'], 'menuHiddBtn': ['Дополнительное меню кнопок скрытия ', 'Additional menu of hide buttons'], 'hideRefPsts': ['Скрывать ответы на скрытые посты*', 'Hide replies to hidden posts*'], 'delHiddPost': ['Удалять скрытые посты', 'Delete hidden posts'], 'ajaxUpdThr': ['AJAX обновление треда ', 'AJAX thread update '], 'updThrDelay': [' (сек)', ' (sec)'], 'noErrInTitle': ['Не показывать номер ошибки в заголовке', 'Don\'t show error number in title'], 'favIcoBlink': ['Мигать фавиконом при новых постах', 'Favicon blinking on new posts'], 'markNewPosts': ['Выделять новые посты при переключении на тред', 'Mark new posts on page focus'], 'desktNotif': ['Уведомления на рабочем столе', 'Desktop notifications'], 'expandPosts': { sel: [['Откл.', 'Авто', 'По клику'], ['Disable', 'Auto', 'On click']], txt: ['AJAX загрузка сокращенных постов*', 'AJAX upload of shorted posts*'] }, 'postBtnsCSS': { sel: [['Text', 'Classic', 'Solid grey'], ['Text', 'Classic', 'Solid grey']], txt: ['Стиль кнопок постов*', 'Post buttons style*'] }, 'noSpoilers': ['Открывать текстовые спойлеры', 'Open text spoilers'], 'noPostNames': ['Скрывать имена в постах', 'Hide names in posts'], 'noPostScrl': ['Без скролла в постах', 'No scroll in posts'], 'keybNavig': ['Навигация с помощью клавиатуры ', 'Navigation with keyboard '], 'loadPages': [' Количество страниц, загружаемых по F5', ' Number of pages that are loaded on F5 '], 'correctTime': ['Корректировать время в постах* ', 'Correct time in posts* '], 'timeOffset': [' Разница во времени', ' Time difference'], 'timePattern': [' Шаблон поиска', ' Find pattern'], 'timeRPattern': [' Шаблон замены', ' Replace pattern'], 'expandImgs': { sel: [['Откл.', 'В посте', 'По центру'], ['Disable', 'In post', 'By center']], txt: ['раскрывать изображения по клику', 'expand images on click'] }, 'resizeImgs': ['Уменьшать в экран большие изображения', 'Resize large images to fit screen'], 'webmControl': ['Показывать контрол-бар для webm-файлов', 'Show control bar for webm files'], 'webmVolume': [' Громкость webm-файлов [0-100]', ' Default volume for webm files [0-100]'], 'preLoadImgs': ['Предварительно загружать изображения*', 'Pre-load images*'], 'findImgFile': ['Распознавать встроенные файлы в изображениях*', 'Detect built-in files in images*'], 'openImgs': ['Скачивать полные версии изображений*', 'Download full version of images*'], 'openGIFs': ['Скачивать только GIFы*', 'Download GIFs only*'], 'imgSrcBtns': ['Добавлять кнопки для поиска изображений*', 'Add image search buttons*'], 'linksNavig': { sel: [['Откл.', 'Без карты', 'С картой'], ['Disable', 'No map', 'With map']], txt: ['навигация по >>ссылкам* ', 'navigation by >>links* '] }, 'linksOver': [' задержка появления (мс)', ' delay appearance (ms)'], 'linksOut': [' задержка пропадания (мс)', ' delay disappearance (ms)'], 'markViewed': ['Отмечать просмотренные посты*', 'Mark viewed posts*'], 'strikeHidd': ['Зачеркивать >>ссылки на скрытые посты', 'Strike >>links to hidden posts'], 'noNavigHidd': ['Не отображать превью для скрытых постов', 'Don\'t show previews for hidden posts'], 'crossLinks': ['Преобразовывать http:// в >>/b/ссылки*', 'Replace http:// with >>/b/links*'], 'insertNum': ['Вставлять >>ссылку по клику на №поста*', 'Insert >>link on №postnumber click*'], 'addMP3': ['Добавлять плейер к mp3 ссылкам* ', 'Add player to mp3 links* '], 'addVimeo': ['Добавлять плейер к Vimeo ссылкам* ', 'Add player to Vimeo links* '], 'addImgs': ['Загружать изображения к jpg, png, gif ссылкам*', 'Load images to jpg, png, gif links*'], 'addYouTube': { sel: [['Ничего', 'Плейер по клику', 'Авто плейер', 'Превью+плейер', 'Только превью'], ['Nothing', 'On click player', 'Auto player', 'Preview+player', 'Only preview']], txt: ['к YouTube-ссылкам* ', 'to YouTube-links* '] }, 'YTubeType': { sel: [['Flash', 'HTML5'], ['Flash', 'HTML5']], txt: ['', ''] }, 'YTubeHD': ['HD ', 'HD '], 'YTubeTitles': ['Загружать названия к YouTube-ссылкам*', 'Load titles into YouTube-links*'], 'ajaxReply': { sel: [['Откл.', 'Iframe', 'HTML5'], ['Disable', 'Iframe', 'HTML5']], txt: ['AJAX отправка постов*', 'posting with AJAX*'] }, 'postSameImg': ['Возможность отправки одинаковых изображений', 'Ability to post same images'], 'removeEXIF': ['Удалять EXIF из JPEG ', 'Remove EXIF from JPEG '], 'removeFName': ['Удалять имя из файлов', 'Remove names from files'], 'sendErrNotif': ['Оповещать в заголовке об ошибке отправки поста', 'Inform in title about post send error'], 'scrAfterRep': ['Перемещаться в конец треда после отправки', 'Scroll to the bottom after reply'], 'addPostForm': { sel: [['Сверху', 'Внизу', 'Скрытая', 'Отдельная'], ['At top', 'At bottom', 'Hidden', 'Hanging']], txt: ['форма ответа в треде* ', 'reply form in thread* '] }, 'favOnReply': ['Добавлять тред в избранное при ответе', 'Add thread to favorites on reply'], 'warnSubjTrip': ['Предупреждать при наличии трип-кода в поле "Тема"', 'Warn if "Subject" field contains trip-code'], 'fileThumb': ['Область превью картинок вместо кнопки "Файл"', 'File thumbnail area instead of "File" button'], 'addSageBtn': ['Кнопка Sage вместо поля "E-mail"* ', 'Sage button instead of "E-mail" field* '], 'saveSage': ['запоминать сажу', 'remember sage'], 'captchaLang': { sel: [['Откл.', 'Eng', 'Rus'], ['Disable', 'Eng', 'Rus']], txt: ['язык ввода капчи', 'language input in captcha'] }, 'addTextBtns': { sel: [['Откл.', 'Графич.', 'Упрощ.', 'Стандарт.'], ['Disable', 'As images', 'As text', 'Standard']], txt: ['кнопки форматирования текста ', 'text format buttons '] }, 'txtBtnsLoc': ['внизу', 'at bottom'], 'userPassw': [' Постоянный пароль ', ' Fixed password '], 'userName': ['Постоянное имя', 'Fixed name'], 'noBoardRule': ['правила', 'rules'], 'noGoto': ['поле goto', 'goto field'], 'noPassword': ['пароль', 'password'], 'scriptStyle': { sel: [['Glass black', 'Glass blue', 'Solid grey'], ['Glass black', 'Glass blue', 'Solid grey']], txt: ['стиль скрипта', 'script style'] }, 'userCSS': ['Пользовательский CSS ', 'User CSS '], 'attachPanel': ['Прикрепить главную панель', 'Attach main panel'], 'panelCounter': ['Счетчик постов/изображений на главной панели', 'Counter of posts/images on main panel'], 'rePageTitle': ['Название треда в заголовке вкладки*', 'Thread title in page tab*'], 'animation': ['CSS3 анимация в скрипте', 'CSS3 animation in script'], 'closePopups': ['Автоматически закрывать уведомления', 'Close popups automatically'], 'updScript': ['Автоматически проверять обновления скрипта', 'Check for script update automatically'], 'turnOff': ['Включать скрипт только на этом сайте', 'Enable script only on this site'], 'scrUpdIntrv': { sel: [['Каждый день', 'Каждые 2 дня', 'Каждую неделю', 'Каждые 2 недели', 'Каждый месяц'], ['Every day', 'Every 2 days', 'Every week', 'Every 2 week', 'Every month']], txt: ['', ''] }, 'language': { sel: [['Ru', 'En'], ['Ru', 'En']], txt: ['', ''] } }, txtBtn: [ ['Жирный', 'Bold'], ['Наклонный', 'Italic'], ['Подчеркнутый', 'Underlined'], ['Зачеркнутый', 'Strike'], ['Спойлер', 'Spoiler'], ['Код', 'Code'], ['Верхний индекс', 'Superscript'], ['Нижний индекс', 'Subscript'], ['Цитировать выделенное', 'Quote selected'] ], cfgTab: { 'filters': ['Фильтры', 'Filters'], 'posts': ['Посты', 'Posts'], 'images': ['Картинки', 'Images'], 'links': ['Ссылки', 'Links'], 'form': ['Форма', 'Form'], 'common': ['Общее', 'Common'], 'info': ['Инфо', 'Info'] }, panelBtn: { 'attach': ['Прикрепить/Открепить', 'Attach/Detach'], 'settings': ['Настройки', 'Settings'], 'hidden': ['Скрытое', 'Hidden'], 'favor': ['Избранное', 'Favorites'], 'refresh': ['Обновить', 'Refresh'], 'goback': ['Назад', 'Go back'], 'gonext': ['Следующая', 'Next'], 'goup': ['Наверх', 'To the top'], 'godown': ['В конец', 'To the bottom'], 'expimg': ['Раскрыть картинки', 'Expand images'], 'preimg': ['Предзагрузка картинок ([Ctrl+Click] только для новых постов)', 'Preload images ([Ctrl+Click] for new posts only)'], 'maskimg': ['Маскировать картинки', 'Mask images'], 'upd-on': ['Выключить автообновление треда', 'Disable thread autoupdate'], 'upd-off': ['Включить автообновление треда', 'Enable thread autoupdate'], 'audio-off':['Звуковое оповещение о новых постах', 'Sound notification about new posts'], 'catalog': ['Каталог', 'Catalog'], 'counter': ['Постов/Изображений в треде', 'Posts/Images in thread'], 'imgload': ['Сохранить изображения из треда', 'Save images from thread'], 'enable': ['Включить/выключить скрипт', 'Turn on/off the script'] }, selHiderMenu: { 'sel': ['Скрывать выделенное', 'Hide selected text'], 'name': ['Скрывать имя', 'Hide name'], 'trip': ['Скрывать трип-код', 'Hide with trip-code'], 'img': ['Скрывать изображение', 'Hide with image'], 'ihash': ['Скрывать схожие изобр.', 'Hide similar images'], 'text': ['Скрыть схожий текст', 'Hide similar text'], 'noimg': ['Скрывать без изображений', 'Hide without images'], 'notext': ['Скрывать без текста', 'Hide without text'] }, selExpandThrd: [ ['5 постов', '15 постов', '30 постов', '50 постов', '100 постов'], ['5 posts', '15 posts', '30 posts', '50 posts', '100 posts'] ], selAjaxPages: [ ['1 страница', '2 страницы', '3 страницы', '4 страницы', '5 страниц'], ['1 page', '2 pages', '3 pages', '4 pages', '5 pages'] ], selAudioNotif: [ ['Каждые 30 сек.', 'Каждую минуту', 'Каждые 2 мин.', 'Каждые 5 мин.'], ['Every 30 sec.', 'Every minute', 'Every 2 min.', 'Every 5 min.'] ], keyNavEdit: [ '%l%i24 – предыдущая страница/изображение%/l' + '%l%i217 – следующая страница/изображение%/l' + '%l%i23 – скрыть текущий пост/тред%/l' + '%l%i33 – раскрыть текущий тред%/l' + '%l%i22 – быстрый ответ или создать тред%/l' + '%l%i25t – отправить пост%/l' + '%l%i21 – тред (на доске)/пост (в треде) ниже%/l' + '%l%i20 – тред (на доске)/пост (в треде) выше%/l' + '%l%i31 – пост (на доске) ниже%/l' + '%l%i30 – пост (на доске) выше%/l' + '%l%i32 – открыть тред%/l' + '%l%i210 – открыть/закрыть настройки%/l' + '%l%i26 – открыть/закрыть избранное%/l' + '%l%i27 – открыть/закрыть скрытые посты%/l' + '%l%i28 – открыть/закрыть панель%/l' + '%l%i29 – включить/выключить маскировку изображений%/l' + '%l%i40 – обновить тред%/l' + '%l%i211 – раскрыть изображение текущего поста%/l' + '%l%i212t – жирный%/l' + '%l%i213t – курсив%/l' + '%l%i214t – зачеркнутый%/l' + '%l%i215t – спойлер%/l' + '%l%i216t – код%/l', '%l%i24 – previous page/image%/l' + '%l%i217 – next page/image%/l' + '%l%i23 – hide current post/thread%/l' + '%l%i33 – expand current thread%/l' + '%l%i22 – quick reply or create thread%/l' + '%l%i25t – send post%/l' + '%l%i21 – thread (on board)/post (in thread) below%/l' + '%l%i20 – thread (on board)/post (in thread) above%/l' + '%l%i31 – on board post below%/l' + '%l%i30 – on board post above%/l' + '%l%i32 – open thread%/l' + '%l%i210 – open/close Settings%/l' + '%l%i26 – open/close Favorites%/l' + '%l%i27 – open/close Hidden Posts Table%/l' + '%l%i28 – open/close the main panel%/l' + '%l%i29 – turn on/off masking images%/l' + '%l%i40 – update thread%/l' + '%l%i211 – expand current post\'s images%/l' + '%l%i212t – bold%/l' + '%l%i213t – italic%/l' + '%l%i214t – strike%/l' + '%l%i215t – spoiler%/l' + '%l%i216t – code%/l' ], month: [ ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] ], fullMonth: [ ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'], ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] ], week: [ ['Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] ], editor: { cfg: ['Редактирование настроек:', 'Edit settings:'], hidden: ['Редактирование скрытых тредов:', 'Edit hidden threads:'], favor: ['Редактирование избранного:', 'Edit favorites:'], css: ['Редактирование CSS', 'Edit CSS'] }, newPost: [ [' новый пост', ' новых поста', ' новых постов', '. Последний:'], [' new post', ' new posts', ' new posts', '. Latest: '] ], add: ['Добавить', 'Add'], apply: ['Применить', 'Apply'], clear: ['Очистить', 'Clear'], refresh: ['Обновить', 'Refresh'], load: ['Загрузить', 'Load'], save: ['Сохранить', 'Save'], edit: ['Правка', 'Edit'], reset: ['Сброс', 'Reset'], remove: ['Удалить', 'Remove'], info: ['Инфо', 'Info'], undo: ['Отмена', 'Undo'], change: ['Сменить', 'Change'], reply: ['Ответ', 'Reply'], loading: ['Загрузка...', 'Loading...'], checking: ['Проверка...', 'Checking...'], deleting: ['Удаление...', 'Deleting...'], error: ['Ошибка', 'Error'], noConnect: ['Ошибка подключения', 'Connection failed'], thrNotFound: ['Тред недоступен (№', 'Thread is unavailable (№'], succDeleted: ['Успешно удалено!', 'Succesfully deleted!'], errDelete: ['Не могу удалить:\n', 'Can\'t delete:\n'], cTimeError: ['Неправильные настройки времени', 'Invalid time settings'], noGlobalCfg: ['Глобальные настройки не найдены', 'Global config not found'], postNotFound: ['Пост не найден', 'Post not found'], dontShow: ['Скрыть: ', 'Hide: '], checkNow: ['Проверить сейчас', 'Check now'], updAvail: ['Доступно обновление!', 'Update available!'], haveLatest: ['У вас стоит самая последняя версия!', 'You have latest version!'], storage: ['Хранение: ', 'Storage: '], thrViewed: ['Тредов просмотрено: ', 'Threads viewed: '], thrCreated: ['Тредов создано: ', 'Threads created: '], thrHidden: ['Тредов скрыто: ', 'Threads hidden: '], postsSent: ['Постов отправлено: ', 'Posts sent: '], total: ['Всего: ', 'Total: '], debug: ['Отладка', 'Debug'], infoDebug: ['Информация для отладки', 'Information for debugging'], loadGlobal: ['Загрузить глобальные настройки', 'Load global settings'], saveGlobal: ['Сохранить настройки как глобальные', 'Save settings as global'], editInTxt: ['Правка в текстовом формате', 'Edit in text format'], resetCfg: ['Сбросить в настройки по умолчанию', 'Reset settings to defaults'], conReset: ['Данное действие удалит все ваши настройки и закладки. Продолжить?', 'This will delete all your preferences and favourites. Continue?'], clrSelected: ['Удалить выделенные записи', 'Remove selected notes'], saveChanges: ['Сохранить внесенные изменения', 'Save your changes'], infoCount: ['Обновить счетчики постов', 'Refresh posts counters'], infoPage: ['Проверить актуальность тредов (до 5 страницы)', 'Check for threads actuality (up to 5 page)'], clrDeleted: ['Очистить записи недоступных тредов', 'Clear notes of inaccessible threads'], hiddenPosts: ['Скрытые посты на странице', 'Hidden posts on the page'], hiddenThrds: ['Скрытые треды', 'Hidden threads'], noHidPosts: ['На этой странице нет скрытых постов...', 'No hidden posts on this page...'], noHidThrds: ['Нет скрытых тредов...', 'No hidden threads...'], expandAll: ['Раскрыть все', 'Expand all'], invalidData: ['Некорректный формат данных', 'Incorrect data format'], favThrds: ['Избранные треды:', 'Favorite threads:'], noFavThrds: ['Нет избранных тредов...', 'Favorites is empty...'], replyTo: ['Ответ в', 'Reply to'], replies: ['Ответы:', 'Replies:'], postsOmitted: ['Пропущено ответов: ', 'Posts omitted: '], collapseThrd: ['Свернуть тред', 'Collapse thread'], deleted: ['удалён', 'deleted'], getNewPosts: ['Получить новые посты', 'Get new posts'], page: ['Страница', 'Page'], hiddenThrd: ['Скрытый тред:', 'Hidden thread:'], makeThrd: ['Создать тред', 'Create thread'], makeReply: ['Ответить', 'Make reply'], hideForm: ['Скрыть форму', 'Hide form'], search: ['Искать в ', 'Search in '], wait: ['Ждите', 'Wait'], noFile: ['Нет файла', 'No file'], clickToAdd: ['Выберите, либо перетащите файл', 'Select or drag and drop file'], removeFile: ['Удалить файл', 'Remove file'], helpAddFile: ['Встроить .ogg, .rar, .zip или .7z в картинку', 'Pack .ogg, .rar, .zip or .7z into image'], downloadFile: ['Скачать содержащийся в картинке файл', 'Download existing file from image'], fileCorrupt: ['Файл повреждён: ', 'File is corrupted: '], subjHasTrip: ['Поле "Тема" содержит трипкод', '"Subject" field contains a tripcode'], loadImage: ['Загружаются изображения: ', 'Loading images: '], loadFile: ['Загружаются файлы: ', 'Loading files: '], cantLoad: ['Не могу загрузить ', 'Can\'t load '], willSavePview: ['Будет сохранено превью', 'Thumbnail will be saved'], loadErrors: ['Во время загрузки произошли ошибки:', 'An error occurred during the loading:'], errCorruptData: ['Ошибка: сервер отправил повреждённые данные', 'Error: server sent corrupted data'], nextImg: ['Следующее изображение', 'Next image'], prevImg: ['Предыдущее изображение', 'Previous image'], togglePost: ['Скрыть/Раскрыть пост', 'Hide/Unhide post'], replyToPost: ['Ответить на пост', 'Reply to post'], expandThrd: ['Раскрыть весь тред', 'Expand all thread'], toggleFav: ['Добавить/Убрать Избранное', 'Add/Remove Favorites'], attachPview: ['Закрепить превью', 'Attach preview'], author: ['автор: ', 'author: '], views: ['просмотров: ', 'views: '], published: ['опубликовано: ', 'published: '], seSyntaxErr: ['синтаксическая ошибка в аргументе спелла: %s', 'syntax error in argument of spell: %s'], seUnknown: ['неизвестный спелл: %s', 'unknown spell: %s'], seMissOp: ['пропущен оператор', 'missing operator'], seMissArg: ['пропущен аргумент спелла: %s', 'missing argument of spell: %s'], seMissSpell: ['пропущен спелл', 'missing spell'], seErrRegex: ['синтаксическая ошибка в регулярном выражении: %s', 'syntax error in regular expression: %s'], seUnexpChar: ['неожиданный символ: %s', 'unexpected character: %s'], seMissClBkt: ['пропущена закрывающаяся скобка', 'missing ) in parenthetical'], seRow: [' (строка ', ' (row '], seCol: [', столбец ', ', column '] }, doc = window.document, aProto = Array.prototype, locStorage, sesStorage, Cfg, comCfg, hThr, pByNum, sVis, bUVis, needScroll, aib, nav, brd, TNum, pageNum, updater, keyNav, firstThr, lastThr, visPosts = 2, dTime, YouTube, WebmParser, Logger, pr, dForm, dummy, spells, Images_ = {preloading: false, afterpreload: null, progressId: null, canvas: null}, ajaxInterval, lang, quotetxt = '', liteMode, isExpImg, isPreImg, chromeCssUpd, $each = Function.prototype.call.bind(aProto.forEach), emptyFn = function() {}; //============================================================================================================ // UTILITIES //============================================================================================================ function $Q(path, root) { return root.querySelectorAll(path); } function $q(path, root) { return root.querySelector(path); } function $C(id, root) { return root.getElementsByClassName(id); } function $c(id, root) { return root.getElementsByClassName(id)[0]; } function $id(id) { return doc.getElementById(id); } function $T(id, root) { return root.getElementsByTagName(id); } function $t(id, root) { return root.getElementsByTagName(id)[0]; } function $append(el, nodes) { for(var i = 0, len = nodes.length; i < len; i++) { if(nodes[i]) { el.appendChild(nodes[i]); } } } function $before(el, node) { el.parentNode.insertBefore(node, el); } function $after(el, node) { el.parentNode.insertBefore(node, el.nextSibling); } function $add(html) { dummy.innerHTML = html; return dummy.firstChild; } function $new(tag, attr, events) { var el = doc.createElement(tag); if(attr) { for(var key in attr) { key === 'text' ? el.textContent = attr[key] : key === 'value' ? el.value = attr[key] : el.setAttribute(key, attr[key]); } } if(events) { for(var key in events) { el.addEventListener(key, events[key], false); } } return el; } function $New(tag, attr, nodes) { var el = $new(tag, attr, null); $append(el, nodes); return el; } function $txt(el) { return doc.createTextNode(el); } function $btn(val, ttl, Fn) { return $new('input', {'type': 'button', 'value': val, 'title': ttl}, {'click': Fn}); } function $script(text) { $del(doc.head.appendChild($new('script', {'type': 'text/javascript', 'text': text}, null))); } function $css(text) { return doc.head.appendChild($new('style', {'type': 'text/css', 'text': text}, null)); } function $if(cond, el) { return cond ? el : null; } function $disp(el) { el.style.display = el.style.display === 'none' ? '' : 'none'; } function $del(el) { if(el) { el.parentNode.removeChild(el); } } function $DOM(html) { var myDoc = doc.implementation.createHTMLDocument(''); myDoc.documentElement.innerHTML = html; return myDoc; } function $pd(e) { e.preventDefault(); } function $txtInsert(el, txt) { var scrtop = el.scrollTop, start = el.selectionStart; el.value = el.value.substr(0, start) + txt + el.value.substr(el.selectionEnd); el.setSelectionRange(start + txt.length, start + txt.length); el.focus(); el.scrollTop = scrtop; } function $txtSelect() { return (nav.Presto ? doc.getSelection() : window.getSelection()).toString(); } function $isEmpty(obj) { for(var i in obj) { if(obj.hasOwnProperty(i)) { return false; } } return true; } Logger = new function() { var instance, oldTime, initTime, timeLog; function LoggerSingleton() { if(instance) { return instance; } instance = this; } LoggerSingleton.prototype = { finish: function() { timeLog.push(Lng.total[lang] + (Date.now() - initTime) + 'ms'); }, get: function() { return timeLog; }, init: function() { oldTime = initTime = Date.now(); timeLog = []; }, log: function realLog(text) { var newTime = Date.now(), time = newTime - oldTime; if(time > 1) { timeLog.push(text + ': ' + time + 'ms'); oldTime = newTime; } } }; return LoggerSingleton; }; function $xhr(obj) { var h, xhr = new XMLHttpRequest(); if(obj['onreadystatechange']) { xhr.onreadystatechange = obj['onreadystatechange'].bind(window, xhr); } if(obj['onload']) { xhr.onload = obj['onload'].bind(window, xhr); } xhr.open(obj['method'], obj['url'], true); if(obj['responseType']) { xhr.responseType = obj['responseType']; } for(h in obj['headers']) { xhr.setRequestHeader(h, obj['headers'][h]); } xhr.send(obj['data'] || null); return xhr; } function $queue(maxNum, Fn, endFn) { this.array = []; this.length = this.index = this.running = 0; this.num = 1; this.fn = Fn; this.endFn = endFn; this.max = maxNum; this.freeSlots = []; while(maxNum--) { this.freeSlots.push(maxNum); } this.completed = this.paused = false; } $queue.prototype = { run: function(data) { if(this.paused || this.running === this.max) { this.array.push(data); this.length++; } else { this.fn(this.freeSlots.pop(), this.num++, data); this.running++; } }, end: function(qIdx) { if(!this.paused && this.index < this.length) { this.fn(qIdx, this.num++, this.array[this.index++]); return; } this.running--; this.freeSlots.push(qIdx); if(!this.paused && this.completed && this.running === 0) { this.endFn(); } }, complete: function() { if(this.index >= this.length && this.running === 0) { this.endFn(); } else { this.completed = true; } }, pause: function() { this.paused = true; }, 'continue': function() { this.paused = false; if(this.index >= this.length) { if(this.completed) { this.endFn(); } return; } while(this.index < this.length && this.running !== this.max) { this.fn(this.freeSlots.pop(), this.num++, this.array[this.index++]); this.running++; } } }; function $tar() { this._data = []; } $tar.prototype = { addFile: function(filepath, input) { var i, checksum, nameLen, fileSize = input.length, header = new Uint8Array(512); for(i = 0, nameLen = Math.min(filepath.length, 100); i < nameLen; ++i) { header[i] = filepath.charCodeAt(i) & 0xFF; } this._padSet(header, 100, '100777', 8); // fileMode this._padSet(header, 108, '0', 8); // uid this._padSet(header, 116, '0', 8); // gid this._padSet(header, 124, fileSize.toString(8), 13); // fileSize this._padSet(header, 136, Math.floor(Date.now() / 1000).toString(8), 12); // mtime this._padSet(header, 148, ' ', 8); // checksum header[156] = 0x30; // type ('0') for(i = checksum = 0; i < 157; i++) { checksum += header[i]; } this._padSet(header, 148, checksum.toString(8), 8); // checksum this._data.push(header); this._data.push(input); if((i = Math.ceil(fileSize / 512) * 512 - fileSize) !== 0) { this._data.push(new Uint8Array(i)); } }, addString: function(filepath, str) { var i, len, data, sDat = unescape(encodeURIComponent(str)); for(i = 0, len = sDat.length, data = new Uint8Array(len); i < len; ++i) { data[i] = sDat.charCodeAt(i) & 0xFF; } this.addFile(filepath, data); }, get: function() { this._data.push(new Uint8Array(1024)); return new Blob(this._data, {'type': 'application/x-tar'}); }, _padSet: function(data, offset, num, len) { var i = 0, nLen = num.length; len -= 2; while(nLen < len) { data[offset++] = 0x20; // ' ' len--; } while(i < nLen) { data[offset++] = num.charCodeAt(i++); } data[offset] = 0x20; // ' ' } }; function $workers(source, count) { var i, wrk, wUrl; if(nav.Firefox) { wUrl = 'data:text/javascript,' + source; wrk = unsafeWindow.Worker; } else { wUrl = window.URL.createObjectURL(new Blob([source], {'type': 'text/javascript'})); this.url = wUrl; wrk = Worker; } for(i = 0; i < count; ++i) { this[i] = new wrk(wUrl); } } $workers.prototype = { url: null, clear: function() { if(this.url !== null) { window.URL.revokeObjectURL(this.url); } } }; function regQuote(str) { return (str + '').replace(/([.?*+^$[\]\\(){}|\-])/g, '\\$1'); } function fixBrd(b) { return '/' + b + (b ? '/' : ''); } function getAbsLink(url) { return url[1] === '/' ? aib.prot + url : url[0] === '/' ? aib.prot + '//' + aib.host + url : url; } function getErrorMessage(eCode, eMsg) { return eCode === 0 ? eMsg || Lng.noConnect[lang] : 'HTTP [' + eCode + '] ' + eMsg; } function getAncestor(el, tagName) { do { el = el.parentElement; } while(el && el.tagName !== tagName); return el; } function getPrettyErrorMessage(e) { return e.stack ? (nav.WebKit ? e.stack : e.name + ': ' + e.message + '\n' + (nav.Firefox ? e.stack.replace(/^([^@]*).*\/(.+)$/gm, function(str, fName, line) { return ' at ' + (fName ? fName + ' (' + line + ')' : line); }) : e.stack) ) : e.name + ': ' + e.message; } function toRegExp(str, noG) { var l = str.lastIndexOf('/'), flags = str.substr(l + 1); return new RegExp(str.substr(1, l - 1), noG ? flags.replace('g', '') : flags); } //============================================================================================================ // STORAGE & CONFIG //============================================================================================================ function getStored(id, Fn) { if(nav.isGM) { Fn(GM_getValue(id)); } else if(nav.isChromeStorage) { chrome.storage.sync.get(id, function(obj) { Fn(obj[id]); }); } else if(nav.isScriptStorage) { Fn(scriptStorage.getItem(id)); } else { Fn(locStorage.getItem(id)); } } function setStored(id, value) { if(nav.isGM) { GM_setValue(id, value); } else if(nav.isChromeStorage) { var obj = {}; obj[id] = value; chrome.storage.sync.set(obj, function() {}); } else if(nav.isScriptStorage) { scriptStorage.setItem(id, value); } else { locStorage.setItem(id, value); } } function delStored(id) { if(nav.isGM) { GM_deleteValue(id); } else if(nav.isChromeStorage) { chrome.storage.sync.remove(id, function() {}); } else if(nav.isScriptStorage) { scriptStorage.removeItem(id); } else { locStorage.removeItem(id); } } function getStoredObj(id, Fn) { getStored(id, function(Fn, val) { try { var data = JSON.parse(val || '{}'); } finally { Fn(data || {}); } }.bind(null, Fn)); } function saveComCfg(dm, obj) { getStoredObj('DESU_Config', function(dm, obj, val) { comCfg = val; if(obj) { comCfg[dm] = obj; } else { delete comCfg[dm]; } setStored('DESU_Config', JSON.stringify(comCfg) || ''); }.bind(null, dm, obj)); } function saveCfg(id, val) { if(Cfg[id] !== val) { Cfg[id] = val; saveComCfg(aib.dm, Cfg); } } function Config(obj) { for(var i in obj) { this[i] = obj[i]; } } Config.prototype = defaultCfg; function readCfg(Fn) { getStoredObj('DESU_Config', function(Fn, val) { var obj; comCfg = val; if(!(aib.dm in comCfg) || $isEmpty(obj = comCfg[aib.dm])) { if(nav.isChromeStorage && (obj = locStorage.getItem('DESU_Config'))) { obj = JSON.parse(obj)[aib.dm]; locStorage.removeItem('DESU_Config'); } else { obj = nav.isGlobal ? comCfg['global'] || {} : {}; } obj['captchaLang'] = aib.ru ? 2 : 1; obj['correctTime'] = 0; } Cfg = new Config(obj); if(!Cfg['timeOffset']) { Cfg['timeOffset'] = '+0'; } if(!Cfg['timePattern']) { Cfg['timePattern'] = aib.timePattern; } if((nav.Opera11 || aib.fch || aib.tiny) && Cfg['ajaxReply'] === 2) { Cfg['ajaxReply'] = 1; } if(!('Notification' in window)) { Cfg['desktNotif'] = 0; } if(nav.Presto) { if(nav.Opera11) { if(!nav.isGM) { Cfg['YTubeTitles'] = 0; } Cfg['animation'] = 0; } if(Cfg['YTubeType'] === 2) { Cfg['YTubeType'] = 1; } Cfg['preLoadImgs'] = 0; Cfg['findImgFile'] = 0; if(!nav.isGM) { Cfg['updScript'] = 0; } Cfg['fileThumb'] = 0; } if(nav.isChromeStorage) { Cfg['updScript'] = 0; } if(Cfg['updThrDelay'] < 10) { Cfg['updThrDelay'] = 10; } if(!Cfg['saveSage']) { Cfg['sageReply'] = 0; } if(!Cfg['passwValue']) { Cfg['passwValue'] = Math.round(Math.random() * 1e15).toString(32); } if(!Cfg['stats']) { Cfg['stats'] = {'view': 0, 'op': 0, 'reply': 0}; } if(TNum) { Cfg['stats']['view']++; } if(aib.dobr) { Cfg['fileThumb'] = 0; aib.hDTFix = new dateTime( 'yyyy-nn-dd-hh-ii-ss', '_d _M _Y (_w) _h:_i ', Cfg['timeOffset'] || 0, Cfg['correctTime'] ? lang : 1, null ); } saveComCfg(aib.dm, Cfg); lang = Cfg['language']; if(Cfg['correctTime']) { dTime = new dateTime(Cfg['timePattern'], Cfg['timeRPattern'], Cfg['timeOffset'], lang, function(rp) { saveCfg('timeRPattern', rp); }); } Fn(); }.bind(null, Fn)); } function toggleCfg(id) { saveCfg(id, +!Cfg[id]); } function readPosts() { var data, str = TNum ? sesStorage['de-hidden-' + brd + TNum] : null; if(typeof str === 'string') { data = str.split(','); if(data.length === 4 && +data[0] === (Cfg['hideBySpell'] ? spells.hash : 0) && (data[1] in pByNum) && pByNum[data[1]].count === +data[2]) { sVis = data[3].split(''); return; } } sVis = []; } function readUserPosts() { getStoredObj('DESU_Posts_' + aib.dm, function(val) { bUVis = val; getStoredObj('DESU_Threads_' + aib.dm, function(val) { hThr = val; if(nav.isChromeStorage && (val = locStorage.getItem('DESU_Posts_' + aib.dm))) { bUVis = JSON.parse(val); val = locStorage.getItem('DESU_Threads_' + aib.dm); hThr = JSON.parse(val); locStorage.removeItem('DESU_Posts_' + aib.dm); locStorage.removeItem('DESU_Threads_' + aib.dm); } var uVis, vis, num, post, date = Date.now(), update = false; if(brd in bUVis) { uVis = bUVis[brd]; } else { uVis = bUVis[brd] = {}; } if(!(brd in hThr)) { hThr[brd] = {}; } if(!firstThr) { return; } for(post = firstThr.op; post; post = post.next) { num = post.num; if(num in uVis) { if(post.isOp) { uVis[num][0] = +!(num in hThr[brd]); } if(uVis[num][0] === 0) { post.setUserVisib(true, date, false); } else { uVis[num][1] = date; post.btns.firstChild.className = 'de-btn-hide-user'; post.userToggled = true; } } else { vis = sVis[post.count]; if(post.isOp) { if(num in hThr[brd]) { vis = '0'; } else if(vis === '0') { vis = null; } } if(vis === '0') { if(!post.hidden) { post.setVisib(true); post.hideRefs(); } post.spellHidden = true; } else if(vis !== '1') { spells.check(post); } } } spells.end(savePosts); if(update) { bUVis[brd] = uVis; saveUserPosts(false); } }); }); } function savePosts() { if(TNum) { var lPost = firstThr.lastNotDeleted; sesStorage['de-hidden-' + brd + TNum] = (Cfg['hideBySpell'] ? spells.hash : '0') + ',' + lPost.num + ',' + lPost.count + ',' + sVis.join(''); } saveHiddenThreads(false); toggleContent('hid', true); } function saveUserPosts(clear) { var minDate, b, vis, key, str = JSON.stringify(bUVis); if(clear && str.length > 1e6) { minDate = Date.now() - 5 * 24 * 3600 * 1000; for(b in bUVis) { if(bUVis.hasOwnProperty(b)) { vis = bUVis[b]; for(key in vis) { if(vis.hasOwnProperty(key) && vis[key][1] < minDate) { delete vis[key]; } } } } str = JSON.stringify(bUVis); } setStored('DESU_Posts_' + aib.dm, str); toggleContent('hid', true); } function saveHiddenThreads(updContent) { setStored('DESU_Threads_' + aib.dm, JSON.stringify(hThr)); if(updContent) { toggleContent('hid', true); } } function readFavoritesPosts() { getStoredObj('DESU_Favorites', function(fav) { var thr, temp, num, update = false; if(nav.isChromeStorage && (temp = locStorage.getItem('DESU_Favorites'))) { temp = JSON.parse(temp); locStorage.removeItem('DESU_Favorites'); if($isEmpty(temp)) { return; } temp = temp[aib.host]; fav[aib.host] = temp; temp = temp[brd]; } else { if(!(aib.host in fav)) { return; } temp = fav[aib.host]; if(!(brd in temp)) { return; } temp = temp[brd]; } for(thr = firstThr; thr; thr = thr.next) { if((num = thr.num) in temp) { $c('de-btn-fav', thr.op.btns).className = 'de-btn-fav-sel'; if(TNum) { temp[num]['cnt'] = thr.pcount; temp[num]['new'] = 0; } else { temp[num]['new'] = thr.pcount - temp[num]['cnt']; } update = true; } } if(update) { saveFavorites(fav); } }); } function saveFavorites(fav) { setStored('DESU_Favorites', JSON.stringify(fav)); toggleContent('fav', true, fav); } function removeFavoriteEntry(fav, h, b, num, clearPage) { function _isEmpty(f) { for(var i in f) { if(i !== 'url' && f.hasOwnProperty(i)) { return false; } } return true; } if((h in fav) && (b in fav[h]) && (num in fav[h][b])) { delete fav[h][b][num]; if(_isEmpty(fav[h][b])) { delete fav[h][b]; if($isEmpty(fav[h])) { delete fav[h]; } } } if(clearPage && h === aib.host && b === brd && (num in pByNum)) { ($c('de-btn-fav-sel', pByNum[num].btns) || {}).className = 'de-btn-fav'; } } function readViewedPosts() { if(Cfg['markViewed']) { var data = sesStorage['de-viewed']; if(data) { data.split(',').forEach(function(pNum) { var post = pByNum[pNum]; if(post) { post.el.classList.add('de-viewed'); post.viewed = true; } }); } } } //============================================================================================================ // MAIN PANEL //============================================================================================================ function pButton(id, href, hasHotkey) { return '<li><a id="de-btn-' + id + '" class="de-abtn" ' + (hasHotkey ? 'de-' : '') + 'title="' + Lng.panelBtn[id][lang] +'" href="' + href + '"></a></li>'; } function addPanel() { var panel, evtObject, imgLen = $Q(aib.qThumbImages, dForm).length; (pr && pr.pArea[0] || dForm).insertAdjacentHTML('beforebegin', '<div id="de-main" lang="' + getThemeLang() + '">' + '<div class="de-content"></div>' + '<div id="de-panel">' + '<span id="de-btn-logo" title="' + Lng.panelBtn['attach'][lang] + '"></span>' + '<ul id="de-panel-btns"' + (Cfg['expandPanel'] ? '>' : ' style="display: none">') + (Cfg['disabled'] ? pButton('enable', '#', false) : pButton('settings', '#', true) + pButton('hidden', '#', true) + pButton('favor', '#', true) + (aib.arch ? '' : pButton('refresh', '#', false) + (!TNum && (pageNum === aib.firstPage) ? '' : pButton('goback', aib.getPageUrl(brd, pageNum - 1), true)) + (TNum || pageNum === aib.lastPage ? '' : pButton('gonext', aib.getPageUrl(brd, pageNum + 1), true)) ) + pButton('goup', '#', false) + pButton('godown', '#', false) + (imgLen === 0 ? '' : pButton('expimg', '#', false) + pButton('maskimg', '#', true) + (nav.Presto ? '' : (Cfg['preLoadImgs'] ? '' : pButton('preimg', '#', false)) + (!TNum && !aib.arch ? '' : pButton('imgload', '#', false)))) + (!TNum ? '' : pButton(Cfg['ajaxUpdThr'] ? 'upd-on' : 'upd-off', '#', false) + (nav.Safari ? '' : pButton('audio-off', '#', false))) + (!aib.abu && (!aib.fch || aib.arch) ? '' : pButton('catalog', '//' + aib.host + '/' + (aib.abu ? 'makaba/makaba.fcgi?task=catalog&board=' + brd : brd + '/catalog.html'), false)) + pButton('enable', '#', false) + (!TNum && !aib.arch ? '' : '<div id="de-panel-info"><span title="' + Lng.panelBtn['counter'][lang] + '">' + firstThr.pcount + '/' + imgLen + '</span></div>') ) + '</ul>' + '</div>' + (Cfg['disabled'] ? '' : '<div id="de-alert"></div>' + '<hr style="clear: both;">' ) + '</div>' ); panel = $id('de-panel'); evtObject = { attach: false, odelay: 0, panel: panel, handleEvent: function(e) { switch(e.type) { case 'click': switch(e.target.id) { case 'de-btn-logo': if(Cfg['expandPanel']) { this.panel.lastChild.style.display = 'none'; this.attach = false; } else { this.attach = true; } toggleCfg('expandPanel'); return; case 'de-btn-settings': this.attach = toggleContent('cfg', false); break; case 'de-btn-hidden': this.attach = toggleContent('hid', false); break; case 'de-btn-favor': this.attach = toggleContent('fav', false); break; case 'de-btn-refresh': window.location.reload(); break; case 'de-btn-goup': scrollTo(0, 0); break; case 'de-btn-godown': scrollTo(0, doc.body.scrollHeight || doc.body.offsetHeight); break; case 'de-btn-expimg': isExpImg = !isExpImg; $del($c('de-img-center', doc)); for(var post = firstThr.op; post; post = post.next) { post.toggleImages(isExpImg); } break; case 'de-btn-preimg': isPreImg = !isPreImg; if(!e.ctrlKey) { preloadImages(null); } break; case 'de-btn-maskimg': toggleCfg('maskImgs'); updateCSS(); break; case 'de-btn-upd-on': case 'de-btn-upd-off': case 'de-btn-upd-warn': if(updater.enabled) { updater.disable(); } else { updater.enable(); } break; case 'de-btn-audio-on': case 'de-btn-audio-off': if(updater.toggleAudio(0)) { updater.enable(); e.target.id = 'de-btn-audio-on'; } else { e.target.id = 'de-btn-audio-off'; } $del($c('de-menu', doc)); break; case 'de-btn-imgload': if($id('de-alert-imgload')) { break; } if(Images_.preloading) { $alert(Lng.loading[lang], 'imgload', true); Images_.afterpreload = loadDocFiles.bind(null, true); Images_.progressId = 'imgload'; } else { loadDocFiles(true); } break; case 'de-btn-enable': toggleCfg('disabled'); window.location.reload(); break; default: return; } $pd(e); return; case 'mouseover': if(!Cfg['expandPanel']) { clearTimeout(this.odelay); this.panel.lastChild.style.display = ''; } switch(e.target.id) { case 'de-btn-settings': KeyEditListener.setTitle(e.target, 10); break; case 'de-btn-hidden': KeyEditListener.setTitle(e.target, 7); break; case 'de-btn-favor': KeyEditListener.setTitle(e.target, 6); break; case 'de-btn-goback': KeyEditListener.setTitle(e.target, 4); break; case 'de-btn-gonext': KeyEditListener.setTitle(e.target, 17); break; case 'de-btn-maskimg': KeyEditListener.setTitle(e.target, 9); break; case 'de-btn-refresh': if(TNum) { return; } case 'de-btn-audio-off': addMenu(e); } return; default: // mouseout if(!Cfg['expandPanel'] && !this.attach) { this.odelay = setTimeout(function(obj) { obj.panel.lastChild.style.display = 'none'; obj.attach = false; }, 500, this); } switch(e.target.id) { case 'de-btn-refresh': case 'de-btn-audio-off': removeMenu(e); break; } } } }; panel.addEventListener('click', evtObject, true); panel.addEventListener('mouseover', evtObject, false); panel.addEventListener('mouseout', evtObject, false); } function toggleContent(name, isUpd, data) { if(liteMode) { return false; } var remove, el = $c('de-content', doc), id = 'de-content-' + name; if(!el) { return false; } if(isUpd && el.id !== id) { return true; } remove = !isUpd && el.id === id; if(el.hasChildNodes() && Cfg['animation']) { nav.animEvent(el, function(node) { showContent(node, id, name, remove, data); id = name = remove = data = null; }); el.className = 'de-content de-cfg-close'; return !remove; } else { showContent(el, id, name, remove, data); return !remove; } } function addContentBlock(parent, title) { return parent.appendChild($New('div', {'class': 'de-content-block'}, [ $new('input', {'type': 'checkbox'}, {'click': function() { var el, res = this.checked, i = 0, els = $Q('.de-entry > div > input', this.parentNode); for(; el = els[i++];) { el.checked = res; } }}), title ])); } function showContent(cont, id, name, remove, data) { var tNum, i, b, els, post, cln, block, temp, cfgTabId; if(name === 'cfg' && !remove && (temp = $q('.de-cfg-tab-back[selected="true"] > .de-cfg-tab', cont))) { cfgTabId = temp.getAttribute('info'); } cont.innerHTML = cont.style.backgroundColor = ''; if(remove) { cont.removeAttribute('id'); return; } cont.id = id; if(name === 'cfg') { addSettings(cont, cfgTabId); } else if(Cfg['attachPanel']) { cont.style.backgroundColor = getComputedStyle(doc.body).getPropertyValue('background-color'); } if(name === 'fav') { if(data) { showFavoriteTable(cont, data); } else { // TODO: show load message getStoredObj('DESU_Favorites', function(fav) { showFavoriteTable(this, fav); }.bind(cont)); } return; } if(name === 'hid') { for(i = 0, els = $C('de-post-hide', dForm); post = els[i++];) { if(post.isOp) { continue; } (cln = post.cloneNode(true)).removeAttribute('id'); cln.style.display = ''; if(cln.classList.contains(aib.cRPost)) { cln.classList.add('de-cloned-post'); } else { cln.className = aib.cReply + ' de-cloned-post'; } cln.post = Object.create(cln.clone = post.post); cln.post.el = cln; cln.btn = $q('.de-btn-hide, .de-btn-hide-user', cln); cln.btn.parentNode.className = 'de-ppanel'; cln.btn.onclick = function() { // doesn't work properly. TODO: Fix this.hideContent(this.hidden = !this.hidden); }.bind(cln); (block || (block = cont.appendChild( $add('<div class="de-content-block"><b>' + Lng.hiddenPosts[lang] + ':</b></div>') ))).appendChild($New('div', {'class': 'de-entry'}, [cln])); } if(block) { $append(cont, [ $btn(Lng.expandAll[lang], '', function() { $each($Q('.de-cloned-post', this.parentNode), function(el) { var post = el.post; post.hideContent(post.hidden = !post.hidden); }); this.value = this.value === Lng.undo[lang] ? Lng.expandAll[lang] : Lng.undo[lang]; }), $btn(Lng.save[lang], '', function() { $each($Q('.de-cloned-post', this.parentNode), function(date, el) { if(!el.post.hidden) { el.clone.setUserVisib(false, date, true); } }.bind(null, Date.now())); saveUserPosts(true); }) ]); } else { cont.appendChild($new('b', {'text': Lng.noHidPosts[lang]}, null)); } $append(cont, [ doc.createElement('hr'), $new('b', {'text': ($isEmpty(hThr) ? Lng.noHidThrds[lang] : Lng.hiddenThrds[lang] + ':')}, null) ]); for(b in hThr) { if(!$isEmpty(hThr[b])) { block = addContentBlock(cont, $new('b', {'text': '/' + b}, null)); for(tNum in hThr[b]) { block.insertAdjacentHTML('beforeend', '<div class="de-entry" info="' + b + ';' + tNum + '"><div class="' + aib.cReply + '"><input type="checkbox"><a href="' + aib.getThrdUrl(b, tNum) + '" target="_blank">№' + tNum + '</a> - ' + hThr[b][tNum] + '</div></div>'); } } } $append(cont, [ doc.createElement('hr'), addEditButton('hidden', function(Fn) { Fn(hThr, true, function(data) { hThr = data; if(!(brd in hThr)) { hThr[brd] = {}; } firstThr.updateHidden(hThr[brd]); saveHiddenThreads(true); locStorage['__de-threads'] = JSON.stringify(hThr); locStorage.removeItem('__de-threads'); }); }), $btn(Lng.clear[lang], Lng.clrDeleted[lang], function() { $each($Q('.de-entry[info]', this.parentNode), function(el) { var arr = el.getAttribute('info').split(';'); ajaxLoad(aib.getThrdUrl(arr[0], arr[1]), false, null, function(eCode, eMsg, xhr) { if(eCode === 404) { delete hThr[this[0]][this[1]]; saveHiddenThreads(true); } }.bind(arr)); }); }), $btn(Lng.remove[lang], Lng.clrSelected[lang], function() { $each($Q('.de-entry[info]', this.parentNode), function(date, el) { var post, arr = el.getAttribute('info').split(';'); if($t('input', el).checked) { if(arr[1] in pByNum) { pByNum[arr[1]].setUserVisib(false, date, true); } else { locStorage['__de-post'] = JSON.stringify({ 'brd': arr[0], 'date': date, 'isOp': true, 'num': arr[1], 'hide': false }); locStorage.removeItem('__de-post'); } delete hThr[arr[0]][arr[1]]; } }.bind(null, Date.now())); saveHiddenThreads(true); }) ]); } if(Cfg['animation']) { cont.className = 'de-content de-cfg-open'; } } function clearFavoriteTable() { var els = $Q('.de-entry[de-removed]', doc), len = els.length; if(len > 0) { getStoredObj('DESU_Favorites', function(fav) { for(var el, i = 0; i < len; ++i) { el = els[i]; removeFavoriteEntry(fav, el.getAttribute('de-host'), el.getAttribute('de-board'), el.getAttribute('de-num'), true); } saveFavorites(fav); }); } } function showFavoriteTable(cont, data) { var h, b, i, block, tNum; for(h in data) { for(b in data[h]) { i = data[h][b]; block = addContentBlock(cont, i['url'] ? $new('a', {'href': i['url'], 'text': h + '/' + b}, null) : $new('b', {'text': h + '/' + b}, null)); if(h === aib.host && b === brd) { block.classList.add('de-fav-current'); } for(tNum in data[h][b]) { if(tNum === 'url') { continue; } i = data[h][b][tNum]; if(!i['url'].startsWith('http')) { i['url'] = (h === aib.host ? aib.prot + '//' : 'http://') + h + i['url']; } block.appendChild($New('div', { 'class': 'de-entry', 'de-host': h, 'de-board': b, 'de-num': tNum, 'de-url': i['url'] }, [ $New('div', {'class': aib.cReply}, [ $add('<input type="checkbox">'), $new('span', {'class': 'de-btn-expthr'}, {'click': loadFavorThread}), $add('<a href="' + i['url'] + '">№' + tNum + '</a>'), $add('<span class="de-fav-title"> - ' + i['txt'] + '</span>'), $add('<span class="de-fav-inf-page"></span>'), $add('<span class="de-fav-inf-posts">[<span class="de-fav-inf-old">' + i['cnt'] + '</span>]<span class="de-fav-inf-new"' + (i['new'] === 0 ? ' style="display: none;"' : '') + '>' + i['new'] + '</span></span>') ]) ])); } } } cont.insertAdjacentHTML('afterbegin', '<b>' + (Lng[block ? 'favThrds' : 'noFavThrds'][lang]) + '</b>'); $append(cont, [ doc.createElement('hr'), addEditButton('favor', function(Fn) { getStoredObj('DESU_Favorites', function(Fn, val) { Fn(val, true, saveFavorites); }.bind(null, Fn)); }), $btn(Lng.info[lang], Lng.infoCount[lang], function() { getStoredObj('DESU_Favorites', function(fav) { var i, els, len, update = false; var queue = new $queue(4, function(qIdx, num, el) { var c, host = el.getAttribute('de-host'), b = el.getAttribute('de-board'), num = el.getAttribute('de-num'), f = fav[host][b][num]; if(host !== aib.host) { queue.end(qIdx); return; } el = $c('de-fav-inf-new', el); el.classList.add('de-wait'); el.textContent = ''; ajaxLoad(aib.getThrdUrl(b, num), true, function(form, xhr) { var cnt = aib.getPosts(form).length + 1 - this.previousElementSibling.textContent; this.textContent = cnt; this.classList.remove('de-wait'); if(cnt === 0) { this.style.display = 'none'; } else { this.style.display = ''; f['new'] = cnt; update = true; } queue.end(qIdx); f = qIdx = null; }.bind(el), function(eCode, eMsg, xhr) { this.textContent = getErrorMessage(eCode, eMsg); this.classList.remove('de-wait'); queue.end(qIdx); qIdx = null; }.bind(el)); }, function() { if(update) { setStored('DESU_Favorites', JSON.stringify(fav)); } fav = queue = update = null; }); for(i = 0, els = $C('de-entry', doc), len = els.length; i < len; ++i) { queue.run(els[i]); } queue.complete(); }); }), $btn(Lng.page[lang], Lng.infoPage[lang], function() { var els = $C('de-entry', doc), i = 6, loaded = 0; $alert(Lng.loading[lang], 'load-pages', true); while(i--) { ajaxLoad(aib.getPageUrl(brd, i), true, function(idx, form, xhr) { for(var inf, el, len = this.length, i = 0; i < len; ++i) { el = this[i]; if(el.getAttribute('de-host') === aib.host && el.getAttribute('de-board') === brd) { inf = $c('de-fav-inf-page', el); if((new RegExp('(?:№|No.|>)\\s*' + el.getAttribute('de-num') + '\\s*<')) .test(form.innerHTML)) { inf.innerHTML = '@' + idx; } else if(loaded === 5 && !inf.textContent.contains('@')) { inf.innerHTML = '@?'; } } } if(loaded === 5) { closeAlert($id('de-alert-load-pages')); } loaded++; }.bind(els, i), function(eCode, eMsg, xhr) { if(loaded === 5) { closeAlert($id('de-alert-load-pages')); } loaded++; }); } }), $btn(Lng.clear[lang], Lng.clrDeleted[lang], function() { var i, len, els, queue = new $queue(4, function(qIdx, num, el) { var node = $c('de-fav-inf-old', el); node.className = 'de-wait'; ajaxLoad(el.getAttribute('de-url'), false, function() { this.classList.remove('de-wait'); queue.end(qIdx); qIdx = null; }.bind(node), function(eCode, eMsg, xhr) { if(eCode === 404) { this.textContent = getErrorMessage(eCode, eMsg); this.classList.remove('de-wait'); el.setAttribute('de-removed', ''); } queue.end(qIdx); qIdx = el = null; }.bind(node)); }, function() { queue = null; clearFavoriteTable(); }); for(i = 0, els = $C('de-entry', doc), len = els.length; i < len; ++i) { queue.run(els[i]); } queue.complete(); }), $btn(Lng.remove[lang], Lng.clrSelected[lang], function() { $each($C('de-entry', doc), function(el) { if($t('input', el).checked) { el.setAttribute('de-removed', ''); } }); clearFavoriteTable(); }) ]); if(Cfg['animation']) { cont.className = 'de-content de-cfg-open'; } } //============================================================================================================ // SETTINGS WINDOW //============================================================================================================ function fixSettings() { function toggleBox(state, arr) { var i = arr.length, nState = !state; while(i--) { ($q(arr[i], doc) || {}).disabled = nState; } } toggleBox(Cfg['ajaxUpdThr'], [ 'input[info="noErrInTitle"]', 'input[info="favIcoBlink"]', 'input[info="markNewPosts"]', 'input[info="desktNotif"]' ]); toggleBox(Cfg['expandImgs'], [ 'input[info="resizeImgs"]', 'input[info="webmControl"]', 'input[info="webmVolume"]' ]); toggleBox(Cfg['preLoadImgs'], ['input[info="findImgFile"]']); toggleBox(Cfg['openImgs'], ['input[info="openGIFs"]']); toggleBox(Cfg['linksNavig'], [ 'input[info="linksOver"]', 'input[info="linksOut"]', 'input[info="markViewed"]', 'input[info="strikeHidd"]', 'input[info="noNavigHidd"]' ]); toggleBox(Cfg['addYouTube'] && Cfg['addYouTube'] !== 4, [ 'select[info="YTubeType"]', 'input[info="YTubeHD"]', 'input[info="addVimeo"]' ]); toggleBox(Cfg['addYouTube'], [ 'input[info="YTubeWidth"]', 'input[info="YTubeHeigh"]', 'input[info="YTubeTitles"]' ]); toggleBox(Cfg['ajaxReply'], ['input[info="sendErrNotif"]', 'input[info="scrAfterRep"]']); toggleBox(Cfg['ajaxReply'] === 2, [ 'input[info="postSameImg"]', 'input[info="removeEXIF"]', 'input[info="removeFName"]' ]); toggleBox(Cfg['addTextBtns'], ['input[info="txtBtnsLoc"]']); toggleBox(Cfg['updScript'], ['select[info="scrUpdIntrv"]']); toggleBox(Cfg['keybNavig'], ['input[info="loadPages"]']); } function lBox(id, isBlock, Fn) { var el = $new('input', {'info': id, 'type': 'checkbox'}, {'click': function() { toggleCfg(this.getAttribute('info')); fixSettings(); if(Fn) { Fn(this); } }}); el.checked = Cfg[id]; return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + Lng.cfg[id][lang])]); } function inpTxt(id, size, Fn) { return $new('input', {'info': id, 'type': 'text', 'size': size, 'value': Cfg[id]}, { 'keyup': Fn ? Fn : function() { saveCfg(this.getAttribute('info'), this.value); } }); } function optSel(id, isBlock, Fn) { for(var i = 0, x = Lng.cfg[id], len = x.sel[lang].length, el, opt = ''; i < len; i++) { opt += '<option value="' + i + '">' + x.sel[lang][i] + '</option>'; } el = $add('<select info="' + id + '">' + opt + '</select>'); el.addEventListener('change', Fn || function() { saveCfg(this.getAttribute('info'), this.selectedIndex); fixSettings(); }, false); el.selectedIndex = Cfg[id]; return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + x.txt[lang])]); } function cfgTab(name) { return $New('div', {'class': aib.cReply + ' de-cfg-tab-back', 'selected': false}, [$new('div', { 'class': 'de-cfg-tab', 'text': Lng.cfgTab[name][lang], 'info': name}, { 'click': function() { var el, id, pN = this.parentNode; if(pN.getAttribute('selected') === 'true') { return; } if(el = $c('de-cfg-body', doc)) { el.className = 'de-cfg-unvis'; $q('.de-cfg-tab-back[selected="true"]', doc).setAttribute('selected', false); } pN.setAttribute('selected', true); if(!(el = $id('de-cfg-' + (id = this.getAttribute('info'))))) { $after($id('de-cfg-bar'), el = id === 'filters' ? getCfgFilters() : id === 'posts' ? getCfgPosts() : id === 'images' ? getCfgImages() : id === 'links' ? getCfgLinks() : id === 'form' ? getCfgForm() : id === 'common' ? getCfgCommon() : getCfgInfo() ); if(id === 'filters') { updRowMeter.call($id('de-spell-edit')); } } el.className = 'de-cfg-body'; if(id === 'filters') { $id('de-spell-edit').value = spells.list; } fixSettings(); } })]); } function updRowMeter() { var str, top = this.scrollTop, el = this.parentNode.previousSibling.firstChild, num = el.numLines || 1, i = 15; if(num - i < ((top / 12) | 0 + 1)) { str = ''; while(i--) { str += num++ + '<br>'; } el.insertAdjacentHTML('beforeend', str); el.numLines = num; } el.scrollTop = top; } function getCfgFilters() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-filters'}, [ lBox('hideBySpell', false, toggleSpells), $New('div', {'id': 'de-spell-panel'}, [ $new('a', { 'id': 'de-btn-addspell', 'text': Lng.add[lang], 'href': '#', 'class': 'de-abtn'}, { 'click': $pd, 'mouseover': addMenu, 'mouseout': removeMenu }), $new('a', {'text': Lng.apply[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) { $pd(e); saveCfg('hideBySpell', 1); $q('input[info="hideBySpell"]', doc).checked = true; toggleSpells(); }}), $new('a', {'text': Lng.clear[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) { $pd(e); $id('de-spell-edit').value = ''; toggleSpells(); }}), $add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Spells-' + (lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>') ]), $New('div', {'id': 'de-spell-div'}, [ $add('<div><div id="de-spell-rowmeter"></div></div>'), $New('div', null, [$new('textarea', {'id': 'de-spell-edit', 'wrap': 'off'}, { 'keydown': updRowMeter, 'scroll': updRowMeter })]) ]), lBox('sortSpells', true, function() { if(Cfg['sortSpells']) { toggleSpells(); } }), lBox('menuHiddBtn', true, null), lBox('hideRefPsts', true, null), lBox('delHiddPost', true, function() { $each($C('de-post-hide', dForm), function(el) { var wrap = el.post.wrap, hide = !wrap.classList.contains('de-hidden'); if(hide) { wrap.insertAdjacentHTML('beforebegin', '<span style="counter-increment: de-cnt 1;"></span>'); } else { $del(wrap.previousSibling); } wrap.classList.toggle('de-hidden'); }); updateCSS(); }) ]); } function getCfgPosts() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-posts'}, [ lBox('ajaxUpdThr', false, TNum ? function() { if(Cfg['ajaxUpdThr']) { updater.enable(); } else { updater.disable(); } } : null), $New('label', null, [ inpTxt('updThrDelay', 4, null), $txt(Lng.cfg['updThrDelay'][lang]) ]), $New('div', {'class': 'de-cfg-depend'}, [ lBox('noErrInTitle', true, null), lBox('favIcoBlink', true, null), lBox('markNewPosts', true, function() { firstThr.clearPostsMarks(); }), $if('Notification' in window, lBox('desktNotif', true, function() { if(Cfg['desktNotif']) { Notification.requestPermission(); } })) ]), optSel('expandPosts', true, null), optSel('postBtnsCSS', true, null), lBox('noSpoilers', true, updateCSS), lBox('noPostNames', true, updateCSS), lBox('noPostScrl', true, updateCSS), $New('div', null, [ lBox('correctTime', false, dateTime.toggleSettings), $add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Settings-time-' + (lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>') ]), $New('div', {'class': 'de-cfg-depend'}, [ $New('div', null, [ inpTxt('timeOffset', 3, null), $txt(Lng.cfg['timeOffset'][lang]) ]), $New('div', null, [ inpTxt('timePattern', 30, null), $txt(Lng.cfg['timePattern'][lang]) ]), $New('div', null, [ inpTxt('timeRPattern', 30, null), $txt(Lng.cfg['timeRPattern'][lang]) ]) ]) ]); } function getCfgImages() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-images'}, [ optSel('expandImgs', true, null), $New('div', {'style': 'padding-left: 25px;'}, [ lBox('resizeImgs', true, null), lBox('webmControl', true, null), inpTxt('webmVolume', 6, function() { var val = +this.value; saveCfg('webmVolume', val < 100 ? val : 100); }), $txt(Lng.cfg['webmVolume'][lang]) ]), $if(!nav.Presto, lBox('preLoadImgs', true, null)), $if(!nav.Presto, $New('div', {'class': 'de-cfg-depend'}, [ lBox('findImgFile', true, null) ])), lBox('openImgs', true, null), $New('div', {'class': 'de-cfg-depend'}, [ lBox('openGIFs', false, null)]), lBox('imgSrcBtns', true, null) ]); } function getCfgLinks() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-links'}, [ optSel('linksNavig', true, null), $New('div', {'class': 'de-cfg-depend'}, [ $New('div', null, [ inpTxt('linksOver', 6, function() { saveCfg('linksOver', +this.value | 0); }), $txt(Lng.cfg['linksOver'][lang]) ]), $New('div', null, [ inpTxt('linksOut', 6, function() { saveCfg('linksOut', +this.value | 0); }), $txt(Lng.cfg['linksOut'][lang]) ]), lBox('markViewed', true, null), lBox('strikeHidd', true, null), lBox('noNavigHidd', true, null) ]), lBox('crossLinks', true, null), lBox('insertNum', true, null), lBox('addMP3', true, null), lBox('addImgs', true, null), optSel('addYouTube', true, null), $New('div', {'class': 'de-cfg-depend'}, [ $New('div', null, [ optSel('YTubeType', false, null), inpTxt('YTubeWidth', 6, null), $txt('×'), inpTxt('YTubeHeigh', 6, null), $txt(' '), lBox('YTubeHD', false, null) ]), $if(!nav.Opera11 || nav.isGM, lBox('YTubeTitles', false, null)), lBox('addVimeo', true, null) ]) ]); } function getCfgForm() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-form'}, [ optSel('ajaxReply', true, null), $if(pr.form, $New('div', {'class': 'de-cfg-depend'}, [ $if(!nav.Opera11, $New('div', null, [ lBox('postSameImg', true, null), lBox('removeEXIF', false, null), lBox('removeFName', false, null), lBox('sendErrNotif', true, null) ])), lBox('scrAfterRep', true, null) ])), $if(pr.form, optSel('addPostForm', true, null)), lBox('favOnReply', true, null), $if(pr.subj, lBox('warnSubjTrip', false, null)), $if(pr.file && !aib.dobr && !nav.Presto, lBox('fileThumb', true, function() { for(var i = 0, ins = pr.fileInputs, len = ins.length; i < len; ++i) { ins[i].updateUtils(); } })), $if(pr.mail, $New('div', null, [ lBox('addSageBtn', false, null), lBox('saveSage', false, null) ])), $if(pr.capTr, optSel('captchaLang', true, null)), $if(pr.txta, $New('div', null, [ optSel('addTextBtns', false, function() { saveCfg('addTextBtns', this.selectedIndex); pr.addTextPanel(); }), lBox('txtBtnsLoc', false, pr.addTextPanel.bind(pr)) ])), $if(pr.passw, $New('div', null, [ inpTxt('passwValue', 20, PostForm.setUserPassw), $txt(Lng.cfg['userPassw'][lang]), $btn(Lng.change[lang], '', function() { $q('input[info="passwValue"]', doc).value = Math.round(Math.random() * 1e15).toString(32); PostForm.setUserPassw(); }) ])), $if(pr.name, $New('div', null, [ inpTxt('nameValue', 20, PostForm.setUserName), lBox('userName', false, PostForm.setUserName) ])), $New('div', null, [ $txt(Lng.dontShow[lang]), lBox('noBoardRule', false, updateCSS), $if(pr.gothr, lBox('noGoto', false, function() { $disp(pr.gothr); })), $if(pr.passw, lBox('noPassword', false, function() { $disp(pr.passw.parentNode.parentNode); })) ]) ]); } function getCfgCommon() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-common'}, [ optSel('scriptStyle', true, function() { saveCfg('scriptStyle', this.selectedIndex); $id('de-main').lang = getThemeLang(); }), $New('div', null, [ lBox('userCSS', false, updateCSS), addEditButton('css', function(Fn) { Fn(Cfg['userCSSTxt'], false, function() { saveCfg('userCSSTxt', this.value); updateCSS(); toggleContent('cfg', true); }); }) ]), lBox('attachPanel', true, function() { toggleContent('cfg', false); updateCSS(); }), lBox('panelCounter', true, updateCSS), lBox('rePageTitle', true, null), $if(nav.Anim, lBox('animation', true, null)), lBox('closePopups', true, null), $New('div', null, [ lBox('keybNavig', false, function() { if(Cfg['keybNavig']) { if(keyNav) { keyNav.enable(); } else { keyNav = new KeyNavigation(); } } else if(keyNav) { keyNav.disable(); } }), $btn(Lng.edit[lang], '', function(e) { $pd(e); if($id('de-alert-edit-keybnavig')) { return; } KeyNavigation.readKeys(function(keys) { var aEl, evtListener, temp = KeyEditListener.getEditMarkup(keys); $alert(temp[1], 'edit-keybnavig', false); aEl = $id('de-alert-edit-keybnavig'); evtListener = new KeyEditListener(aEl, keys, temp[0]); aEl.addEventListener('focus', evtListener, true); aEl.addEventListener('blur', evtListener, true); aEl.addEventListener('click', evtListener, true); aEl.addEventListener('keydown', evtListener, true); aEl.addEventListener('keyup', evtListener, true); }); }) ]), $New('div', {'class': 'de-cfg-depend'}, [ inpTxt('loadPages', 4, null), $txt(Lng.cfg['loadPages'][lang]) ]), $if(!nav.isChromeStorage && !nav.Presto || nav.isGM, $New('div', null, [ lBox('updScript', true, null), $New('div', {'class': 'de-cfg-depend'}, [ optSel('scrUpdIntrv', false, null), $btn(Lng.checkNow[lang], '', function() { $alert(Lng.loading[lang], 'updavail', true); checkForUpdates(true, function(html) { $alert(html, 'updavail', false); }); }) ]) ])), lBox('turnOff', true, function() { for(var dm in comCfg) { if(dm !== aib.dm && dm !== 'global' && dm !== 'lastUpd') { comCfg[dm]['disabled'] = Cfg['turnOff']; } } setStored('DESU_Config', JSON.stringify(comCfg) || ''); }) ]); } function getCfgInfo() { function getHiddenThrCount() { var b, tNum, count = 0; for(b in hThr) { for(tNum in hThr[b]) { count++; } } return count; } return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-info'}, [ $add('<div style="padding-bottom: 10px;">' + '<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/versions" ' + 'target="_blank">v' + version + '</a>&nbsp;|&nbsp;' + '<a href="http://www.freedollchan.org/scripts/" target="_blank">Freedollchan</a>&nbsp;|&nbsp;' + '<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/' + (lang ? 'home-en/' : '') + '" target="_blank">Github</a></div>'), $add('<div><div style="display: inline-block; vertical-align: top; width: 186px; height: 235px;">' + Lng.thrViewed[lang] + Cfg['stats']['view'] + '<br>' + Lng.thrCreated[lang] + Cfg['stats']['op'] + '<br>' + Lng.thrHidden[lang] + getHiddenThrCount() + '<br>' + Lng.postsSent[lang] + Cfg['stats']['reply'] + '</div>' + '<div style="display: inline-block; padding-left: 7px; height: 235px; ' + 'border-left: 1px solid grey;">' + new Logger().get().join('<br>') + '</div></div>'), $btn(Lng.debug[lang], Lng.infoDebug[lang], function() { $alert(Lng.infoDebug[lang] + ':<textarea readonly id="de-debug-info" class="de-editor"></textarea>', 'help-debug', false); $id('de-debug-info').value = JSON.stringify({ 'version': version, 'location': String(window.location), 'nav': nav, 'cfg': Cfg, 'sSpells': spells.list.split('\n'), 'oSpells': sesStorage['de-spells-' + brd + TNum], 'perf': new Logger().get() }, function(key, value) { if(key in defaultCfg) { if(value === defaultCfg[key] || key === 'nameValue' || key === 'passwValue') { return void 0; } } return key === 'stats' ? void 0 : value; }, '\t'); }) ]); } function addEditButton(name, getDataFn) { return $btn(Lng.edit[lang], Lng.editInTxt[lang], function(getData) { getData(function(val, isJSON, saveFn) { var ta = $new('textarea', { 'class': 'de-editor', 'value': isJSON ? JSON.stringify(val, null, '\t') : val }, null); $alert('', 'edit-' + name, false); $append($c('de-alert-msg', $id('de-alert-edit-' + name)), [ $txt(Lng.editor[name][lang]), ta, $btn(Lng.save[lang], Lng.saveChanges[lang], isJSON ? function(fun) { var data; try { data = JSON.parse(this.value.trim().replace(/[\n\r\t]/g, '') || '{}'); } finally { if(data) { fun(data); closeAlert($id('de-alert-edit-' + name)); closeAlert($id('de-alert-err-invaliddata')); } else { $alert(Lng.invalidData[lang], 'err-invaliddata', false); } } }.bind(ta, saveFn) : saveFn.bind(ta)) ]); }); }.bind(null, getDataFn)); } function addSettings(Set, id) { Set.appendChild($New('div', {'class': aib.cReply}, [ $new('div', {'id': 'de-cfg-head', 'text': 'Dollchan Extension Tools'}, null), $New('div', {'id': 'de-cfg-bar'}, [ cfgTab('filters'), cfgTab('posts'), cfgTab('images'), cfgTab('links'), $if(pr.form || pr.oeForm, cfgTab('form')), cfgTab('common'), cfgTab('info') ]), $New('div', {'id': 'de-cfg-btns'}, [ optSel('language', false, function() { saveCfg('language', lang = this.selectedIndex); $del($id('de-main')); $del($id('de-css')); $del($id('de-css-dynamic')); scriptCSS(); addPanel(); toggleContent('cfg', false); }), $New('div', {'style': 'float: right;'}, [ addEditButton('cfg', function(Fn) { Fn(Cfg, true, function(data) { saveComCfg(aib.dm, data); window.location.reload(); }); }), $if(nav.isGlobal, $btn(Lng.load[lang], Lng.loadGlobal[lang], function() { if(('global' in comCfg) && !$isEmpty(comCfg['global'])) { saveComCfg(aib.dm, null); window.location.reload(); } else { $alert(Lng.noGlobalCfg[lang], 'err-noglobalcfg', false); } })), $if(nav.isGlobal, $btn(Lng.save[lang], Lng.saveGlobal[lang], function() { var i, obj = {}, com = comCfg[aib.dm]; for(i in com) { if(com[i] !== defaultCfg[i] && i !== 'stats') { obj[i] = com[i]; } } saveComCfg('global', obj); toggleContent('cfg', true); })), $btn(Lng.reset[lang], Lng.resetCfg[lang], function() { if(confirm(Lng.conReset[lang])) { delStored('DESU_Config'); delStored('DESU_Favorites'); delStored('DESU_Posts_' + aib.dm); delStored('DESU_Threads_' + aib.dm); delStored('DESU_keys'); window.location.reload(); } }) ]), $new('div', {'style': 'clear: both;'}, null) ]) ])); $q('.de-cfg-tab[info="' + (id || 'filters') + '"]', Set).click(); } //============================================================================================================ // MENUS & POPUPS //============================================================================================================ function closeAlert(el) { if(el) { el.closeTimeout = null; if(Cfg['animation']) { nav.animEvent(el, function(node) { var p = node && node.parentNode; if(p) { p.removeChild(node); } }); el.classList.add('de-close'); } else { $del(el); } } } function $alert(txt, id, wait) { var node, el = $id('de-alert-' + id), cBtn = 'de-alert-btn' + (wait ? ' de-wait' : ''), tBtn = wait ? '' : '\u2716 '; if(el) { $t('div', el).innerHTML = txt.trim(); node = $t('span', el); node.className = cBtn; node.textContent = tBtn; clearTimeout(el.closeTimeout); if(!wait && Cfg['animation']) { nav.animEvent(el, function(node) { node.classList.remove('de-blink'); }); el.classList.add('de-blink'); } } else { el = $id('de-alert').appendChild($New('div', {'class': aib.cReply, 'id': 'de-alert-' + id}, [ $new('span', {'class': cBtn, 'text': tBtn}, {'click': function() { closeAlert(this.parentNode); }}), $add('<div class="de-alert-msg">' + txt.trim() + '</div>') ])); if(Cfg['animation']) { nav.animEvent(el, function(node) { node.classList.remove('de-open'); }); el.classList.add('de-open'); } } if(Cfg['closePopups'] && !wait && !id.contains('help') && !id.contains('edit')) { el.closeTimeout = setTimeout(closeAlert, 4e3, el); } } function showMenu(el, html, inPanel, onclick) { var y, pos, menu, cr = el.getBoundingClientRect(); if(Cfg['attachPanel'] && inPanel) { pos = 'fixed'; y = 'bottom: 25'; } else { pos = 'absolute'; y = 'top: ' + (window.pageYOffset + cr.bottom); } doc.body.insertAdjacentHTML('beforeend', '<div class="' + aib.cReply + ' de-menu" style="position: ' + pos + '; right: ' + (doc.documentElement.clientWidth - cr.right - window.pageXOffset) + 'px; ' + y + 'px;">' + html + '</div>'); menu = doc.body.lastChild; menu.addEventListener('mouseover', function(e) { clearTimeout(e.currentTarget.odelay); }, true); menu.addEventListener('mouseout', removeMenu, true); menu.addEventListener('click', function(e) { var el = e.target; if(el.className === 'de-menu-item') { this(el); do { el = el.parentElement; } while (!el.classList.contains('de-menu')); $del(el); } }.bind(onclick), false); } function addMenu(e) { e.target.odelay = setTimeout(function(el) { switch(el.id) { case 'de-btn-addspell': addSpellMenu(el); return; case 'de-btn-refresh': addAjaxPagesMenu(el); return; case 'de-btn-audio-off': addAudioNotifMenu(el); return; } }, Cfg['linksOver'], e.target); } function removeMenu(e) { var el = $c('de-menu', doc), rt = e.relatedTarget; clearTimeout(e.target.odelay); if(el && (!rt || (rt !== el && !el.contains(rt)))) { el.odelay = setTimeout($del, 75, el); } } function addSpellMenu(el) { showMenu(el, '<div style="display: inline-block; border-right: 1px solid grey;">' + '<span class="de-menu-item">' + ('#words,#exp,#exph,#imgn,#ihash,#subj,#name,#trip,#img,<br>') .split(',').join('</span><span class="de-menu-item">') + '</span></div><div style="display: inline-block;"><span class="de-menu-item">' + ('#sage,#op,#tlen,#all,#video,#vauthor,#num,#wipe,#rep,#outrep') .split(',').join('</span><span class="de-menu-item">') + '</span></div>', false, function(el) { var exp = el.textContent, idx = Spells.names.indexOf(exp.substr(1)); $txtInsert($id('de-spell-edit'), exp + ( TNum && exp !== '#op' && exp !== '#rep' && exp !== '#outrep' ? '[' + brd + ',' + TNum + ']' : '' ) + (Spells.needArg[idx] ? '(' : '')); }); } function addAjaxPagesMenu(el) { showMenu(el, '<span class="de-menu-item">' + Lng.selAjaxPages[lang].join('</span><span class="de-menu-item">') + '</span>', true, function(el) { loadPages(aProto.indexOf.call(el.parentNode.children, el) + 1); }); } function addAudioNotifMenu(el) { showMenu(el, '<span class="de-menu-item">' + Lng.selAudioNotif[lang].join('</span><span class="de-menu-item">') + '</span>', true, function(el) { var i = aProto.indexOf.call(el.parentNode.children, el); updater.enable(); updater.toggleAudio(i === 0 ? 3e4 : i === 1 ? 6e4 : i === 2 ? 12e4 : 3e5); $id('de-btn-audio-off').id = 'de-btn-audio-on'; }); } //============================================================================================================ // KEYBOARD NAVIGATION //============================================================================================================ function KeyNavigation() { KeyNavigation.readKeys(this._init.bind(this)); } KeyNavigation.version = 4; KeyNavigation.readKeys = function(Fn) { getStored('DESU_keys', function(str) { var tKeys, keys; if(!str) { this(KeyNavigation.getDefaultKeys()); return; } try { keys = JSON.parse(str); } finally { if(!keys) { this(KeyNavigation.getDefaultKeys()); return; } if(keys[0] !== KeyNavigation.version) { tKeys = KeyNavigation.getDefaultKeys(); switch(keys[0]) { case 1: keys[2][11] = tKeys[2][11]; keys[4] = tKeys[4]; case 2: keys[2][12] = tKeys[2][12]; keys[2][13] = tKeys[2][13]; keys[2][14] = tKeys[2][14]; keys[2][15] = tKeys[2][15]; keys[2][16] = tKeys[2][16]; case 3: keys[2][17] = keys[3][3]; keys[3][3] = keys[3].splice(4, 1)[0]; } keys[0] = KeyNavigation.version; setStored('DESU_keys', JSON.stringify(keys)); } if(keys[1] ^ !!nav.Firefox) { var mapFunc = nav.Firefox ? function mapFuncFF(key) { switch(key) { case 189: return 173; case 187: return 61; case 186: return 59; default: return key; } } : function mapFuncNonFF(key) { switch(key) { case 173: return 189; case 61: return 187; case 59: return 186; default: return key; } }; keys[1] = !!nav.Firefox; keys[2] = keys[2].map(mapFunc); keys[3] = keys[3].map(mapFunc); setStored('DESU_keys', JSON.stringify(keys)); } this(keys); } }.bind(Fn)); }; KeyNavigation.getDefaultKeys = function() { var isFirefox = !!nav.Firefox; var globKeys = [ /* One post/thread above */ 0x004B /* = K */, /* One post/thread below */ 0x004A /* = J */, /* Reply or create thread */ 0x0052 /* = R */, /* Hide selected thread/post */ 0x0048 /* = H */, /* Open previous page/picture */ 0x1025 /* = Ctrl+Left */, /* Send post (txt) */ 0xC00D /* = Alt+Enter */, /* Open/close favorites posts */ 0x4046 /* = Alt+F */, /* Open/close hidden posts */ 0x4048 /* = Alt+H */, /* Open/close panel */ 0x0050 /* = P */, /* Mask/unmask images */ 0x0042 /* = B */, /* Open/close settings */ 0x4053 /* = Alt+S */, /* Expand current image */ 0x0049 /* = I */, /* Bold text */ 0xC042 /* = Alt+B */, /* Italic text */ 0xC049 /* = Alt+I */, /* Strike text */ 0xC054 /* = Alt+T */, /* Spoiler text */ 0xC050 /* = Alt+P */, /* Code text */ 0xC043 /* = Alt+C */, /* Open next page/picture */ 0x1027 /* = Ctrl+Right */ ]; var nonThrKeys = [ /* One post above */ 0x004D /* = M */, /* One post below */ 0x004E /* = N */, /* Open thread */ 0x0056 /* = V */, /* Expand thread */ 0x0045 /* = E */ ]; var thrKeys = [ /* Update thread */ 0x0055 /* = U */ ]; return [KeyNavigation.version, isFirefox, globKeys, nonThrKeys, thrKeys]; }; KeyNavigation.prototype = { cPost: null, enabled: false, gKeys: null, lastPage: 0, lastPageOffset: 0, ntKeys: null, paused: false, tKeys: null, clear: function(lastPage) { this.cPost = null; this.lastPage = lastPage; this.lastPageOffset = 0; }, disable: function() { if(this.enabled) { if(this.cPost) { this.cPost.unselect(); } doc.removeEventListener('keydown', this, true); this.enabled = false; } }, enable: function() { if(!this.enabled) { this.clear(pageNum); doc.addEventListener('keydown', this, true); this.enabled = true; } }, handleEvent: function(e) { if(this.paused) { return; } var temp, post, scrollToThread, globIdx, idx, curTh = e.target.tagName, kc = e.keyCode | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) | (e.altKey ? 0x4000 : 0) | (curTh === 'TEXTAREA' || (curTh === 'INPUT' && e.target.type === 'text') ? 0x8000 : 0); if(kc === 0x74 || kc === 0x8074) { // F5 if(TNum) { return; } if(Attachment.viewer) { Attachment.viewer.close(null); Attachment.viewer = null; } loadPages(+Cfg['loadPages']); } else if(kc === 0x1B) { // ESC if(Attachment.viewer) { Attachment.viewer.close(null); Attachment.viewer = null; return; } if(this.cPost) { this.cPost.unselect(); this.cPost = null; } if(TNum) { firstThr.clearPostsMarks(); } this.lastPageOffset = 0; } else if(kc === 0x801B) { // ESC (txt) e.target.blur(); } else { globIdx = this.gKeys.indexOf(kc); switch(globIdx) { case 2: // Reply or create thread if(pr.form) { if(!this.cPost && TNum && Cfg['addPostForm'] === 3) { this.cPost = firstThr.op; } if(this.cPost) { pr.showQuickReply(this.cPost, this.cPost.num, true); } else { pr.showMainReply(Cfg['addPostForm'] === 1, null); } } break; case 3: // Hide selected thread/post post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { post.toggleUserVisib(); this._scroll(post, false, post.isOp); } break; case 4: // Open previous page/picture if(Attachment.viewer) { Attachment.viewer.navigate(false); } else if(TNum || pageNum !== aib.firstPage) { window.location.pathname = aib.getPageUrl(brd, TNum ? 0 : pageNum - 1); } break; case 5: // Send post (txt) if(e.target !== pr.txta && e.target !== pr.cap) { return; } pr.subm.click(); break; case 6: // Open/close favorites posts toggleContent('fav', false); break; case 7: // Open/close hidden posts toggleContent('hid', false); break; case 8: // Open/close panel $disp($id('de-panel').lastChild); break; case 9: // Mask/unmask images toggleCfg('maskImgs'); updateCSS(); break; case 10: // Open/close settings toggleContent('cfg', false); break; case 11: // Expand current image post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { post.toggleImages(!post.imagesExpanded); } break; case 12: // Bold text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-bold').click(); break; case 13: // Italic text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-italic').click(); break; case 14: // Strike text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-strike').click(); break; case 15: // Spoiler text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-spoil').click(); break; case 16: // Code text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-code').click(); break; case 17: // Open next page/picture if(Attachment.viewer) { Attachment.viewer.navigate(true); } else if(!TNum && this.lastPage !== aib.lastPage) { window.location.pathname = aib.getPageUrl(brd, this.lastPage + 1); } break; case -1: if(TNum) { idx = this.tKeys.indexOf(kc); if(idx === 0) { // Update thread Thread.loadNewPosts(null); break; } return; } idx = this.ntKeys.indexOf(kc); if(idx === -1) { return; } else if(idx === 2) { // Open thread post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { if(nav.Firefox) { GM_openInTab(aib.getThrdUrl(brd, post.tNum), false, true); } else { window.open(aib.getThrdUrl(brd, post.tNum), '_blank'); } } break; } else if(idx === 3) { // Expand/collapse thread post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { if(post.thr.loadedOnce && post.thr.op.next.count === 1) { temp = post.thr.nextNotHidden; post.thr.load(visPosts, !!temp, null); post = (temp || post.thr).op; } else { post.thr.load(1, false, null); post = post.thr.op; } scrollTo(0, pageYOffset + post.topCoord); if(this.cPost && this.cPost !== post) { this.cPost.unselect(); this.cPost = post; } } break; } default: scrollToThread = !TNum && (globIdx === 0 || globIdx === 1); this._scroll(this._getFirstVisPost(scrollToThread, false), globIdx === 0 || idx === 0, scrollToThread); } } e.stopPropagation(); $pd(e); }, pause: function() { this.paused = true; }, resume: function(keys) { this.gKeys = keys[2]; this.ntKeys = keys[3]; this.tKeys = keys[4]; this.paused = false; }, _getFirstVisPost: function(getThread, getFull) { var post, tPost; if(this.lastPageOffset !== pageYOffset) { post = getThread ? firstThr : firstThr.op; while(post.topCoord < 1) { tPost = post.next; if(!tPost) { break; } post = tPost; } if(this.cPost) { this.cPost.unselect(); } this.cPost = getThread ? getFull ? post.op : post.op.prev : getFull ? post : post.prev; this.lastPageOffset = pageYOffset; } return this.cPost; }, _getNextVisPost: function(cPost, isOp, toUp) { var thr; if(isOp) { thr = cPost ? toUp ? cPost.thr.prevNotHidden : cPost.thr.nextNotHidden : firstThr.hidden ? firstThr.nextNotHidden : firstThr; return thr ? thr.op : null; } return cPost ? cPost.getAdjacentVisPost(toUp) : firstThr.hidden || firstThr.op.hidden ? firstThr.op.getAdjacentVisPost(toUp) : firstThr.op; }, _init: function(keys) { this.enabled = true; this.lastPage = pageNum; this.gKeys = keys[2]; this.ntKeys = keys[3]; this.tKeys = keys[4]; doc.addEventListener('keydown', this, true); }, _scroll: function(post, toUp, toThread) { var next = this._getNextVisPost(post, toThread, toUp); if(!next) { if(!TNum && (toUp ? pageNum > aib.firstPage : this.lastPage < aib.lastPage)) { window.location.pathname = aib.getPageUrl(brd, toUp ? pageNum - 1 : this.lastPage + 1); } return; } if(post) { post.unselect(); } if(toThread) { next.el.scrollIntoView(); } else { scrollTo(0, pageYOffset + next.el.getBoundingClientRect().top - Post.sizing.wHeight / 2 + next.el.clientHeight / 2); } this.lastPageOffset = pageYOffset; next.select(); this.cPost = next; } } function KeyEditListener(alertEl, keys, allKeys) { var j, k, i, len, aInputs = aProto.slice.call($C('de-input-key', alertEl)); for(i = 0, len = allKeys.length; i < len; ++i) { k = allKeys[i]; if(k !== 0) { for(j = i + 1; j < len; ++j) { if(k === allKeys[j]) { aInputs[i].classList.add('de-error-key'); aInputs[j].classList.add('de-error-key'); break; } } } } this.aEl = alertEl; this.keys = keys; this.initKeys = JSON.parse(JSON.stringify(keys)); this.allKeys = allKeys; this.allInputs = aInputs; this.errCount = $C('de-error-key', alertEl).length; if(this.errCount !== 0) { this.saveButton.disabled = true; } } // Browsers have different codes for these keys (see KeyNavigation.readKeys): // Firefox - '-' - 173, '=' - 61, ';' - 59 // Chrome/Opera: '-' - 189, '=' - 187, ';' - 186 KeyEditListener.keyCodes = ['',,,,,,,,'Backspace',/* Tab */,,,,'Enter',,,'Shift','Ctrl','Alt', /* Pause/Break */,/* Caps Lock */,,,,,,,/* Escape */,,,,,'Space',/* Page Up */, /* Page Down */,/* End */,/* Home */,'←','↑','→','↓',,,,,/* Insert */,/* Delete */,,'0','1','2', '3','4','5','6','7','8','9',,';',,'=',,,,'A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',/* Left WIN Key */,/* Right WIN Key */, /* Select key */,,,'Numpad 0','Numpad 1','Numpad 2','Numpad 3','Numpad 4','Numpad 5','Numpad 6', 'Numpad 7','Numpad 8','Numpad 9','Numpad *','Numpad +',,'Numpad -','Numpad .','Numpad /', /* F1 */,/* F2 */,/* F3 */,/* F4 */,/* F5 */,/* F6 */,/* F7 */,/* F8 */,/* F9 */,/* F10 */, /* F11 */,/* F12 */,,,,,,,,,,,,,,,,,,,,,/* Num Lock */,/* Scroll Lock */,,,,,,,,,,,,,,,,,,,,,,,, ,,,,'-',,,,,,,,,,,,,';','=',',','-','.','/','`',,,,,,,,,,,,,,,,,,,,,,,,,,,'[','\\',']','\'' ]; KeyEditListener.getStrKey = function(key) { var str = ''; if(key & 0x1000) { str += 'Ctrl+'; } if(key & 0x2000) { str += 'Shift+'; } if(key & 0x4000) { str += 'Alt+'; } str += KeyEditListener.keyCodes[key & 0xFFF]; return str; }; KeyEditListener.getEditMarkup = function(keys) { var allKeys = []; var html = Lng.keyNavEdit[lang] .replace(/%l/g, '<label class="de-block">') .replace(/%\/l/g, '</label>') .replace(/%i([2-4])([0-9]+)(t)?/g, function(aKeys, all, id1, id2, isText) { var key = this[+id1][+id2]; aKeys.push(key); return '<input class="de-input-key" type="text" de-id1="' + id1 + '" de-id2="' + id2 + '" size="26" value="' + KeyEditListener.getStrKey(key) + (isText ? '" de-text' : '"' ) + ' readonly></input>'; }.bind(keys, allKeys)) + '<input type="button" id="de-keys-save" value="' + Lng.save[lang] + '"></input>' + '<input type="button" id="de-keys-reset" value="' + Lng.reset[lang] + '"></input>'; return [allKeys, html]; }; KeyEditListener.setTitle = function(el, idx) { var title = el.getAttribute('de-title'); if(keyNav && idx !== -1) { title += ' [' + KeyEditListener.getStrKey(keyNav.gKeys[idx]) + ']'; } el.title = title; }; KeyEditListener.prototype = { cEl: null, cKey: -1, errorInput: false, get saveButton() { var val = $id('de-keys-save'); Object.defineProperty(this, 'saveButton', { value: val, configurable: true }); return val; }, handleEvent: function(e) { var key, keyStr, keys, str, id, temp, el = e.target; switch(e.type) { case 'blur': if(keyNav && this.errCount === 0) { keyNav.resume(this.keys); } this.cEl = null; return; case 'focus': if(keyNav) { keyNav.pause(); } this.cEl = el; return; case 'click': if(el.id === 'de-keys-reset') { this.keys = KeyNavigation.getDefaultKeys(); this.initKeys = KeyNavigation.getDefaultKeys(); if(keyNav) { keyNav.resume(this.keys); } temp = KeyEditListener.getEditMarkup(this.keys); this.allKeys = temp[0]; $c('de-alert-msg', this.aEl).innerHTML = temp[1]; this.allInputs = aProto.slice.call($C('de-input-key', this.aEl)); this.errCount = 0; delete this.saveButton; break; } else if(el.id === 'de-keys-save') { keys = this.keys; setStored('DESU_keys', JSON.stringify(keys)); } else if(el.className === 'de-alert-btn') { keys = this.initKeys; } else { return; } if(keyNav) { keyNav.resume(keys); } closeAlert($id('de-alert-edit-keybnavig')); break; case 'keydown': if(!this.cEl) { return; } key = e.keyCode; if(key === 0x1B || key === 0x2E) { // ESC, DEL this.cEl.value = ''; this.cKey = 0; this.errorInput = false; break; } keyStr = KeyEditListener.keyCodes[key]; if(keyStr == null) { this.cKey = -1; return; } str = ''; if(e.ctrlKey) { str += 'Ctrl+'; } if(e.shiftKey) { str += 'Shift+'; } if(e.altKey) { str += 'Alt+'; } if(key === 16 || key === 17 || key === 18) { this.errorInput = true; } else { this.cKey = key | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) | (e.altKey ? 0x4000 : 0) | (this.cEl.hasAttribute('de-text') ? 0x8000 : 0); this.errorInput = false; str += keyStr; } this.cEl.value = str; break; case 'keyup': var idx, rIdx, oKey, rEl, isError, el = this.cEl, key = this.cKey; if(!el || key === -1) { return; } isError = el.classList.contains('de-error-key'); if(!this.errorInput && key !== -1) { idx = this.allInputs.indexOf(el); oKey = this.allKeys[idx]; if(oKey === key) { this.errorInput = false; break; } rIdx = key === 0 ? -1 : this.allKeys.indexOf(key); this.allKeys[idx] = key; if(isError) { idx = this.allKeys.indexOf(oKey); if(idx !== -1 && this.allKeys.indexOf(oKey, idx + 1) === -1) { rEl = this.allInputs[idx]; if(rEl.classList.contains('de-error-key')) { this.errCount--; rEl.classList.remove('de-error-key'); } } if(rIdx === -1) { this.errCount--; el.classList.remove('de-error-key'); } } if(rIdx === -1) { this.keys[+el.getAttribute('de-id1')][+el.getAttribute('de-id2')] = key; if(this.errCount === 0) { this.saveButton.disabled = false; } this.errorInput = false; break; } rEl = this.allInputs[rIdx]; if(!rEl.classList.contains('de-error-key')) { this.errCount++; rEl.classList.add('de-error-key'); } } if(!isError) { this.errCount++; el.classList.add('de-error-key'); } if(this.errCount !== 0) { this.saveButton.disabled = true; } } $pd(e); } }; //============================================================================================================ // FORM SUBMIT //============================================================================================================ function getSubmitError(dc) { var i, els, el, err = '', form = $q(aib.qDForm, dc); if(dc.body.hasChildNodes() && !form) { for(i = 0, els = $Q(aib.qError, dc); el = els[i++];) { err += el.innerHTML + '\n'; } if(!(err = err.replace(/<a [^>]+>Назад.+|<br.+/, ''))) { err = Lng.error[lang] + ':\n' + dc.body.innerHTML; } err = /:null|successful|uploaded|updating|обновл|удален[о\.]/i.test(err) ? '' : err.replace(/"/g, "'"); } return err; } function checkUpload(dc) { if(aib.krau) { pr.form.action = pr.form.action.split('?')[0]; $id('postform_row_progress').style.display = 'none'; aib.btnZeroLUTime.click(); } var el, err = getSubmitError(dc); if(err) { if(pr.isQuick) { pr.setReply(true, false); } if(/captch|капч|подтвер|verifizie/i.test(err)) { pr.refreshCapImg(true); } $alert(err, 'upload', false); updater.sendErrNotif(); return; } pr.txta.value = ''; if(pr.file) { pr.delFilesUtils(); } if(pr.video) { pr.video.value = ''; } Cfg['stats'][pr.tNum ? 'reply' : 'op']++; saveComCfg(aib.dm, Cfg); if(!pr.tNum) { window.location = aib.getThrdUrl(brd, aib.getTNum($q(aib.qDForm, dc))); return; } el = !aib._55ch && !aib.belch && (aib.qPostRedir === null || $q(aib.qPostRedir, dc)) ? $q(aib.qDForm, dc) : null; if(TNum) { firstThr.clearPostsMarks(); if(el) { firstThr.loadNewFromForm(el); closeAlert($id('de-alert-upload')); if(Cfg['scrAfterRep']) { scrollTo(0, pageYOffset + firstThr.last.el.getBoundingClientRect().top); } } else { firstThr.loadNew(function(eCode, eMsg, np, xhr) { infoLoadErrors(eCode, eMsg, 0); closeAlert($id('de-alert-upload')); if(Cfg['scrAfterRep']) { scrollTo(0, pageYOffset + firstThr.last.el.getBoundingClientRect().top); } }, true); } } else { if(el) { pByNum[pr.tNum].thr.loadFromForm(visPosts, false, el); closeAlert($id('de-alert-upload')); } else { pByNum[pr.tNum].thr.load(visPosts, false, closeAlert.bind(window, $id('de-alert-upload'))); } } pr.closeQReply(); pr.refreshCapImg(false); } function endDelete() { var el = $id('de-alert-deleting'); if(el) { closeAlert(el); $alert(Lng.succDeleted[lang], 'deleted', false); } } function checkDelete(dc) { var el, i, els, len, post, tNums, num, err = getSubmitError(dc); if(err) { $alert(Lng.errDelete[lang] + err, 'deleting', false); updater.sendErrNotif(); return; } tNums = []; num = (doc.location.hash.match(/\d+/) || [null])[0]; if(num && (post = pByNum[num])) { if(!post.isOp) { post.el.className = aib.cReply; } doc.location.hash = ''; } for(i = 0, els = $Q('.' + aib.cRPost + ' input:checked', dForm), len = els.length; i < len; ++i) { el = els[i]; el.checked = false; if(!TNum && tNums.indexOf(num = aib.getPostEl(el).post.tNum) === -1) { tNums.push(num); } } if(TNum) { firstThr.clearPostsMarks(); firstThr.loadNew(function(eCode, eMsg, np, xhr) { infoLoadErrors(eCode, eMsg, 0); endDelete(); }, false); } else { tNums.forEach(function(tNum) { pByNum[tNum].thr.load(visPosts, false, endDelete); }); } } function html5Submit(form, button, fn) { this.boundary = '---------------------------' + Math.round(Math.random() * 1e11); this.data = []; this.busy = 0; this.error = false; this.url = form.action; this.fn = fn; $each($Q('input:not([type="submit"]):not([type="button"]), textarea, select', form), this.append.bind(this)); this.append(button); this.submit(); } html5Submit.prototype = { append: function(el) { var file, fName, idx, fr, pre = '--' + this.boundary + '\r\nContent-Disposition: form-data; name="' + el.name + '"'; if(el.type === 'file' && el.files.length > 0) { file = el.files[0]; fName = file.name; this.data.push(pre + '; filename="' + ( !Cfg['removeFName'] ? fName : ' ' + fName.substring(fName.lastIndexOf('.')) ) + '"\r\nContent-type: ' + file.type + '\r\n\r\n', null, '\r\n'); idx = this.data.length - 2; if(!/^image\/(?:png|jpeg)$|^video\/webm$/.test(file.type)) { this.data[idx] = file; return; } fr = new FileReader(); fr.onload = function(name, e) { var dat = this.clearImage(e.target.result, el.obj.imgFile, Cfg['postSameImg'] && String(Math.round(Math.random() * 1e6))); if(dat) { this.data[idx] = new Blob(dat); this.busy--; this.submit(); } else { this.error = true; $alert(Lng.fileCorrupt[lang] + name, 'upload', false); } }.bind(this, fName); fr.readAsArrayBuffer(file); this.busy++; } else if((el.type !== 'checkbox' && el.type !== 'radio') || el.checked) { this.data.push(pre + '\r\n\r\n' + el.value + '\r\n'); } }, submit: function() { if(this.error || this.busy !== 0) { return; } this.data.push('--' + this.boundary + '--\r\n'); $xhr({ 'method': 'POST', 'headers': {'Content-type': 'multipart/form-data; boundary=' + this.boundary}, 'data': new Blob(this.data), 'url': nav.fixLink(this.url), 'onreadystatechange': function(xhr) { if(xhr.readyState === 4) { if(xhr.status === 200) { this($DOM(xhr.responseText)); } else { $alert(xhr.status === 0 ? Lng.noConnect[lang] : 'HTTP [' + xhr.status + '] ' + xhr.statusText, 'upload', false); } } }.bind(this.fn) }); }, readExif: function(data, off, len) { var i, j, dE, tag, tgLen, xRes = 0, yRes = 0, resT = 0, dv = new DataView(data, off), le = String.fromCharCode(dv.getUint8(0), dv.getUint8(1)) !== 'MM'; if(dv.getUint16(2, le) !== 0x2A) { return null; } i = dv.getUint32(4, le); if(i > len) { return null; } for(tgLen = dv.getUint16(i, le), j = 0; j < tgLen; j++) { tag = dv.getUint16(dE = i + 2 + 12 * j, le); if(tag === 0x0128) { resT = dv.getUint16(dE + 8, le) - 1; } else if(tag === 0x011A || tag === 0x011B) { dE = dv.getUint32(dE + 8, le); if(dE > len) { return null; } if(tag === 0x11A) { xRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le)); } else { yRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le)); } } } xRes = xRes || yRes; yRes = yRes || xRes; return new Uint8Array([resT & 0xFF, xRes >> 8, xRes & 0xFF, yRes >> 8, yRes & 0xFF]); }, clearImage: function(data, extraData, rand) { var tmp, i, len, deep, val, lIdx, jpgDat, img = new Uint8Array(data), rExif = !!Cfg['removeEXIF'], rv = extraData ? rand ? [img, extraData, rand] : [img, extraData] : rand ? [img, rand] : [img]; if(!Cfg['postSameImg'] && !rExif && !extraData) { return rv; } // JPG if(img[0] === 0xFF && img[1] === 0xD8) { for(i = 2, deep = 1, len = img.length - 1, val = [null, null], lIdx = 2, jpgDat = null; i < len; ) { if(img[i] === 0xFF) { if(rExif) { if(!jpgDat && deep === 1) { if(img[i + 1] === 0xE1 && img[i + 4] === 0x45) { jpgDat = this.readExif(data, i + 10, (img[i + 2] << 8) + img[i + 3]); } else if(img[i + 1] === 0xE0 && img[i + 7] === 0x46 && (img[i + 2] !== 0 || img[i + 3] >= 0x0E || img[i + 15] !== 0xFF)) { jpgDat = img.subarray(i + 11, i + 16); } } if((img[i + 1] >> 4) === 0xE || img[i + 1] === 0xFE) { if(lIdx !== i) { val.push(img.subarray(lIdx, i)); } i += 2 + (img[i + 2] << 8) + img[i + 3]; lIdx = i; continue; } } else if(img[i + 1] === 0xD8) { deep++; i++; continue; } if(img[i + 1] === 0xD9 && --deep === 0) { break; } } i++; } i += 2; if(!extraData && len - i > 75) { i = len; } if(lIdx === 2) { if(i !== len) { rv[0] = new Uint8Array(data, 0, i); } return rv; } val[0] = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0, 0, 0x0E, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1]); val[1] = jpgDat || new Uint8Array([0, 0, 1, 0, 1]); val.push(img.subarray(lIdx, i)); if(extraData) { val.push(extraData); } if(rand) { val.push(rand); } return val; } // PNG if(img[0] === 0x89 && img[1] === 0x50) { for(i = 0, len = img.length - 7; i < len && (img[i] !== 0x49 || img[i + 1] !== 0x45 || img[i + 2] !== 0x4E || img[i + 3] !== 0x44); i++) {} i += 8; if(i !== len && (extraData || len - i <= 75)) { rv[0] = new Uint8Array(data, 0, i); } return rv; } // WEBM if(img[0] === 0x1a && img[1] === 0x45 && img[2] === 0xDF && img[3] === 0xA3) { return new WebmParser(data).addData(rand).getData(); } return null; } }; WebmParser = function(data) { var EBMLId = 0x1A45DFA3, segmentId = 0x18538067, voidId = 0xEC; function WebmElement(data, dataLength, offset) { var num, clz, id, size, headSize = 0; if(offset + 4 >= dataLength) { return; } num = data.getUint32(offset); clz = Math.clz32(num); if(clz > 3) { this.error = true; return; } id = num >>> (8 * (3 - clz)); headSize += clz + 1; offset += clz + 1; if(offset + 4 >= dataLength) { this.error = true; return; } num = data.getUint32(offset); clz = Math.clz32(num); if(clz > 3) { if((num & (0xFFFFFFFF >>> (clz + 1))) !== 0) { this.error = true; return; // We cannot handle webm-files with size greater than 4Gb :( } if(offset + 8 >= dataLength) { this.error = true; return; } headSize += 4; offset += 4; num = data.getUint32(offset); clz -= 4; } size = num >>> (8 * (3 - clz)); headSize += clz + 1; offset += clz + 1; if(offset + size > dataLength) { this.error = true; return; } this.data = data; this.offset = offset; this.endOffset = offset + size; this.id = id; this.headSize = headSize; this.size = size; } WebmElement.prototype = { error: false, id: 0 }; function Parser(data) { var dv = new DataView(data), len = data.byteLength, el = new WebmElement(dv, len, 0), offset = 0, voids = []; error: do { if(el.error || el.id !== EBMLId) { break; } this.EBML = el; offset += el.headSize + el.size; while(true) { el = new WebmElement(dv, len, offset); if(el.error) { break error; } if(el.id === segmentId) { this.segment = el; break; // Ignore everything after first segment } else if(el.id === voidId) { voids.push(el); } else { break error; } offset += el.headSize + el.size; } this.voids = voids; this.data = data; this.length = len; this.rv = [null]; this.error = false; return; } while(false); this.error = true; } Parser.prototype = { addData: function(data) { if(this.error || !data) { return this; } var size = typeof data === 'string' ? data.length : data.byteLength; if(size > 127) { this.error = true; return; } this.rv.push(new Uint8Array([voidId, 0x80 | size]), data); return this; }, getData: function() { if(this.error) { return null; } var len = this.segment.endOffset; this.rv[0] = len === this.length ? this.data : new Uint8Array(this.data, 0, len); return this.rv; } }; WebmParser = Parser; return new Parser(data); } //============================================================================================================ // CONTENT FEATURES //============================================================================================================ function initMessageFunctions() { window.addEventListener('message', function(e) { var temp, data = e.data.substring(1); switch(e.data[0]) { case 'A': if(data.substr(10, 5) === 'pform') { checkUpload($DOM(data.substr(15))); $q('iframe[name="de-iframe-pform"]', doc).src = 'about:blank'; } else { checkDelete($DOM(data.substr(15))); $q('iframe[name="de-iframe-dform"]', doc).src = 'about:blank'; } return; case 'B': $del($id('de-fav-wait')); $id('de-iframe-fav').style.height = data + 'px'; return; } }, false); } function detectImgFile(ab) { var i, j, dat = new Uint8Array(ab), len = dat.length; /* JPG [ff d8 ff e0] = [яШяа] */ if(dat[0] === 0xFF && dat[1] === 0xD8) { for(i = 0, j = 0; i < len - 1; i++) { if(dat[i] === 0xFF) { /* Built-in JPG */ if(dat[i + 1] === 0xD8) { j++; /* JPG end [ff d9] */ } else if(dat[i + 1] === 0xD9 && --j === 0) { i += 2; break; } } } /* PNG [89 50 4e 47] = [‰PNG] */ } else if(dat[0] === 0x89 && dat[1] === 0x50) { for(i = 0; i < len - 7; i++) { /* PNG end [49 45 4e 44 ae 42 60 82] */ if(dat[i] === 0x49 && dat[i + 1] === 0x45 && dat[i + 2] === 0x4E && dat[i + 3] === 0x44) { i += 8; break; } } } else { return {}; } /* Ignore small files */ if(i !== len && len - i > 60) { for(len = i + 90; i < len; i++) { /* 7Z [37 7a bc af] = [7zјЇ] */ if(dat[i] === 0x37 && dat[i + 1] === 0x7A && dat[i + 2] === 0xBC) { return {'type': 0, 'idx': i, 'data': ab}; /* ZIP [50 4b 03 04] = [PK..] */ } else if(dat[i] === 0x50 && dat[i + 1] === 0x4B && dat[i + 2] === 0x03) { return {'type': 1, 'idx': i, 'data': ab}; /* RAR [52 61 72 21] = [Rar!] */ } else if(dat[i] === 0x52 && dat[i + 1] === 0x61 && dat[i + 2] === 0x72) { return {'type': 2, 'idx': i, 'data': ab}; /* OGG [4f 67 67 53] = [OggS] */ } else if(dat[i] === 0x4F && dat[i + 1] === 0x67 && dat[i + 2] === 0x67) { return {'type': 3, 'idx': i, 'data': ab}; /* MP3 [0x49 0x44 0x33] = [ID3] */ } else if(dat[i] === 0x49 && dat[i + 1] === 0x44 && dat[i + 2] === 0x33) { return {'type': 4, 'idx': i, 'data': ab}; } } } return {}; } function workerQueue(mReqs, wrkFn, errFn) { if(!nav.hasWorker) { this.run = this._runSync.bind(wrkFn); return; } this.queue = new $queue(mReqs, this._createWrk.bind(this), null); this.run = this._runWrk; this.wrks = new $workers('self.onmessage = function(e) {\ var info = (' + String(wrkFn) + ')(e.data[1]);\ if(info.data) {\ self.postMessage([e.data[0], info], [info.data]);\ } else {\ self.postMessage([e.data[0], info]);\ }\ }', mReqs); this.errFn = errFn; } workerQueue.prototype = { _runSync: function(data, transferObjs, Fn) { Fn(this(data)); }, onMess: function(Fn, e) { this.queue.end(e.data[0]); Fn(e.data[1]); }, onErr: function(qIdx, e) { this.queue.end(qIdx); this.errFn(e); }, _runWrk: function(data, transObjs, Fn) { this.queue.run([data, transObjs, this.onMess.bind(this, Fn)]); }, _createWrk: function(qIdx, num, data) { var w = this.wrks[qIdx]; w.onmessage = data[2]; w.onerror = this.onErr.bind(this, qIdx); w.postMessage([qIdx, data[0]], data[1]); }, clear: function() { this.wrks && this.wrks.clear(); this.wrks = null; } }; function addImgFileIcon(fName, info) { var app, ext, type = info['type']; if(typeof type !== 'undefined') { if(type === 2) { app = 'application/x-rar-compressed'; ext = 'rar'; } else if(type === 1) { app = 'application/zip'; ext = 'zip'; } else if(type === 0) { app = 'application/x-7z-compressed'; ext = '7z'; } else if(type === 3) { app = 'audio/ogg'; ext = 'ogg'; } else { app = 'audio/mpeg'; ext = 'mp3'; } this.insertAdjacentHTML('afterend', '<a href="' + window.URL.createObjectURL( new Blob([new Uint8Array(info['data']).subarray(info['idx'])], {'type': app}) ) + '" class="de-img-' + (type > 2 ? 'audio' : 'arch') + '" title="' + Lng.downloadFile[lang] + '" download="' + fName.substring(0, fName.lastIndexOf('.')) + '.' + ext + '">.' + ext + '</a>' ); } } function downloadImgData(url, Fn) { downloadObjInfo(Fn, { 'method': 'GET', 'url': url, 'onreadystatechange': function onDownloaded(url, e) { if(e.readyState !== 4) { return; } var isAb = e.responseType === 'arraybuffer'; if(e.status === 0 && isAb) { Fn(new Uint8Array(e.response)); } else if(e.status !== 200) { if(e.status === 404 || !url) { Fn(null); } else { downloadObjInfo(Fn, { 'method': 'GET', 'url': url, 'onreadystatechange': onDownloaded.bind(null, null) }); } } else if(isAb) { Fn(new Uint8Array(e.response)); } else { for(var len, i = 0, txt = e.responseText, rv = new Uint8Array(len = txt.length); i < len; ++i) { rv[i] = txt.charCodeAt(i) & 0xFF; } Fn(rv); } }.bind(null, url) }); } function downloadObjInfo(Fn, obj) { if(aib.fch && nav.Firefox && !obj.url.startsWith('blob')) { obj['overrideMimeType'] = 'text/plain; charset=x-user-defined'; GM_xmlhttpRequest(obj); } else { obj['responseType'] = 'arraybuffer'; try { $xhr(obj); } catch(e) { Fn(null); } } } function preloadImages(post) { if(!Cfg['preLoadImgs'] && !Cfg['openImgs'] && !isPreImg) { return; } var lnk, url, iType, nExp, el, i, len, els, queue, mReqs = post ? 1 : 4, cImg = 1, rjf = (isPreImg || Cfg['findImgFile']) && new workerQueue(mReqs, detectImgFile, function(e) { console.error("FILE DETECTOR ERROR, line: " + e.lineno + " - " + e.message); }); if(isPreImg || Cfg['preLoadImgs']) { queue = new $queue(mReqs, function(qIdx, num, dat) { downloadImgData(dat[0], function(idx, data) { if(data) { var a = this[1], fName = this[0].substring(this[0].lastIndexOf("/") + 1), aEl = $q(aib.qImgLink, aib.getImgWrap(a)); aEl.setAttribute('download', fName); a.href = window.URL.createObjectURL(new Blob([data], {'type': this[2]})); a.setAttribute('de-name', fName); if(this[2] === 'video/webm') { this[4].setAttribute('de-video', ''); } if(this[3]) { this[4].src = a.href; } if(rjf) { rjf.run(data.buffer, [data.buffer], addImgFileIcon.bind(aEl, fName)); } } queue.end(idx); if(Images_.progressId) { $alert(Lng.loadImage[lang] + cImg + '/' + len, Images_.progressId, true); } cImg++; }.bind(dat, qIdx)); }, function() { Images_.preloading = false; if(Images_.afterpreload) { Images_.afterpreload(); Images_.afterpreload = Images_.progressId = null; } rjf && rjf.clear(); rjf = queue = cImg = len = null; }); Images_.preloading = true; } for(i = 0, els = $Q(aib.qThumbImages, post || dForm), len = els.length; i < len; i++) { if(lnk = getAncestor(el = els[i], 'A')) { url = lnk.href; nExp = !!Cfg['openImgs']; if(/\.gif$/i.test(url)) { iType = 'image/gif'; } else { if(/\.jpe?g$/i.test(url)) { iType = 'image/jpeg'; } else if(/\.png$/i.test(url)) { iType = 'image/png'; } else if(/\.webm$/i.test(url)) { iType = 'video/webm'; nExp = false; } else { continue; } nExp &= !Cfg['openGIFs']; } if(queue) { queue.run([url, lnk, iType, nExp, el]); } else if(nExp) { el.src = url; // ! } } } queue && queue.complete(); } function getDataFromImg(img) { var cnv = Images_.canvas || (Images_.canvas = doc.createElement('canvas')); cnv.width = img.width; cnv.height = img.height; cnv.getContext('2d').drawImage(img, 0, 0); return new Uint8Array(atob(cnv.toDataURL("image/png").split(',')[1]).split('').map(function(a) { return a.charCodeAt(); })); } function loadDocFiles(imgOnly) { var els, files, progress, counter, count = 0, current = 1, warnings = '', tar = new $tar(), dc = imgOnly ? doc : doc.documentElement.cloneNode(true); Images_.queue = new $queue(4, function(qIdx, num, dat) { downloadImgData(dat[0], function(idx, data) { var name = this[1].replace(/[\\\/:*?"<>|]/g, '_'), el = this[2]; progress.value = current; counter.innerHTML = current; current++; if(this[3]) { if(!data) { warnings += '<br>' + Lng.cantLoad[lang] + '<a href="' + this[0] + '">' + this[0] + '</a><br>' + Lng.willSavePview[lang]; $alert(Lng.loadErrors[lang] + warnings, 'floadwarn', false); name = 'thumb-' + name.replace(/\.[a-z]+$/, '.png'); data = getDataFromImg(this[2]); } if(!imgOnly) { el.classList.add('de-thumb'); el.src = this[3].href = $q(aib.qImgLink, aib.getImgWrap(this[3])).href = name = 'images/' + name; } tar.addFile(name, data); } else if(data && data.length > 0) { tar.addFile(el.href = el.src = 'data/' + name, data); } else { $del(el); } Images_.queue.end(idx); }.bind(dat, qIdx)); }, function() { var u, a, dt; if(!imgOnly) { dt = doc.doctype; $t('head', dc).insertAdjacentHTML('beforeend', '<script type="text/javascript" src="data/dollscript.js"></script>'); tar.addString('data/dollscript.js', '(' + String(de_main_func) + ')(null, true);'); tar.addString( TNum + '.html', '<!DOCTYPE ' + dt.name + (dt.publicId ? ' PUBLIC "' + dt.publicId + '"' : dt.systemId ? ' SYSTEM' : '') + (dt.systemId ? ' "' + dt.systemId + '"' : '') + '>' + dc.outerHTML ); } u = window.URL.createObjectURL(tar.get()); a = $new('a', {'href': u, 'download': aib.dm + '-' + brd.replace(/[\\\/:*?"<>|]/g, '') + '-t' + TNum + (imgOnly ? '-images.tar' : '.tar')}, null); doc.body.appendChild(a); a.click(); setTimeout(function(el, url) { window.URL.revokeObjectURL(url); $del(el); }, 0, a, u); $del($id('de-alert-filesload')); Images_.queue = tar = warnings = count = current = imgOnly = progress = counter = null; }); els = aProto.slice.call($Q(aib.qThumbImages, $q('[de-form]', dc))); count += els.length; els.forEach(function(el) { var lnk, url; if(lnk = getAncestor(el, 'A')) { url = lnk.href; Images_.queue.run([url, lnk.getAttribute('de-name') || url.substring(url.lastIndexOf("/") + 1), el, lnk]); } }); if(!imgOnly) { files = []; $each($Q('script, link[rel="alternate stylesheet"], span[class^="de-btn-"],' + ' #de-main > div, .de-parea, #de-qarea, ' + aib.qPostForm, dc), $del); $each($T('a', dc), function(el) { var num, tc = el.textContent; if(tc[0] === '>' && tc[1] === '>' && (num = +tc.substr(2)) && (num in pByNum)) { el.href = aib.anchor + num; } else { el.href = getAbsLink(el.href); } if(!el.classList.contains('de-preflink')) { el.className = 'de-preflink ' + el.className; } }); $each($Q('.' + aib.cRPost, dc), function(post, i) { post.setAttribute('de-num', i === 0 ? TNum : aib.getPNum(post)); }); $each($Q('link, *[src]', dc), function(el) { if(els.indexOf(el) !== -1) { return; } var temp, i, ext, name, url = el.tagName === 'LINK' ? el.href : el.src; if(!this.test(url)) { $del(el); return; } name = url.substring(url.lastIndexOf("/") + 1).replace(/[\\\/:*?"<>|]/g, '_') .toLowerCase(); if(files.indexOf(name) !== -1) { temp = url.lastIndexOf('.'); ext = url.substring(temp); url = url.substring(0, temp); name = name.substring(0, name.lastIndexOf('.')); for(i = 0; ; ++i) { temp = name + '(' + i + ')' + ext; if(files.indexOf(temp) === -1) { break; } } name = temp; } files.push(name); Images_.queue.run([url, name, el, null]); count++; }.bind(new RegExp('^\\/\\/?|^https?:\\/\\/([^\\/]*\.)?' + regQuote(aib.dm) + '\\/', 'i'))); } $alert((imgOnly ? Lng.loadImage[lang] : Lng.loadFile[lang]) + '<br><progress id="de-loadprogress" value="0" max="' + count + '"></progress> <span>1</span>/' + count, 'filesload', true); progress = $id('de-loadprogress'); counter = progress.nextElementSibling; Images_.queue.complete(); els = null; } //============================================================================================================ // TIME CORRECTION //============================================================================================================ function dateTime(pattern, rPattern, diff, dtLang, onRPat) { if(dateTime.checkPattern(pattern)) { this.disabled = true; return; } this.regex = pattern .replace(/(?:[sihdny]\?){2,}/g, function() { return '(?:' + arguments[0].replace(/\?/g, '') + ')?'; }) .replace(/\-/g, '[^<]') .replace(/\+/g, '[^0-9]') .replace(/([sihdny]+)/g, '($1)') .replace(/[sihdny]/g, '\\d') .replace(/m|w/g, '([a-zA-Zа-яА-Я]+)'); this.pattern = pattern.replace(/[\?\-\+]+/g, '').replace(/([a-z])\1+/g, '$1'); this.diff = parseInt(diff, 10); this.sDiff = (this.diff < 0 ? '' : '+') + this.diff; this.arrW = Lng.week[dtLang]; this.arrM = Lng.month[dtLang]; this.arrFM = Lng.fullMonth[dtLang]; this.rPattern = rPattern; this.onRPat = onRPat; } dateTime.toggleSettings = function(el) { if(el.checked && (!/^[+-]\d{1,2}$/.test(Cfg['timeOffset']) || dateTime.checkPattern(Cfg['timePattern']))) { $alert(Lng.cTimeError[lang], 'err-correcttime', false); saveCfg('correctTime', 0); el.checked = false; } }; dateTime.checkPattern = function(val) { return !val.contains('i') || !val.contains('h') || !val.contains('d') || !val.contains('y') || !(val.contains('n') || val.contains('m')) || /[^\?\-\+sihdmwny]|mm|ww|\?\?|([ihdny]\?)\1+/.test(val); }; dateTime.prototype = { getRPattern: function(txt) { var k, p, a, str, i = 1, j = 0, m = txt.match(new RegExp(this.regex)); if(!m) { this.disabled = true; return false; } this.rPattern = ''; str = m[0]; while(a = m[i++]) { p = this.pattern[i - 2]; if((p === 'm' || p === 'y') && a.length > 3) { p = p.toUpperCase(); } k = str.indexOf(a, j); this.rPattern += str.substring(j, k) + '_' + p; j = k + a.length; } this.onRPat && this.onRPat(this.rPattern); return true; }, pad2: function(num) { return num < 10 ? '0' + num : num; }, fix: function(txt) { if(this.disabled || (!this.rPattern && !this.getRPattern(txt))) { return txt; } return txt.replace(new RegExp(this.regex, 'g'), function() { var i, a, t, second, minute, hour, day, month, year, dtime; for(i = 1; i < 8; i++) { a = arguments[i]; t = this.pattern[i - 1]; t === 's' ? second = a : t === 'i' ? minute = a : t === 'h' ? hour = a : t === 'd' ? day = a : t === 'n' ? month = a - 1 : t === 'y' ? year = a : t === 'm' && ( month = /^янв|^jan/i.test(a) ? 0 : /^фев|^feb/i.test(a) ? 1 : /^мар|^mar/i.test(a) ? 2 : /^апр|^apr/i.test(a) ? 3 : /^май|^may/i.test(a) ? 4 : /^июн|^jun/i.test(a) ? 5 : /^июл|^jul/i.test(a) ? 6 : /^авг|^aug/i.test(a) ? 7 : /^сен|^sep/i.test(a) ? 8 : /^окт|^oct/i.test(a) ? 9 : /^ноя|^nov/i.test(a) ? 10 : /^дек|^dec/i.test(a) && 11 ); } dtime = new Date(year.length === 2 ? '20' + year : year, month, day, hour, minute, second || 0); dtime.setHours(dtime.getHours() + this.diff); return this.rPattern .replace('_o', this.sDiff) .replace('_s', this.pad2(dtime.getSeconds())) .replace('_i', this.pad2(dtime.getMinutes())) .replace('_h', this.pad2(dtime.getHours())) .replace('_d', this.pad2(dtime.getDate())) .replace('_w', this.arrW[dtime.getDay()]) .replace('_n', this.pad2(dtime.getMonth() + 1)) .replace('_m', this.arrM[dtime.getMonth()]) .replace('_M', this.arrFM[dtime.getMonth()]) .replace('_y', ('' + dtime.getFullYear()).substring(2)) .replace('_Y', dtime.getFullYear()); }.bind(this)); } }; //============================================================================================================ // PLAYERS //============================================================================================================ YouTube = new function() { var instance, vData, embedType, videoType, width, height, isHD, loadTitles, vimReg = /^https?:\/\/(?:www\.)?vimeo\.com\/(?:[^\?]+\?clip_id=)?(\d+).*?$/; function addThumb(el, m, isYtube) { var wh = ' width="' + width + '" height="' + height + '"></a>'; if(isYtube) { el.innerHTML = '<a href="https://www.youtube.com/watch?v=' + m[1] + '" target="_blank">' + '<img class="de-video-thumb de-ytube" src="https://i.ytimg.com/vi/' + m[1] + '/0.jpg"' + wh; } else { el.innerHTML = '<a href="https://vimeo.com/' + m[1] + '" target="_blank">' + '<img class="de-video-thumb de-vimeo" src=""' + wh; GM_xmlhttpRequest({ 'method': 'GET', 'url': 'http://vimeo.com/api/v2/video/' + m[1] + '.json', 'onload': function(xhr){ this.setAttribute('src', JSON.parse(xhr.responseText)[0]['thumbnail_large']); }.bind(el.firstChild.firstChild) }); } } function addPlayer(el, m, isYtube) { var time, id = m[1], wh = ' width="' + width + '" height="' + height + '">'; if(isYtube) { time = (m[2] ? m[2] * 3600 : 0) + (m[3] ? m[3] * 60 : 0) + (m[4] ? +m[4] : 0); el.innerHTML = videoType === 1 ? '<iframe type="text/html" src="//www.youtube.com/embed/' + id + (isHD ? '?hd=1&' : '?') + 'start=' + time + '&html5=1&rel=0" frameborder="0"' + wh : '<embed type="application/x-shockwave-flash" src="https://www.youtube.com/v/' + id + (isHD ? '?hd=1&' : '?') + 'start=' + time + '" allowfullscreen="true" wmode="transparent"' + wh; } else { el.innerHTML = videoType === 1 ? '<iframe src="//player.vimeo.com/video/' + id + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen' + wh : '<embed type="application/x-shockwave-flash" src="http://vimeo.com/moogaloop.swf?clip_id=' + id + '&server=vimeo.com&color=00adef&fullscreen=1" ' + 'allowscriptaccess="always" allowfullscreen="true"' + wh; } } function addLink(post, m, loader, link, isYtube) { var msg, src, time, dataObj; post.hasYTube = true; if(post.ytInfo === null) { if(embedType === 2) { addPlayer(post.ytObj, post.ytInfo = m, isYtube); } else if(embedType > 2) { addThumb(post.ytObj, post.ytInfo = m, isYtube); } } else if(!link && $q('.de-video-link[href*="' + m[1] + '"]', post.msg)) { return; } if(loader && (dataObj = vData[m[1]])) { post.ytData.push(dataObj); } if(m[4] || m[3] || m[2]) { if(m[4] >= 60) { m[3] = (m[3] || 0) + Math.floor(m[4] / 60); m[4] %= 60; } if(m[3] >= 60) { m[2] = (m[2] || 0) + Math.floor(m[3] / 60); m[3] %= 60; } time = (m[2] ? m[2] + 'h' : '') + (m[3] ? m[3] + 'm' : '') + (m[4] ? m[4] + 's' : ''); } if(link) { link.href = link.href.replace(/^http:/, 'https:'); if(time) { link.setAttribute('de-time', time); } if(dataObj) { link.textContent = dataObj[0]; link.className = 'de-video-link de-ytube de-video-title'; link.setAttribute('de-author', dataObj[1]); link.title = Lng.author[lang] + dataObj[1] + ', ' + Lng.views[lang] + dataObj[2] + ', ' + Lng.published[lang] + dataObj[3]; } else { link.className = 'de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo'); } } else { src = isYtube ? 'https://www.youtube.com/watch?v=' + m[1] + (time ? '#t=' + time : '') : 'https://vimeo.com/' + m[1]; post.msg.insertAdjacentHTML('beforeend', '<p class="de-video-ext"><a class="de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo') + (dataObj ? ' de-video-title" title="' + Lng.author[lang] + dataObj[1] + ', ' + Lng.views[lang] + dataObj[2] + ', ' + Lng.published[lang] + dataObj[3] + '" de-author="' + dataObj[1] : '') + (time ? '" de-time="' + time : '') + '" href="' + src + '">' + (dataObj ? dataObj[0] : src) + '</a></p>'); link = post.msg.lastChild.firstChild; } if(!post.ytInfo || post.ytInfo === m) { post.ytLink = link; } link.ytInfo = m; if(loader && !dataObj) { post.ytLinksLoading++; loader.run([post, link, m[1]]); } } function getYtubeTitleLoader() { var queueEnd, queue = new $queue(4, function(qIdx, num, data) { if(num % 30 === 0) { queue.pause(); setTimeout(queue.continue.bind(queue), 3e3); } GM_xmlhttpRequest({ 'method': 'GET', 'url': 'https://gdata.youtube.com/feeds/api/videos/' + data[2] + '?alt=json&fields=title/text(),author/name,yt:statistics/@viewCount,published', 'onreadystatechange': function(idx, xhr) { if(xhr.readyState !== 4) { return; } var entry, title, author, views, publ, data, post = this[0], link = this[1]; try { if(xhr.status === 200) { entry = JSON.parse(xhr.responseText)['entry']; title = entry['title']['$t']; author = entry['author'][0]['name']['$t']; views = entry['yt$statistics']['viewCount']; publ = entry['published']['$t'].substr(0, 10); } } finally { if(title) { link.textContent = title; link.setAttribute('de-author', author); link.classList.add('de-video-title'); link.title = Lng.author[lang] + author + ', ' + Lng.views[lang] + views + ', ' + Lng.published[lang] + publ; vData[this[2]] = data = [title, author, views, publ]; post.ytData.push(data); post.ytLinksLoading--; if(post.ytHideFun !== null) { post.ytHideFun(data); } } setTimeout(queueEnd, 250, idx); } }.bind(data, qIdx) }); }, function() { sesStorage['de-ytube-data'] = JSON.stringify(vData); queue = queueEnd = null; }); queueEnd = queue.end.bind(queue); return queue; } function YouTubeSingleton() { if(instance) { return instance; } instance = this; embedType = Cfg['addYouTube']; if(embedType === 0) { this.parseLinks = emptyFn; this.updatePost = emptyFn; } loadTitles = Cfg['YTubeTitles']; if(loadTitles) { vData = JSON.parse(sesStorage['de-ytube-data'] || '{}'); } videoType = Cfg['YTubeType']; width = Cfg['YTubeWidth']; height = Cfg['YTubeHeigh']; isHD = Cfg['YTubeHD']; } YouTubeSingleton.prototype = { embedType: embedType, ytReg: /^https?:\/\/(?:www\.|m\.)?youtu(?:be\.com\/(?:watch\?.*?v=|v\/|embed\/)|\.be\/)([^&#?]+).*?(?:t(?:ime)?=(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?)?$/, vData: vData, addPlayer: addPlayer, addThumb: addThumb, parseLinks: function(post) { var i, len, els, el, src, m, embedTube = [], loader = loadTitles && getYtubeTitleLoader(); for(i = 0, els = $Q('embed, object, iframe', post ? post.el : dForm), len = els.length; i < len; ++i) { el = els[i]; src = el.src || el.data; if(m = src.match(this.ytReg)) { embedTube.push(post || aib.getPostEl(el).post, m, true); $del(el); } if(Cfg['addVimeo'] && (m = src.match(vimReg))) { embedTube.push(post || aib.getPostEl(el).post, m, false); $del(el); } } for(i = 0, els = $Q('a[href*="youtu"]', post ? post.el : dForm), len = els.length; i < len; ++i) { el = els[i]; if(m = el.href.match(this.ytReg)) { addLink(post || aib.getPostEl(el).post, m, loader, el, true); } } if(Cfg['addVimeo']) { for(i = 0, els = $Q('a[href*="vimeo.com"]', post ? post.el : dForm), len = els.length; i < len; ++i) { el = els[i]; if(m = el.href.match(vimReg)) { addLink(post || aib.getPostEl(el).post, m, null, el, false); } } } for(i = 0, len = embedTube.length; i < len; i += 3) { addLink(embedTube[i], embedTube[i + 1], loader, null, embedTube[i + 2]); } loader && loader.complete(); }, updatePost: function(post, oldLinks, newLinks, cloned) { var i, j, el, link, m, loader = !cloned && loadTitles && getYtubeTitleLoader(), len = newLinks.length; for(i = 0, j = 0; i < len; i++) { el = newLinks[i]; link = oldLinks[j]; if(link && link.classList.contains('de-current')) { post.ytLink = el; } if(cloned) { el.ytInfo = link.ytInfo; j++; } else if(m = el.href.match(this.ytReg)) { addLink(post, m, loader, el, true); j++; } } post.ytLink = post.ytLink || newLinks[0]; loader && loader.complete(); } }; return YouTubeSingleton; }; function embedMP3Links(post) { var el, link, src, i, els, len; if(!Cfg['addMP3']) { return; } for(i = 0, els = $Q('a[href*=".mp3"]', post ? post.el : dForm), len = els.length; i < len; ++i) { link = els[i]; if(link.target !== '_blank' && link.rel !== 'nofollow') { continue; } src = link.href; el = (post || aib.getPostEl(link).post).mp3Obj; if(nav.canPlayMP3) { if(!$q('audio[src="' + src + '"]', el)) { el.insertAdjacentHTML('beforeend', '<p><audio src="' + src + '" preload="none" controls></audio></p>'); link = el.lastChild.firstChild; link.addEventListener('play', updater.addPlayingTag, false); link.addEventListener('pause', updater.removePlayingTag, false); } } else if(!$q('object[FlashVars*="' + src + '"]', el)) { el.insertAdjacentHTML('beforeend', '<object data="http://junglebook2007.narod.ru/audio/player.swf" type="application/x-shockwave-flash" wmode="transparent" width="220" height="16" FlashVars="playerID=1&amp;bg=0x808080&amp;leftbg=0xB3B3B3&amp;lefticon=0x000000&amp;rightbg=0x808080&amp;rightbghover=0x999999&amp;rightcon=0x000000&amp;righticonhover=0xffffff&amp;text=0xffffff&amp;slider=0x222222&amp;track=0xf5f5dc&amp;border=0x666666&amp;loader=0x7fc7ff&amp;loop=yes&amp;autostart=no&amp;soundFile=' + src + '"><br>'); } } } //============================================================================================================ // AJAX //============================================================================================================ function ajaxLoad(url, loadForm, Fn, errFn) { return GM_xmlhttpRequest({ 'method': 'GET', 'url': nav.fixLink(url), 'onreadystatechange': function(xhr) { if(xhr.readyState !== 4) { return; } if(xhr.status !== 200) { if(errFn) { errFn(xhr.status, xhr.statusText, this); } } else if(Fn) { do { var el, text = xhr.responseText; if((aib.futa ? /<!--gz-->$/ : /<\/html?>[\s\n\r]*$/).test(text)) { el = $DOM(text); if(!loadForm || (el = $q(aib.qDForm, el))) { Fn(el, this); break; } } if(errFn) { errFn(0, Lng.errCorruptData[lang], this); } } while(false); } loadForm = Fn = errFn = null; } });; } function getJsonPosts(url, Fn) { GM_xmlhttpRequest({ 'method': 'GET', 'url': nav.fixLink(url), 'onreadystatechange': function(xhr) { if(xhr.readyState !== 4) { return; } if(xhr.status === 304) { closeAlert($id('de-alert-newposts')); } else { try { var json = JSON.parse(xhr.responseText); } catch(e) { Fn(1, e.toString(), null, this); } finally { if(json) { Fn(xhr.status, xhr.statusText, json, this); } Fn = null; } } } }); } function loadFavorThread() { var post, el = this.parentNode.parentNode, ifrm = $t('iframe', el), cont = $c('de-content', doc); if(ifrm) { $del(ifrm); cont.style.overflowY = 'auto'; return; } if((post = pByNum[el.getAttribute('de-num')]) && !post.hidden) { scrollTo(0, pageYOffset + post.el.getBoundingClientRect().top); return; } $del($id('de-iframe-fav')); $c('de-content', doc).style.overflowY = 'scroll'; el.insertAdjacentHTML('beforeend', '<iframe name="de-iframe-fav" id="de-iframe-fav" src="' + $t('a', el).href + '" scrolling="no" style="border: none; width: ' + (doc.documentElement.clientWidth - 55) + 'px; height: 1px;"><div id="de-fav-wait" ' + 'class="de-wait" style="font-size: 1.1em; text-align: center">' + Lng.loading[lang] + '</div>'); } function loadPages(count) { var fun, i = pageNum, len = Math.min(aib.lastPage + 1, i + count), pages = [], loaded = 1; count = len - i; function onLoadOrError(idx, eCodeOrForm, eMsgOrXhr, maybeXhr) { if(typeof eCodeOrForm === 'number') { pages[idx] = $add('<div><center style="font-size: 2em">' + getErrorMessage(eCodeOrForm, eMsgOrXhr) + '</center><hr></div>'); } else { pages[idx] = replacePost(eCodeOrForm); } if(loaded === count) { var el, df, j, parseThrs = Thread.parsed, threads = parseThrs ? [] : null; for(j in pages) { if(!pages.hasOwnProperty(j)) { continue; } if(j != pageNum) { dForm.insertAdjacentHTML('beforeend', '<center style="font-size: 2em">' + Lng.page[lang] + ' ' + j + '</center><hr>'); } df = pages[j]; if(parseThrs) { threads = parseThreadNodes(df, threads); } while(el = df.firstChild) { dForm.appendChild(el); } } if(!parseThrs) { threads = $Q(aib.qThread, dForm); } do { if(threads.length !== 0) { try { parseDelform(dForm, threads); } catch(e) { $alert(getPrettyErrorMessage(e), 'load-pages', true); break; } initDelformAjax(); addDelformStuff(false); readUserPosts(); readFavoritesPosts(); $each($Q('input[type="password"]', dForm), function(pEl) { pr.dpass = pEl; pEl.value = Cfg['passwValue']; }); if(keyNav) { keyNav.clear(pageNum + count - 1); } } closeAlert($id('de-alert-load-pages')); } while(false); dForm.style.display = ''; loaded = pages = count = null; } else { loaded++; } } $alert(Lng.loading[lang], 'load-pages', true); $each($Q('a[href^="blob:"]', dForm), function(a) { window.URL.revokeObjectURL(a.href); }); Pview.clearCache(); isExpImg = false; pByNum = Object.create(null); Thread.tNums = []; Post.hiddenNums = []; if(Attachment.viewer) { Attachment.viewer.close(null); Attachment.viewer = null; } dForm.style.display = 'none'; dForm.innerHTML = ''; if(pr.isQuick) { if(pr.file) { pr.delFilesUtils(); } pr.txta.value = ''; } while(i < len) { fun = onLoadOrError.bind(null, i); ajaxLoad(aib.getPageUrl(brd, i++), true, fun, fun); } } function infoLoadErrors(eCode, eMsg, newPosts) { if(eCode === 200 || eCode === 304) { closeAlert($id('de-alert-newposts')); } else if(eCode === 0) { $alert(eMsg || Lng.noConnect[lang], 'newposts', false); } else { $alert(Lng.thrNotFound[lang] + TNum + '): \n' + getErrorMessage(eCode, eMsg), 'newposts', false); if(newPosts !== -1) { doc.title = '{' + eCode + '} ' + doc.title; } } } //============================================================================================================ // SPELLS //============================================================================================================ function Spells(read) { if(read) { this._read(true); } else { this.disable(false); } } Spells.names = [ 'words', 'exp', 'exph', 'imgn', 'ihash', 'subj', 'name', 'trip', 'img', 'sage', 'op', 'tlen', 'all', 'video', 'wipe', 'num', 'vauthor' ]; Spells.needArg = [ /* words */ true, /* exp */ true, /* exph */ true, /* imgn */ true, /* ihash */ true, /* subj */ false, /* name */ true, /* trip */ false, /* img */ false, /* sage */ false, /* op */ false, /* tlen */ false, /* all */ false, /* video */ false, /* wipe */ false, /* num */ true, /* vauthor */ true ]; Spells.decompileSpell = function(type, neg, val, scope) { var temp, temp_, spell = (neg ? '!#' : '#') + Spells.names[type] + (scope ? '[' + scope[0] + (scope[1] ? ',' + (scope[1] === -1 ? '' : scope[1]) : '') + ']' : ''); if(!val) { return spell; } // #img if(type === 8) { return spell + '(' + (val[0] === 2 ? '>' : val[0] === 1 ? '<' : '=') + (val[1] ? val[1][0] + (val[1][1] === val[1][0] ? '' : '-' + val[1][1]) : '') + (val[2] ? '@' + val[2][0] + (val[2][0] === val[2][1] ? '' : '-' + val[2][1]) + 'x' + val[2][2] + (val[2][2] === val[2][3] ? '' : '-' + val[2][3]) : '') + ')'; } // #wipe else if(type === 14) { if(val === 0x3F) { return spell; } temp = []; (val & 1) && temp.push('samelines'); (val & 2) && temp.push('samewords'); (val & 4) && temp.push('longwords'); (val & 8) && temp.push('symbols'); (val & 16) && temp.push('capslock'); (val & 32) && temp.push('numbers'); (val & 64) && temp.push('whitespace'); return spell + '(' + temp.join(',') + ')'; } // #num, #tlen else if(type === 15 || type === 11) { if((temp = val[1].length - 1) !== -1) { for(temp_ = []; temp >= 0; temp--) { temp_.push(val[1][temp][0] + '-' + val[1][temp][1]); } temp_.reverse(); } spell += '('; if(val[0].length !== 0) { spell += val[0].join(',') + (temp_ ? ',' : ''); } if(temp_) { spell += temp_.join(','); } return spell + ')'; } // #words, #name, #trip, #vauthor else if(type === 0 || type === 6 || type === 7 || type === 16) { return spell + '(' + val.replace(/\)/g, '\\)') + ')'; } else { return spell + '(' + String(val) + ')'; } }; Spells.prototype = { _optimizeSpells: function(spells) { var i, j, len, flags, type, spell, scope, neg, parensSpells, lastSpell = -1, newSpells = []; for(i = 0, len = spells.length; i < len; ++i) { spell = spells[i]; flags = spell[0]; type = flags & 0xFF; neg = (flags & 0x100) !== 0; if(type === 0xFF) { parensSpells = this._optimizeSpells(spell[1]); if(parensSpells) { if(parensSpells.length !== 1) { newSpells.push([flags, parensSpells]); lastSpell++; continue; } else if((parensSpells[0][0] & 0xFF) !== 12) { newSpells.push([(parensSpells[0][0] | (flags & 0x200)) ^ (flags & 0x100), parensSpells[0][1]]); lastSpell++; continue; } flags = parensSpells[0][0]; neg = !(neg ^ ((flags & 0x100) !== 0)); } } else { scope = spell[2]; if(!scope || (scope[0] === brd && (scope[1] === -1 ? !TNum : (!scope[1] || scope[1] === TNum)))) { if(type === 12) { neg = !neg; } else { newSpells.push([flags, spell[1]]); lastSpell++; continue; } } } for(j = lastSpell; j >= 0 && (((newSpells[j][0] & 0x200) !== 0) ^ neg); --j) {} if(j !== lastSpell) { newSpells = newSpells.slice(0, j + 1); lastSpell = j; } if(neg && j !== -1) { newSpells[j][0] &= 0x1FF; } if(((flags & 0x200) !== 0) ^ neg) { break; } } return lastSpell === -1 ? neg ? [[12, '']] : null : newSpells; }, _initSpells: function(data) { if(data) { data.forEach(function initExps(item) { var val = item[1]; if(val) { switch(item[0] & 0xFF) { case 1: case 2: case 3: case 5: case 13: item[1] = toRegExp(val, true); break; case 0xFF: val.forEach(initExps); } } }); } return data; }, _decompileScope: function(scope, indent) { var spell, type, temp, str, dScope = [], hScope = false, i = 0, j = 0, len = scope.length; for(; i < len; i++, j++) { spell = scope[i]; type = spell[0] & 0xFF; if(type === 0xFF) { hScope = true; temp = this._decompileScope(spell[1], indent + ' '); if(temp[1]) { str = ((spell[0] & 0x100) ? '!(\n' : '(\n') + indent + ' ' + temp[0].join('\n' + indent + ' ') + '\n' + indent + ')'; if(j === 0) { dScope[0] = str; } else { dScope[--j] += ' ' + str; } } else { dScope[j] = ((spell[0] & 0x100) ? '!(' : '(') + temp[0].join(' ') + ')'; } } else { dScope[j] = Spells.decompileSpell(type, spell[0] & 0x100, spell[1], spell[2]); } if(i !== len - 1) { dScope[j] += (spell[0] & 0x200) ? ' &' : ' |'; } } return [dScope, dScope.length > 2 || hScope]; }, _decompileSpells: function() { var str, reps, oreps, data = this._data; if(!data) { this._read(false); if(!(data = this._data)) { return this._list = ''; } } str = data[1] ? this._decompileScope(data[1], '')[0].join('\n') : ''; reps = data[2]; oreps = data[3]; if(reps || oreps) { if(str) { str += '\n\n'; } reps && reps.forEach(function(rep) { str += this._decompileRep(rep, false) + '\n'; }.bind(this)); oreps && oreps.forEach(function(orep) { str += this._decompileRep(orep, true) + '\n'; }.bind(this)); str = str.substr(0, str.length - 1); } this._data = null; return this._list = str; }, _decompileRep: function(rep, isOrep) { return (isOrep ? '#outrep' : '#rep') + (rep[0] ? '[' + rep[0] + (rep[1] ? ',' + (rep[1] === -1 ? '' : rep[1]) : '') + ']' : '') + '(' + rep[2] + ',' + rep[3].replace(/\)/g, '\\)') + ')'; }, _optimizeReps: function(data) { if(data) { var nData = []; data.forEach(function(temp) { if(!temp[0] || (temp[0] === brd && (temp[1] === -1 ? !TNum : !temp[1] || temp[1] === TNum))) { nData.push([temp[2], temp[3]]); } }); return nData.length === 0 ? false : nData; } return false; }, _initReps: function(data) { if(data) { for(var i = data.length - 1; i >= 0; i--) { data[i][0] = toRegExp(data[i][0], false); } } return data; }, _init: function(spells, reps, outreps) { this._spells = this._initSpells(spells); this._sLength = spells && spells.length; this._reps = this._initReps(reps); this._outreps = this._initReps(outreps); this.enable = !!this._spells; this.haveReps = !!reps; this.haveOutreps = !!outreps; }, _read: function(init) { var spells, data; try { spells = JSON.parse(Cfg['spells']); data = JSON.parse(sesStorage['de-spells-' + brd + TNum]); } catch(e) {} if(data && spells && data[0] === spells[0]) { this._data = spells; if(init) { this.hash = data[0]; this._init(data[1], data[2], data[3]); } return; } if(!spells) { spells = this.parseText('#wipe(samelines,samewords,longwords,numbers,whitespace)'); } if(init) { this.update(spells, false, false); } else { this._data = spells; } }, _asyncSpellComplete: function(interp) { this.hasNumSpell |= interp.hasNumSpell; this._asyncJobs--; this.end(null); }, _asyncJobs: 0, _completeFns: [], _hasComplFns: false, _data: null, _list: '', hash: 0, hasNumSpell: false, enable: false, get list() { return this._list || this._decompileSpells(); }, addCompleteFunc: function(Fn) { this._completeFns.push(Fn); this._hasComplFns = true; }, parseText: function(str) { var codeGen, spells, reps = [], outreps = [], regexError = false, checkRegex = function(exp, reg) { if(!regexError) { try { toRegExp(reg, false); } catch(e) { var line = str.substr(0, str.indexOf(exp)).match(/\n/g).length + 1; $alert(Lng.error[lang] + ': ' + Lng.seErrRegex[lang].replace('%s', reg) + Lng.seRow[lang] + line + ')', 'help-err-spell', false); regexError = true; } } }; str = String(str).replace(/[\s\n]+$/, '').replace( /([^\\]\)|^)?[\n\s]*(#rep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g, function(exp, preOp, fullExp, b, nt, t, reg, txt) { checkRegex(fullExp, reg); reps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]); return preOp || ''; } ).replace( /([^\\]\)|^)?[\n\s]*(#outrep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g, function(exp, preOp, fullExp, b, nt, t, reg, txt) { checkRegex(fullExp, reg); outreps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]); return preOp || ''; } ); checkRegex = null; if(regexError) { return null; } if(reps.length === 0) { reps = false; } if(outreps.length === 0) { outreps = false; } codeGen = new SpellsCodegen(str); spells = codeGen.generate(); if(codeGen.hasError) { $alert(Lng.error[lang] + ': ' + codeGen.error, 'help-err-spell', false); } else if(spells || reps || outreps) { if(spells && Cfg['sortSpells']) { this.sort(spells); } return [Date.now(), spells, reps, outreps]; } return null; }, sort: function(sp) { // Wraps AND-spells with brackets for proper sorting for(var i = 0, len = sp.length-1; i < len; i++) { if(sp[i][0] > 0x200) { var temp = [0xFF, []]; do { temp[1].push(sp.splice(i, 1)[0]); len--; } while (sp[i][0] > 0x200); temp[1].push(sp.splice(i, 1)[0]); sp.splice(i, 0, temp); } } sp = sp.sort(); for(var i = 0, len = sp.length-1; i < len; i++) { // Removes duplicates and weaker spells if(sp[i][0] === sp[i+1][0] && sp[i][1] <= sp[i+1][1] && sp[i][1] >= sp[i+1][1] && (sp[i][2] === null || // Stronger spell with 3 parameters sp[i][2] === undefined || // Equal spells with 2 parameters (sp[i][2] <= sp[i+1][2] && sp[i][2] >= sp[i+1][2]))) { // Equal spells with 3 parameters sp.splice(i+1, 1); i--; len--; // Moves brackets to the end of the list } else if(sp[i][0] === 0xFF) { sp.push(sp.splice(i, 1)[0]); i--; len--; } } }, update: function(data, sync, isHide) { var spells = data[1] ? this._optimizeSpells(data[1]) : false, reps = this._optimizeReps(data[2]), outreps = this._optimizeReps(data[3]); saveCfg('spells', JSON.stringify(data)); sesStorage['de-spells-' + brd + TNum] = JSON.stringify([data[0], spells, reps, outreps]); this._data = data; this._list = ''; this.hash = data[0]; if(sync) { locStorage['__de-spells'] = JSON.stringify({ 'hide': (!!this.list && !!isHide), 'data': data }); locStorage.removeItem('__de-spells'); } this._init(spells, reps, outreps); }, setSpells: function(spells, sync) { this.update(spells, sync, Cfg['hideBySpell']); if(Cfg['hideBySpell']) { for(var post = firstThr.op; post; post = post.next) { this.check(post); } this.end(savePosts); } else { this.enable = false; } }, disable: function(sync) { this.enable = false; this._list = ''; this._data = null; this.haveReps = this.haveOutreps = false; saveCfg('hideBySpell', false); }, end: function(Fn) { if(this._asyncJobs === 0) { Fn && Fn(); if(this._hasComplFns) { for(var i = 0, len = this._completeFns.length; i < len; ++i) { this._completeFns[i](); } this._completeFns = []; this._hasComplFns = false; } } else if(Fn) { this.addCompleteFunc(Fn); } }, check: function(post) { if(!this.enable) { return 0; } var interp = new SpellsInterpreter(post, this._spells, this._sLength); if(interp.run()) { this.hasNumSpell |= interp.hasNumSpell; return interp.postHidden ? 1 : 0; } interp.setEndFn(this._asyncSpellComplete.bind(this)); this._asyncJobs++; return 0; }, replace: function(txt) { for(var i = 0, len = this._reps.length; i < len; i++) { txt = txt.replace(this._reps[i][0], this._reps[i][1]); } return txt; }, outReplace: function(txt) { for(var i = 0, len = this._outreps.length; i < len; i++) { txt = txt.replace(this._outreps[i][0], this._outreps[i][1]); } return txt; }, addSpell: function(type, arg, scope, isNeg, spells) { if(!spells) { if(!this._data) { this._read(false); } spells = this._data || [Date.now(), [], false, false]; } var idx, sScope = String(scope), sArg = String(arg); if(spells[1]) { spells[1].some(scope && isNeg ? function(spell, i) { var data; if(spell[0] === 0xFF && ((data = spell[1]) instanceof Array) && data.length === 2 && data[0][0] === 0x20C && data[1][0] === type && data[1][2] == null && String(data[1][1]) === sArg && String(data[0][2]) === sScope) { idx = i; return true; } return (spell[0] & 0x200) !== 0; } : function(spell, i) { if(spell[0] === type && String(spell[1]) === sArg && String(spell[2]) === sScope) { idx = i; return true; } return (spell[0] & 0x200) !== 0; }); } else { spells[1] = []; } if(typeof idx !== 'undefined') { spells[1].splice(idx, 1); } else if(scope && isNeg) { spells[1].splice(0, 0, [0xFF, [[0x20C, '', scope], [type, arg, void 0]], void 0]); } else { spells[1].splice(0, 0, [type, arg, scope]); } this.update(spells, true, true); idx = null; } }; function SpellsCodegen(sList) { this._line = 1; this._col = 1; this._sList = sList; this.hasError = false; } SpellsCodegen.prototype = { TYPE_UNKNOWN: 0, TYPE_ANDOR: 1, TYPE_NOT: 2, TYPE_SPELL: 3, TYPE_PARENTHESES: 4, generate: function() { return this._sList ? this._generate(this._sList, false) : null; }, get error() { if(!this.hasError) { return ''; } return (this._errMsgArg ? this._errMsg.replace('%s', this._errMsgArg) : this._errMsg) + Lng.seRow[lang] + this._line + Lng.seCol[lang] + this._col + ')'; }, _errMsg: '', _errMsgArg: null, _generate: function(sList, inParens) { var res, name, i = 0, len = sList.length, data = [], lastType = this.TYPE_UNKNOWN; for(; i < len; i++, this._col++) { switch(sList[i]) { case '\n': this._line++; this._col = 0; case '\r': case ' ': continue; case '#': if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) { this._setError(Lng.seMissOp[lang], null); return null; } name = ''; i++; this._col++; while((sList[i] >= 'a' && sList[i] <= 'z') || (sList[i] >= 'A' && sList[i] <= 'Z')) { name += sList[i].toLowerCase(); i++; this._col++; } res = this._doSpell(name, sList.substr(i), lastType === this.TYPE_NOT) if(!res) { return null; } i += res[0] - 1; this._col += res[0] - 1; data.push(res[1]); lastType = this.TYPE_SPELL; break; case '(': if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) { this._setError(Lng.seMissOp[lang], null); return null; } res = this._generate(sList.substr(i + 1), true); if(!res) { return null; } i += res[0] + 1; data.push([lastType === this.TYPE_NOT ? 0x1FF : 0xFF, res[1]]); lastType = this.TYPE_PARENTHESES; break; case '|': case '&': if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) { this._setError(Lng.seMissSpell[lang], null); return null; } if(sList[i] === '&') { data[data.length - 1][0] |= 0x200; } lastType = this.TYPE_ANDOR; break; case '!': if(lastType !== this.TYPE_ANDOR && lastType !== this.TYPE_UNKNOWN) { this._setError(Lng.seMissOp[lang], null); return null; } lastType = this.TYPE_NOT; break; case ')': if(lastType === this.TYPE_ANDOR || lastType === this.TYPE_NOT) { this._setError(Lng.seMissSpell[lang], null); return null; } if(inParens) { return [i, data]; } default: this._setError(Lng.seUnexpChar[lang], sList[i]); return null; } } if(inParens) { this._setError(Lng.seMissClBkt[lang], null); return null; } if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) { this._setError(Lng.seMissSpell[lang], null); return null; } return data; }, _doSpell: function(name, str, isNeg) { var scope, m, spellType, val, i = 0, spellIdx = Spells.names.indexOf(name); if(spellIdx === -1) { this._setError(Lng.seUnknown[lang], name); return null; } spellType = isNeg ? spellIdx | 0x100 : spellIdx; m = str.match(/^\[([a-z0-9\/]+)(?:(,)|,(\s*[0-9]+))?\]/); if(m) { i = m[0].length; str = str.substring(i); scope = [m[1], m[3] ? m[3] : m[2] ? -1 : false]; } else { scope = null; } if(str[0] !== '(' || str[1] === ')') { if(Spells.needArg[spellIdx]) { this._setError(Lng.seMissArg[lang], name); return null; } return [str[0] === '(' ? i + 2 : i, [spellType, spellIdx === 14 ? 0x3F : '', scope]]; } switch(spellIdx) { // #ihash case 4: m = str.match(/^\((\d+)\)/); if(+m[1] === +m[1]) { return [i + m[0].length, [spellType, +m[1], scope]]; } break; // #img case 8: m = str.match(/^\(([><=])(?:(\d+(?:\.\d+)?)(?:-(\d+(?:\.\d+)?))?)?(?:@(\d+)(?:-(\d+))?x(\d+)(?:-(\d+))?)?\)/); if(m && (m[2] || m[4])) { return [i + m[0].length, [spellType, [ m[1] === '=' ? 0 : m[1] === '<' ? 1 : 2, m[2] && [+m[2], m[3] ? +m[3] : +m[2]], m[4] && [+m[4], m[5] ? +m[5] : +m[4], +m[6], m[7] ? +m[7] : +m[6]] ], scope]]; } break; // #wipe case 14: m = str.match(/^\(([a-z, ]+)\)/); if(m) { val = m[1].split(/, */).reduce(function(val, str) { switch(str) { case 'samelines': return val |= 1; case 'samewords': return val |= 2; case 'longwords': return val |= 4; case 'symbols': return val |= 8; case 'capslock': return val |= 16; case 'numbers': return val |= 32; case 'whitespace': return val |= 64; default: return -1; } }, 0); if(val !== -1) { return [i + m[0].length, [spellType, val, scope]]; } } break; // #tlen, #num case 11: case 15: m = str.match(/^\(([\d-, ]+)\)/); if(m) { m[1].split(/, */).forEach(function(v) { if(v.contains('-')) { var nums = v.split('-'); nums[0] = +nums[0]; nums[1] = +nums[1]; this[1].push(nums); } else { this[0].push(+v); } }, val = [[], []]); return [i + m[0].length, [spellType, val, scope]]; } break; // #exp, #exph, #imgn, #subj, #video case 1: case 2: case 3: case 5: case 13: m = str.match(/^\((\/.*?[^\\]\/[igm]*)\)/); if(m) { val = m[1]; try { toRegExp(val, true); } catch(e) { this._setError(Lng.seErrRegex[lang], val); return null; } return [i + m[0].length, [spellType, val, scope]]; } break; // #sage, #op, #all, #trip, #name, #words, #vauthor default: m = str.match(/^\((.*?[^\\])\)/); if(m) { val = m[1].replace(/\\\)/g, ')'); return [i + m[0].length, [spellType, spellIdx === 0 ? val.toLowerCase() : val, scope]]; } } this._setError(Lng.seSyntaxErr[lang], name); return null; }, _setError: function(msg, arg) { this.hasError = true; this._errMsg = msg; this._errMsgArg = arg; } }; function SpellsInterpreter(post, spells, length) { this._post = post; this._ctx = [length, spells, 0]; this._deep = 0; } SpellsInterpreter.prototype = { hasNumSpell: false, postHidden: false, run: function() { var rv, type, val, i = this._ctx.pop(), scope = this._ctx.pop(), len = this._ctx.pop(); while(true) { if(i < len) { type = scope[i][0] & 0xFF; if(type === 0xFF) { this._deep++; this._ctx.push(len, scope, i); scope = scope[i][1]; len = scope.length; i = 0; continue; } val = this._runSpell(type, scope[i][1]); if(this._asyncWait) { this._ctx.push(len, scope, i, scope[i][0]); return false; } rv = this._checkRes(scope[i][0], val); if(rv === null) { i++; continue; } this._lastSpellIdx = i; } else { this._lastSpellIdx = i -= 1; rv = false; } if(this._deep !== 0) { this._deep--; i = this._ctx.pop(); scope = this._ctx.pop(); len = this._ctx.pop(); rv = this._checkRes(scope[i][0], rv); if(rv === null) { i++; continue; } } if(rv) { this._post.spellHide(this._getMsg(scope[i])); this.postHidden = true; } else if(!this._post.deleted) { sVis[this._post.count] = 1; } return true; } }, setEndFn: function(Fn) { this._endFn = Fn; }, _asyncWait: false, _endFn: null, _lastSpellIdx: 0, _wipeMsg: '', _asyncContinue: function(val) { this._asyncWait = false; var temp, rv = this._checkRes(this._ctx.pop(), val); if(rv === null) { if(!this.run()) { return; } } else if(rv) { temp = this._ctx.pop(); this._post.spellHide(this._getMsg(this._ctx.pop()[temp - 1])); this.postHidden = true; } else if(!this._post.deleted) { sVis[this._post.count] = 1; } if(this._endFn) { this._endFn(this); } }, _checkRes: function(flags, val) { if((flags & 0x100) !== 0) { val = !val; } if((flags & 0x200) !== 0) { if(!val) { return false; } } else if(val) { return true; } return null; }, _getMsg: function(spell) { var neg = spell[0] & 0x100, type = spell[0] & 0xFF, val = spell[1]; if(type === 0xFF) { return this._getMsg(val[this._lastSpellIdx]); } if(type === 14) { return (neg ? '!#wipe' : '#wipe') + (Spells._lastWipeMsg ? ': ' + Spells._lastWipeMsg : ''); } else { return Spells.decompileSpell(type, neg, val, spell[2]); } }, _runSpell: function(spellId, val) { switch(spellId) { case 0: return this._words(val); case 1: return this._exp(val); case 2: return this._exph(val); case 3: return this._imgn(val); case 4: return this._ihash(val); case 5: return this._subj(val); case 6: return this._name(val); case 7: return this._trip(val); case 8: return this._img(val); case 9: return this._sage(val); case 10: return this._op(val); case 11: return this._tlen(val); case 12: return this._all(val); case 13: return this._video(val); case 14: return this._wipe(val); case 15: this.hasNumSpell = true; return this._num(val); case 16: return this._vauthor(val); } }, _words: function(val) { return this._post.text.toLowerCase().contains(val) || this._post.subj.toLowerCase().contains(val); }, _exp: function(val) { return val.test(this._post.text); }, _exph: function(val) { return val.test(this._post.html); }, _imgn: function(val) { for(var i = 0, imgs = this._post.images, len = imgs.length; i < len; ++i) { if(val.test(imgs[i].info)) { return true; } } return false; }, _ihash: function(val) { for(var i = 0, imgs = this._post.images, len = imgs.length; i < len; ++i) { if(imgs[i].hash === val) { return true; } } if(this._post.hashImgsBusy === 0) { return false; } this._post.hashHideFun = this._ihash_helper.bind(this, val); this._asyncWait = true; return false; }, _ihash_helper: function(val, hash) { if(val === hash) { this._post.hashHideFun = null; this._asyncContinue(true); } else if(this._post.hashImgsBusy === 0) { this.hashHideFun = null; this._asyncContinue(false); } }, _subj: function(val) { var pSubj = this._post.subj; return pSubj ? !val || val.test(pSubj) : false; }, _name: function(val) { var pName = this._post.posterName; return pName ? !val || pName.contains(val) : false; }, _trip: function(val) { var pTrip = this._post.posterTrip; return pTrip ? !val || pTrip.contains(val) : false; }, _img: function(val) { var temp, w, h, hide, img, i, imgs = this._post.images, len = imgs.length; if(!val) { return len !== 0; } for(i = 0; i < len; ++i) { img = imgs[i]; if(temp = val[1]) { w = img.weight; switch(val[0]) { case 0: hide = w >= temp[0] && w <= temp[1]; break; case 1: hide = w < temp[0]; break; case 2: hide = w > temp[0]; } if(!hide) { continue; } else if(!val[2]) { return true; } } if(temp = val[2]) { w = img.width; h = img.height; switch(val[0]) { case 0: if(w >= temp[0] && w <= temp[1] && h >= temp[2] && h <= temp[3]) { return true } break; case 1: if(w < temp[0] && h < temp[3]) { return true } break; case 2: if(w > temp[0] && h > temp[3]) { return true } } } } return false; }, _sage: function(val) { return this._post.sage; }, _op: function(val) { return this._post.isOp; }, _tlen: function(val) { var text = this._post.text; return !val ? !!text : this._tlenNum_helper(val, text.replace(/\n/g, '').length); }, _all: function(val) { return true; }, _video: function(val) { return this._videoVauthor(val, false); }, _wipe: function(val) { var arr, len, i, j, n, x, keys, pop, capsw, casew, _txt, txt = this._post.text; // (1 << 0): samelines if(val & 1) { arr = txt.replace(/>/g, '').split(/\s*\n\s*/); if((len = arr.length) > 5) { arr.sort(); for(i = 0, n = len / 4; i < len;) { x = arr[i]; j = 0; while(arr[i++] === x) { j++; } if(j > 4 && j > n && x) { this._wipeMsg = 'same lines: "' + x.substr(0, 20) + '" x' + (j + 1); return true; } } } } // (1 << 1): samewords if(val & 2) { arr = txt.replace(/[\s\.\?\!,>]+/g, ' ').toUpperCase().split(' '); if((len = arr.length) > 3) { arr.sort(); for(i = 0, n = len / 4, keys = 0, pop = 0; i < len; keys++) { x = arr[i]; j = 0; while(arr[i++] === x) { j++; } if(len > 25) { if(j > pop && x.length > 2) { pop = j; } if(pop >= n) { this._wipeMsg = 'same words: "' + x.substr(0, 20) + '" x' + (pop + 1); return true; } } } x = keys / len; if(x < 0.25) { this._wipeMsg = 'uniq words: ' + (x * 100).toFixed(0) + '%'; return true; } } } // (1 << 2): longwords if(val & 4) { arr = txt.replace(/https*:\/\/.*?(\s|$)/g, '').replace(/[\s\.\?!,>:;-]+/g, ' ').split(' '); if(arr[0].length > 50 || ((len = arr.length) > 1 && arr.join('').length / len > 10)) { this._wipeMsg = 'long words'; return true; } } // (1 << 3): symbols if(val & 8) { _txt = txt.replace(/\s+/g, ''); if((len = _txt.length) > 30 && (x = _txt.replace(/[0-9a-zа-я\.\?!,]/ig, '').length / len) > 0.4) { this._wipeMsg = 'specsymbols: ' + (x * 100).toFixed(0) + '%'; return true; } } // (1 << 4): capslock if(val & 16) { arr = txt.replace(/[\s\.\?!;,-]+/g, ' ').trim().split(' '); if((len = arr.length) > 4) { for(i = 0, n = 0, capsw = 0, casew = 0; i < len; i++) { x = arr[i]; if((x.match(/[a-zа-я]/ig) || []).length < 5) { continue; } if((x.match(/[A-ZА-Я]/g) || []).length > 2) { casew++; } if(x === x.toUpperCase()) { capsw++; } n++; } if(capsw / n >= 0.3 && n > 4) { this._wipeMsg = 'CAPSLOCK: ' + capsw / arr.length * 100 + '%'; return true; } else if(casew / n >= 0.3 && n > 8) { this._wipeMsg = 'cAsE words: ' + casew / arr.length * 100 + '%'; return true; } } } // (1 << 5): numbers if(val & 32) { _txt = txt.replace(/\s+/g, ' ').replace(/>>\d+|https*:\/\/.*?(?: |$)/g, ''); if((len = _txt.length) > 30 && (x = (len - _txt.replace(/\d/g, '').length) / len) > 0.4) { this._wipeMsg = 'numbers: ' + Math.round(x * 100) + '%'; return true; } } // (1 << 5): whitespace if(val & 64) { if(/(?:\n\s*){5}/i.test(txt)) { this._wipeMsg = 'whitespace'; return true; } } return false; }, _num: function(val) { return this._tlenNum_helper(val, this._post.count + 1); }, _tlenNum_helper: function(val, num) { var i, arr; for(arr = val[0], i = arr.length - 1; i >= 0; --i) { if(arr[i] === num) { return true; } } for(arr = val[1], i = arr.length - 1; i >= 0; --i) { if(num >= arr[i][0] && num <= arr[i][1]) { return true; } } return false; }, _vauthor: function(val) { return this._videoVauthor(val, true); }, _videoVauthor: function(val, isAuthorSpell) { if(!val) { return !!this._post.hasYTube; } if(!this._post.hasYTube || !Cfg['YTubeTitles']) { return false; } var i, data, len; for(i = 0, data = this._post.ytData, len = data.length; i < len; ++i) { if(isAuthorSpell ? val === data[i][1] : val.test(data[i][0])) { return true; } } if(this._post.ytLinksLoading === 0) { return false; } this._post.ytHideFun = this._videoVauthor_helper.bind(this, isAuthorSpell, val); this._asyncWait = true; return false; }, _videoVauthor_helper: function(isAuthorSpell, val, data) { if(isAuthorSpell ? val === data[1] : val.test(data[0])) { this._post.ytHideFun = null; this._asyncContinue(true); } else if(this._post.ytLinksLoading === 0) { this._post.ytHideFun = null; this._asyncContinue(false); } } } function disableSpells() { closeAlert($id('de-alert-help-err-spell')); if(spells.enable) { sVis = TNum ? '1'.repeat(firstThr.pcount).split('') : []; for(var post = firstThr.op; post; post = post.next) { if(post.spellHidden && !post.userToggled) { post.spellUnhide(); } } } } function toggleSpells() { var temp, fld = $id('de-spell-edit'), val = fld.value; if(val && (temp = spells.parseText(val))) { disableSpells(); spells.setSpells(temp, true); fld.value = spells.list; } else { if(val) { locStorage['__de-spells'] = '{"hide": false, "data": null}'; } else { disableSpells(); spells.disable(); saveCfg('spells', ''); locStorage['__de-spells'] = '{"hide": false, "data": ""}'; } locStorage.removeItem('__de-spells'); $q('input[info="hideBySpell"]', doc).checked = spells.enable = false; } } function addSpell(type, arg, isNeg) { var temp, fld = $id('de-spell-edit'), val = fld && fld.value, chk = $q('input[info="hideBySpell"]', doc); if(!val || (temp = spells.parseText(val))) { disableSpells(); spells.addSpell(type, arg, TNum ? [brd, TNum] : null, isNeg, temp); val = spells.list; saveCfg('hideBySpell', !!val); if(val) { for(var post = firstThr.op; post; post = post.next) { spells.check(post); } spells.end(savePosts); } else { saveCfg('spells', ''); spells.enable = false; } if(fld) { chk.checked = !!(fld.value = val); } return; } spells.enable = false; if(chk) { chk.checked = false; } } //============================================================================================================ // STYLES //============================================================================================================ function getThemeLang() { return !Cfg['scriptStyle'] ? 'fr' : Cfg['scriptStyle'] === 1 ? 'en' : 'de'; } function scriptCSS() { var p, x = ''; function cont(id, src) { return id + ':before { content: ""; padding: 0 16px 0 0; margin: 0 4px; background: url(' + src + ') no-repeat center; }'; } function gif(id, src) { return id + ' { background: url(data:image/gif;base64,' + src + ') no-repeat center !important; }'; } // Settings window x += '.de-block { display: block; }\ #de-content-cfg > div { border-radius: 10px 10px 0 0; width: auto; min-width: 0; padding: 0; margin: 5px 20px; overflow: hidden; }\ #de-cfg-head { padding: 4px; border-radius: 10px 10px 0 0; color: #fff; text-align: center; font: bold 14px arial; cursor: default; }\ #de-cfg-head:lang(en), #de-panel:lang(en) { background: linear-gradient(to bottom, #4b90df, #3d77be 5px, #376cb0 7px, #295591 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #183d77 13px, #1f4485 18px, #264c90 20px, #325f9e 25px); }\ #de-cfg-head:lang(fr), #de-panel:lang(fr) { background: linear-gradient(to bottom, #7b849b, #616b86 2px, #3a414f 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #121212 13px, #1f2740 25px); }\ #de-cfg-head:lang(de), #de-panel:lang(de) { background: #777; }\ .de-cfg-body { min-height: 289px; min-width: 371px; padding: 11px 7px 7px; margin-top: -1px; font: 13px sans-serif; }\ .de-cfg-body input[type="text"], .de-cfg-body select { width: auto; padding: 0 !important; margin: 0 !important; }\ .de-cfg-body, #de-cfg-btns { border: 1px solid #183d77; border-top: none; }\ .de-cfg-body:lang(de), #de-cfg-btns:lang(de) { border-color: #444; }\ #de-cfg-btns { padding: 7px 2px 2px; }\ #de-cfg-bar { width: 100%; display: table; background-color: #1f2740; margin: 0; padding: 0; }\ #de-cfg-bar:lang(en) { background-color: #325f9e; }\ #de-cfg-bar:lang(de) { background-color: #777; }\ .de-cfg-depend { padding-left: 25px; }\ .de-cfg-tab { padding: 4px 5px; border-radius: 4px 4px 0 0; font: bold 12px arial; text-align: center; cursor: default; }\ .de-cfg-tab-back { display: table-cell !important; float: none !important; width:auto; min-width: 0 !important; padding: 0 !important; box-shadow: none !important; border: 1px solid #183d77 !important; border-radius: 4px 4px 0 0; opacity: 1; }\ .de-cfg-tab-back:lang(de) { border-color: #444 !important; }\ .de-cfg-tab-back:lang(fr) { border-color: #121421 !important; }\ .de-cfg-tab-back[selected="true"] { border-bottom: none !important; }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab { background-color: rgba(0,0,0,.2); }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(fr) { background: linear-gradient(to bottom, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover { background-color: rgba(99,99,99,.2); }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(fr) { background: linear-gradient(to top, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\ .de-cfg-tab::' + (nav.Firefox ? '-moz-' : '') + 'selection { background: transparent; }\ .de-cfg-unvis { display: none; }\ #de-spell-panel { float: right; }\ #de-spell-panel > a { padding: 0 4px; }\ #de-spell-div { display: table; }\ #de-spell-div > div { display: table-cell; vertical-align: top; }\ #de-spell-edit { padding: 2px !important; width: 340px; height: 180px; border: none !important; outline: none !important; }\ #de-spell-rowmeter { padding: 2px 3px 0 0; margin: 2px 0; overflow: hidden; width: 2em; height: 182px; text-align: right; color: #fff; font: 12px courier new; }\ #de-spell-rowmeter:lang(en), #de-spell-rowmeter:lang(fr) { background-color: #616b86; }\ #de-spell-rowmeter:lang(de) { background-color: #777; }'; // Main panel x += '#de-btn-logo { margin-right: 3px; cursor: pointer; }\ #de-panel { height: 25px; z-index: 9999; border-radius: 15px 0 0 0; cursor: default;}\ #de-panel-btns { display: inline-block; padding: 0 0 0 2px; margin: 0; height: 25px; border-left: 1px solid #8fbbed; }\ #de-panel-btns:lang(de), #de-panel-info:lang(de) { border-color: #ccc; }\ #de-panel-btns:lang(fr), #de-panel-info:lang(fr) { border-color: #616b86; }\ #de-panel-btns > li { margin: 0 1px; padding: 0; }\ #de-panel-btns > li, #de-panel-btns > li > a, #de-btn-logo { display: inline-block; width: 25px; height: 25px; }\ #de-panel-btns:lang(en) > li, #de-panel-btns:lang(fr) > li { transition: all 0.3s ease; }\ #de-panel-btns:lang(en) > li:hover, #de-panel-btns:lang(fr) > li:hover { background-color: rgba(255,255,255,.15); box-shadow: 0 0 3px rgba(143,187,237,.5); }\ #de-panel-btns:lang(de) > li > a { border-radius: 5px; }\ #de-panel-btns:lang(de) > li > a:hover { width: 21px; height: 21px; border: 2px solid #444; }\ #de-panel-info { display: inline-block; vertical-align: 6px; padding: 0 6px; margin: 0 0 0 2px; height: 25px; border-left: 1px solid #8fbbed; color: #fff; font: 18px serif; }'; p = 'R0lGODlhGQAZAIAAAPDw8P///yH5BAEAAAEALAAAAAAZABkA'; x += gif('#de-btn-logo', p + 'QAI5jI+pywEPWoIIRomz3tN6K30ixZXM+HCgtjpk1rbmTNc0erHvLOt4vvj1KqnD8FQ0HIPCpbIJtB0KADs='); x += gif('#de-btn-settings', p + 'QAJAjI+pa+API0Mv1Ymz3hYuiQHHFYjcOZmlM3Jkw4aeAn7R/aL6zuu5VpH8aMJaKtZR2ZBEZnMJLM5kIqnP2csUAAA7'); x += gif('#de-btn-hidden', p + 'QAI5jI+pa+CeHmRHgmCp3rxvO3WhMnomUqIXl2UmuLJSNJ/2jed4Tad96JLBbsEXLPbhFRc8lU8HTRQAADs='); x += gif('#de-btn-favor', p + 'QAIzjI+py+AMjZs02ovzobzb1wDaeIkkwp3dpLEoeMbynJmzG6fYysNh3+IFWbqPb3OkKRUFADs='); x += gif('#de-btn-refresh', p + 'QAJAjI+pe+AfHmRGLkuz3rzN+1HS2JWbhWlpVIXJ+roxSpr2jedOBIu0rKjxhEFgawcCqJBFZlPJIA6d0ZH01MtRCgA7'); x += gif('#de-btn-goback', p + 'QAIrjI+pmwAMm4u02gud3lzjD4biJgbd6VVPybbua61lGqIoY98ZPcvwD4QUAAA7'); x += gif('#de-btn-gonext', p + 'QAIrjI+pywjQonuy2iuf3lzjD4Zis0Xd6YnQyLbua61tSqJnbXcqHVLwD0QUAAA7'); x += gif('#de-btn-goup', p + 'QAIsjI+pm+DvmDRw2ouzrbq9DmKcBpVfN4ZpyLYuCbgmaK7iydpw1OqZf+O9LgUAOw=='); x += gif('#de-btn-godown', p + 'QAItjI+pu+DA4ps02osznrq9DnZceIxkYILUd7bue6WhrLInLdokHq96tnI5YJoCADs='); x += gif('#de-btn-expimg', p + 'QAI9jI+pGwDn4GPL2Wep3rxXFEFel42mBE6kcYXqFqYnVc72jTPtS/KNr5OJOJMdq4diAXWvS065NNVwseehAAA7'); x += gif('#de-btn-preimg', p + 'QAJFjI+pGwCcHJPGWdoe3Lz7qh1WFJLXiX4qgrbXVEIYadLLnMX4yve+7ErBYorRjXiEeXagGguZAbWaSdHLOow4j8Hrj1EAADs='); x += gif('#de-btn-maskimg', p + 'QAJQjI+pGwD3TGxtJgezrKz7DzLYRlKj4qTqmoYuysbtgk02ZCG1Rkk53gvafq+i8QiSxTozIY7IcZJOl9PNBx1de1Sdldeslq7dJ9gsUq6QnwIAOw=='); x += gif('#de-btn-imgload', p + 'QAJFjI+pG+CQnHlwSYYu3rz7RoVipWib+aVUVD3YysAledKZHePpzvecPGnpDkBQEEV03Y7DkRMZ9ECNnemUlZMOQc+iT1EAADs=') x += gif('#de-btn-catalog', p + 'QAI2jI+pa+DhAHyRNYpltbz7j1Rixo0aCaaJOZ2SxbIwKTMxqub6zuu32wP9WsHPcFMs0XDJ5qEAADs='); x += gif('#de-btn-audio-off', p + 'QAI7jI+pq+DO1psvQHOj3rxTik1dCIzmSZqfmGXIWlkiB6L2jedhPqOfCitVYolgKcUwyoQuSe3WwzV1kQIAOw=='); x += gif('#de-btn-audio-on', p + 'QAJHjI+pq+AewJHs2WdoZLz7X11WRkEgNoHqimadOG7uAqOm+Y6atvb+D0TgfjHS6RIp8YQ1pbHRfA4n0eSTI7JqP8Wtahr0FAAAOw=='); x += gif('#de-btn-enable', p + 'AAJAjI+py+0Po5wUWKoswOF27z2aMX6bo51lioal2bzwISPyHSZ1lts9fwKKfjQiyXgkslq95TAFnUCdUirnis0eCgA7'); p = 'Dw8P///wAAACH5BAEAAAIALAAAAAAZABkAQAJElI+pe2EBoxOTNYmr3bz7OwHiCDzQh6bq06QSCUhcZMCmNrfrzvf+XsF1MpjhCSainBg0AbKkFCJko6g0MSGyftwuowAAOw=='; x += gif('#de-btn-upd-on', 'R0lGODlhGQAZAJEAADL/Mv' + p); x += gif('#de-btn-upd-off', 'R0lGODlhGQAZAJEAAP8yMv' + p); x += gif('#de-btn-upd-warn', 'R0lGODlhGQAZAJEAAP/0Qf' + p); if(Cfg['disabled']) { applyCSS(x); return; } // Post panel x += '.de-ppanel { margin-left: 4px; }\ .de-post-note { color: inherit; margin: 0 4px; vertical-align: 1px; font: italic bold 12px serif; }\ .de-thread-note { font-style: italic; }\ .de-btn-expthr, .de-btn-fav, .de-btn-fav-sel, .de-btn-hide, .de-btn-hide-user, .de-btn-rep, .de-btn-sage, .de-btn-src, .de-btn-stick, .de-btn-stick-on { display: inline-block; margin: 0 4px -2px 0 !important; cursor: pointer; '; if(Cfg['postBtnsCSS'] === 0) { x += 'color: #4F7942; font-size: 14px; }\ .de-post-hide .de-btn-hide:after { content: "\u271A"; }\ .de-post-hide .de-btn-hide-user:after { content: "\u271A"; }\ .de-btn-expthr:after { content: "\u21D5"; }\ .de-btn-fav:after { content: "\u2605"; }\ .de-btn-fav-sel:after { content: "[\u2605]"; }\ .de-btn-hide:after { content: "\u2716"; }\ .de-btn-hide-user:after { content: "\u2716"; color: red !important; }\ .de-btn-rep:after { content: "\u25B6"; }\ .de-btn-sage:after { content: "\u274E"; }\ .de-btn-src:after { content: "[S]"; }\ .de-btn-stick:after { content: "\u25FB"; }\ .de-btn-stick-on:after { content: "\u25FC"; }'; } else if(Cfg['postBtnsCSS'] === 1) { p = 'R0lGODlhDgAOAKIAAPDw8KCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM'; x += 'padding: 0 14px 14px 0; }'; x += gif('.de-post-hide .de-btn-hide', p + '4SLLcqyHKGRe1E1cARPaSwIGVI3bOIAxc26oD7LqwusZcbMcNC9gLHsMHvFFixwFlGRgQdNAoIQEAOw=='); x += gif('.de-post-hide .de-btn-hide-user', 'R0lGODlhDgAOAKIAAP+/v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM4SLLcqyHKGRe1E1cARPaSwIGVI3bOIAxc26oD7LqwusZcbMcNC9gLHsMHvFFixwFlGRgQdNAoIQEAOw=='); x += gif('.de-btn-expthr', p + '5SLLcqyHGJaeoAoAr6dQaF3gZGFpO6AzNoLHMAC8uMAty+7ZwbfYzny02qNSKElkloDQSZNAolJAAADs='); x += gif('.de-btn-fav', p + '4SLLcqyHGJaeoAoAradec1Wigk5FoOQhDSq7DyrpyvLRpDb84AO++m+YXiVWMAWRlmSTEntAnIQEAOw=='); x += gif('.de-btn-fav-sel', 'R0lGODlhDgAOAKIAAP/hAKCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM4SLLcqyHGJaeoAoAradec1Wigk5FoOQhDSq7DyrpyvLRpDb84AO++m+YXiVWMAWRlmSTEntAnIQEAOw=='); x += gif('.de-btn-hide', p + '7SLLcqyHKGZcUE1ctAPdb0AHeCDpkWi4DM6gtGwtvOg9xDcu0rbc4FiA3lEkGE2QER2kGBgScdColJAAAOw=='); x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAKIAAL//v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM7SLLcqyHKGZcUE1ctAPdb0AHeCDpkWi4DM6gtGwtvOg9xDcu0rbc4FiA3lEkGE2QER2kGBgScdColJAAAOw=='); x += gif('.de-btn-rep', p + '2SLLcqyHKGZe0NGABAL5C1XWfM47NsAznqA6qwLbAG8/nfeexvNe91UACywSKxsmAAGs6m4QEADs='); x += gif('.de-btn-sage', 'R0lGODlhDgAOAJEAAPDw8EtLS////wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu0AgZs0SoqTzdnu5l1P1ImcwmBCAQA7'); x += gif('.de-btn-src', p + '/SLLcqyEuKWKYF4Cl6/VCF26UJHaUIzaDMGjA8Gqt7MJ47Naw3O832kxnay1sx11g6KMtBxEZ9DkdEKTYLCEBADs='); x += gif('.de-btn-stick', p + 'xSLLcqyHKGRe9wVYntQBgKGxMKDJDaQJouqzsMrgDTNO27Apzv88YCjAoGRB8yB4hAQA7'); x += gif('.de-btn-stick-on', 'R0lGODlhDgAOAKIAAL//v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAMxSLLcqyHKGRe9wVYntQBgKGxMKDJDaQJouqzsMrgDTNO27Apzv88YCjAoGRB8yB4hAQA7'); } else { p = 'R0lGODlhDgAOAJEAAPDw8IyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAI'; x += 'padding: 0 14px 14px 0; }'; x += gif('.de-post-hide .de-btn-hide', p + 'ZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7'); x += gif('.de-post-hide .de-btn-hide-user', 'R0lGODlhDgAOAJEAAP+/v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7 '); x += gif('.de-btn-expthr', p + 'bVI55pu0BwEMxzlonlHp331kXxjlYWH4KowkFADs='); x += gif('.de-btn-fav', p + 'dVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw=='); x += gif('.de-btn-fav-sel', 'R0lGODlhDgAOAJEAAP/hAIyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw=='); x += gif('.de-btn-hide', p + 'dVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw=='); x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAJEAAL//v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw=='); x += gif('.de-btn-rep', p + 'aVI55pu2vAIBISmrty7rx63FbN1LmiTCUUAAAOw=='); x += gif('.de-btn-sage', 'R0lGODlhDgAOAJEAAPDw8FBQUP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu0AgZs0SoqTzdnu5l1P1ImcwmBCAQA7'); x += gif('.de-btn-src', p + 'fVI55pt0ADnRh1uispfvpLkEieGGiZ5IUGmJrw7xCAQA7'); x += gif('.de-btn-stick', p + 'XVI55pu0PI5j00erutJpfj0XiKDKRUAAAOw=='); x += gif('.de-btn-stick-on', 'R0lGODlhDgAOAJEAAL//v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIXVI55pu0PI5j00erutJpfj0XiKDKRUAAAOw=='); } if(!pr.form && !pr.oeForm) { x += '.de-btn-rep { display: none; }'; } // Search images buttons x += cont('.de-src-google', 'http://google.com/favicon.ico'); x += cont('.de-src-tineye', 'http://tineye.com/favicon.ico'); x += cont('.de-src-iqdb', 'http://iqdb.org/favicon.ico'); x += cont('.de-src-saucenao', 'http://saucenao.com/favicon.ico'); // Posts counter x += '.de-ppanel-cnt:after { counter-increment: de-cnt 1; content: counter(de-cnt); margin-right: 4px; vertical-align: 1px; color: #4f7942; font: bold 11px tahoma; cursor: default; }\ .de-ppanel-del:after { content: "' + Lng.deleted[lang] + '"; margin-right: 4px; vertical-align: 1px; color: #727579; font: bold 11px tahoma; cursor: default; }'; // Text format buttons x += '#de-txt-panel { display: block; height: 23px; font-weight: bold; cursor: pointer; }\ #de-txt-panel > span:empty { display: inline-block; width: 27px; height: 23px; }'; p = 'R0lGODlhFwAWAJEAAPDw8GRkZAAAAP///yH5BAEAAAMALAAAAAAXABYAQAJ'; x += gif('#de-btn-bold:empty', p + 'T3IKpq4YAoZgR0KqqnfzipIUikFWc6ZHBwbQtG4zyonW2Vkb2iYOo8Ps8ZLOV69gYEkU5yQ7YUzqhzmgsOLXWnlRIc9PleX06rnbJ/KITDqTLUAAAOw=='); x += gif('#de-btn-italic:empty', p + 'K3IKpq4YAYxRCSmUhzTfx3z3c9iEHg6JnAJYYSFpvRlXcLNUg3srBmgr+RL0MzxILsYpGzyepfEIjR43t5kResUQmtdpKOIQpQwEAOw=='); x += gif('#de-btn-under:empty', p + 'V3IKpq4YAoRARzAoV3hzoDnoJNlGSWSEHw7JrEHILiVp1NlZXtKe5XiptPrFh4NVKHh9FI5NX60WIJ6ATZoVeaVnf8xSU4r7NMRYcFk6pzYRD2TIUAAA7'); x += gif('#de-btn-strike:empty', p + 'S3IKpq4YAoRBR0qqqnVeD7IUaKHIecjCqmgbiu3jcfCbAjOfTZ0fmVnu8YIHW6lgUDkOkCo7Z8+2AmCiVqHTSgi6pZlrN3nJQ8TISO4cdyJWhAAA7'); x += gif('#de-btn-spoil:empty', 'R0lGODlhFwAWAJEAAPDw8GRkZP///wAAACH5BAEAAAIALAAAAAAXABYAQAJBlIKpq4YAmHwxwYtzVrprXk0LhBziGZiBx44hur4kTIGsZ99fSk+mjrMAd7XerEg7xnpLIVM5JMaiFxc14WBiBQUAOw=='); x += gif('#de-btn-code:empty', p + 'O3IKpq4YAoZgR0KpqnFxokH2iFm7eGCEHw7JrgI6L2F1YotloKek6iIvJAq+WkfgQinjKVLBS45CePSXzt6RaTjHmNjpNNm9aq6p4XBgKADs='); x += gif('#de-btn-sup:empty', p + 'Q3IKpq4YAgZiSQhGByrzn7YURGFGWhxzMuqqBGC7wRUNkeU7nnWNoMosFXKzi8BHs3EQnDRAHLY2e0BxnWfEJkRdT80NNTrliG3aWcBhZhgIAOw=='); x += gif('#de-btn-sub:empty', p + 'R3IKpq4YAgZiSxquujtOCvIUayAkVZEoRcjCu2wbivMw2WaYi7vVYYqMFYq/i8BEM4ZIrYOmpdD49m2VFd2oiUZTORWcNYT9SpnZrTjiML0MBADs='); x += gif('#de-btn-quote:empty', p + 'L3IKpq4YAYxRUSKguvRzkDkZfWFlicDCqmgYhuGjVO74zlnQlnL98uwqiHr5ODbDxHSE7Y490wxF90eUkepoysRxrMVaUJBzClaEAADs='); // Show/close animation if(nav.Anim) { x += '@keyframes de-open {\ 0% { transform: translateY(-1500px); }\ 40% { transform: translateY(30px); }\ 70% { transform: translateY(-10px); }\ 100% { transform: translateY(0); }\ }\ @keyframes de-close {\ 0% { transform: translateY(0); }\ 20% { transform: translateY(20px); }\ 100% { transform: translateY(-4000px); }\ }\ @keyframes de-blink {\ 0%, 100% { transform: translateX(0); }\ 10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }\ 20%, 40%, 60%, 80% { transform: translateX(10px); }\ }\ @keyframes de-cfg-open { from { transform: translate(0,50%) scaleY(0); opacity: 0; } }\ @keyframes de-cfg-close { to { transform: translate(0,50%) scaleY(0); opacity: 0; } }\ @keyframes de-post-open-tl { from { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-open-bl { from { transform: translate(-50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-open-tr { from { transform: translate(50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-open-br { from { transform: translate(50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-tl { to { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-bl { to { transform: translate(-50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-tr { to { transform: translate(50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-br { to { transform: translate(50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-new { from { transform: translate(0,-50%) scaleY(0); opacity: 0; } }\ .de-pview-anim { animation-duration: .2s; animation-timing-function: ease-in-out; animation-fill-mode: both; }\ .de-open { animation: de-open .7s ease-out both; }\ .de-close { animation: de-close .7s ease-in both; }\ .de-blink { animation: de-blink .7s ease-in-out both; }\ .de-cfg-open { animation: de-cfg-open .2s ease-out backwards; }\ .de-cfg-close { animation: de-cfg-close .2s ease-in both; }\ .de-post-new { animation: de-post-new .2s ease-out both; }'; } // Embedders x += cont('.de-video-link.de-ytube', 'https://youtube.com/favicon.ico'); x += cont('.de-video-link.de-vimeo', 'https://vimeo.com/favicon.ico'); x += cont('.de-img-arch', 'data:image/gif;base64,R0lGODlhEAAQALMAAF82SsxdwQMEP6+zzRA872NmZQesBylPHYBBHP///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAAAQABAAQARTMMlJaxqjiL2L51sGjCOCkGiBGWyLtC0KmPIoqUOg78i+ZwOCUOgpDIW3g3KJWC4t0ElBRqtdMr6AKRsA1qYy3JGgMR4xGpAAoRYkVDDWKx6NRgAAOw=='); x += cont('.de-img-audio', 'data:image/gif;base64,R0lGODlhEAAQAKIAAGya4wFLukKG4oq3802i7Bqy9P///wAAACH5BAEAAAYALAAAAAAQABAAQANBaLrcHsMN4QQYhE01OoCcQIyOYQGooKpV1GwNuAwAa9RkqTPpWqGj0YTSELg0RIYM+TjOkgba0sOaAEbGBW7HTQAAOw=='); x += '.de-current:after { content: "\u25C4"; }\ .de-img-arch, .de-img-audio { color: inherit; text-decoration: none; font-weight: bold; }\ .de-img-pre, .de-img-full { display: block; border: none; outline: none; cursor: pointer; }\ .de-img-pre { max-width: 200px; max-height: 200px; }\ .de-img-full { float: left; }\ .de-img-center { position: fixed; margin: 0 !important; z-index: 9999; background-color: #ccc; border: 1px solid black !important; }\ #de-img-btn-next > div, #de-img-btn-prev > div { height: 36px; width: 36px; }' + gif('#de-img-btn-next > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJPjI8JkO1vlpzS0YvzhUdX/nigR2ZgSJ6IqY5Uy5UwJK/l/eI6A9etP1N8grQhUbg5RlLKAJD4DAJ3uCX1isU4s6xZ9PR1iY7j5nZibixgBQA7') + gif('#de-img-btn-prev > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJOjI8JkO24ooxPzYvzfJrWf3Rg2JUYVI4qea1g6zZmPLvmDeM6Y4mxU/v1eEKOpziUIA1BW+rXXEVVu6o1dQ1mNcnTckp7In3LAKyMchUAADs=') + '#de-img-btn-next, #de-img-btn-prev { position: fixed; top: 50%; z-index: 10000; margin-top: -8px; background-color: black; cursor: pointer; }\ #de-img-btn-next { right: 0; border-radius: 10px 0 0 10px; }\ #de-img-btn-prev { left: 0; border-radius: 0 10px 10px 0; }\ .de-mp3, .de-video-obj { margin: 5px 20px; }\ .de-video-title[de-time]:after { content: " [" attr(de-time) "]"; color: red; }\ td > a + .de-video-obj, td > img + .de-video-obj { display: inline-block; }\ video { background: black; }'; // Other x += cont('.de-wait', 'data:image/gif;base64,R0lGODlhEAAQALMMAKqooJGOhp2bk7e1rZ2bkre1rJCPhqqon8PBudDOxXd1bISCef///wAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAMACwAAAAAEAAQAAAET5DJyYyhmAZ7sxQEs1nMsmACGJKmSaVEOLXnK1PuBADepCiMg/DQ+/2GRI8RKOxJfpTCIJNIYArS6aRajWYZCASDa41Ow+Fx2YMWOyfpTAQAIfkEBQAADAAsAAAAABAAEAAABE6QyckEoZgKe7MEQMUxhoEd6FFdQWlOqTq15SlT9VQM3rQsjMKO5/n9hANixgjc9SQ/CgKRUSgw0ynFapVmGYkEg3v1gsPibg8tfk7CnggAIfkEBQAADAAsAAAAABAAEAAABE2QycnOoZjaA/IsRWV1goCBoMiUJTW8A0XMBPZmM4Ug3hQEjN2uZygahDyP0RBMEpmTRCKzWGCkUkq1SsFOFQrG1tr9gsPc3jnco4A9EQAh+QQFAAAMACwAAAAAEAAQAAAETpDJyUqhmFqbJ0LMIA7McWDfF5LmAVApOLUvLFMmlSTdJAiM3a73+wl5HYKSEET2lBSFIhMIYKRSimFriGIZiwWD2/WCw+Jt7xxeU9qZCAAh+QQFAAAMACwAAAAAEAAQAAAETZDJyRCimFqbZ0rVxgwF9n3hSJbeSQ2rCWIkpSjddBzMfee7nQ/XCfJ+OQYAQFksMgQBxumkEKLSCfVpMDCugqyW2w18xZmuwZycdDsRACH5BAUAAAwALAAAAAAQABAAAARNkMnJUqKYWpunUtXGIAj2feFIlt5JrWybkdSydNNQMLaND7pC79YBFnY+HENHMRgyhwPGaQhQotGm00oQMLBSLYPQ9QIASrLAq5x0OxEAIfkEBQAADAAsAAAAABAAEAAABE2QycmUopham+da1cYkCfZ94UiW3kmtbJuRlGF0E4Iwto3rut6tA9wFAjiJjkIgZAYDTLNJgUIpgqyAcTgwCuACJssAdL3gpLmbpLAzEQA7'); x += '.de-abtn { text-decoration: none !important; outline: none; }\ .de-after-fimg { clear: left; }\ #de-alert { position: fixed; right: 0; top: 0; z-index: 9999; font: 14px arial; cursor: default; }\ #de-alert > div { overflow: visible !important; float: right; clear: both; width: auto; min-width: 0pt; padding: 10px; margin: 1px; border: 1px solid grey; white-space: pre-wrap; }\ .de-alert-btn { display: inline-block; vertical-align: top; color: green; cursor: pointer; }\ .de-alert-btn:not(.de-wait) + div { margin-top: .15em; }\ .de-alert-msg { display: inline-block; }\ .de-content textarea { display: block; margin: 2px 0; font: 12px courier new; ' + (nav.Presto ? '' : 'resize: none !important; ') + '}\ .de-content-block > a { color: inherit; font-weight: bold; font-size: 14px; }\ #de-content-fav, #de-content-hid { font-size: 16px; padding: 10px; border: 1px solid gray; }\ .de-editor { display: block; font: 12px courier new; width: 619px; height: 337px; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; }\ .de-entry { margin: 2px 0; font-size: 14px; ' + (nav.Presto ? 'white-space: nowrap; ' : '') + '}\ .de-entry > :first-child { float: none !important; }\ .de-entry > div > a { text-decoration: none; }\ .de-fav-inf-posts, .de-fav-inf-page { float: right; margin-right: 5px; font: bold 16px serif; }\ .de-fav-inf-new { color: #424f79; }\ .de-fav-inf-new:before { content: " + "; }\ .de-fav-inf-old { color: #4f7942; }\ .de-fav-title { margin-right: 15px; }\ .de-file { display: inline-block; margin: 1px; height: 130px; width: 130px; text-align: center; border: 1px dashed grey; }\ .de-file > .de-file-del { float: right; }\ .de-file > .de-file-rar { float: left; }\ .de-file > .de-file-rarmsg { float: left; padding: 0 4px 2px; color: #fff; background-color: rgba(55, 55, 55, 0.5); }\ .de-file > .de-file-utils { display: none; }\ .de-file > div { display: table; width: 100%; height: 100%; cursor: pointer; }\ .de-file > div > div { display: table-cell; vertical-align: middle; }\ .de-file + [type="file"] { opacity: 0; margin: 1px 0 0 -132px !important; vertical-align: top; width: 132px !important; height: 132px; border: none !important; cursor: pointer; }\ .de-file-drag { background: rgba(88, 88, 88, 0.4); border: 1px solid grey; }\ .de-file-hover > .de-file-utils { display: block; position: relative; margin: -18px 2px; }\ .de-file-img > img, .de-file-img > video { max-width: 126px; max-height: 126px; }\ .de-file-off > div > div:after { content: "' + Lng.noFile[lang] + '" }\ .de-file-off + .de-file-off { display: none; }\ .de-file-rarmsg { margin: 0 5px; font: bold 11px tahoma; cursor: default; }\ .de-file-del, .de-file-rar { display: inline-block; margin: 0 4px -3px; width: 16px; height: 16px; cursor: pointer; }'; x += gif('.de-file-del', 'R0lGODlhEAAQALMOAP8zAMopAJMAAP/M//+DIP8pAP86Av9MDP9sFP9zHv9aC/9gFf9+HJsAAP///wAAACH5BAEAAA4ALAAAAAAQABAAAARU0MlJKw3B4hrGyFP3hQNBjE5nooLJMF/3msIkJAmCeDpeU4LFQkFUCH8VwWHJRHIM0CiIMwBYryhS4XotZDuFLUAg6LLC1l/5imykgW+gU0K22C0RADs='); x += gif('.de-file-rar', 'R0lGODlhEAAQALMAAF82SsxdwQMEP6+zzRA872NmZQesBylPHYBBHP///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAAAQABAAQARTMMlJaxqjiL2L51sGjCOCkGiBGWyLtC0KmPIoqUOg78i+ZwOCUOgpDIW3g3KJWC4t0ElBRqtdMr6AKRsA1qYy3JGgMR4xGpAAoRYkVDDWKx6NRgAAOw=='); x += '.de-menu { padding: 0 !important; margin: 0 !important; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important;}\ .de-menu-item { display: block; padding: 3px 10px; color: inherit; text-decoration: none; font: 13px arial; white-space: nowrap; cursor: pointer; }\ .de-menu-item:hover { background-color: #222; color: #fff; }\ .de-new-post { ' + (nav.Presto ? 'border-left: 4px solid blue; border-right: 4px solid blue; }' : 'box-shadow: 6px 0 2px -2px blue, -6px 0 2px -2px blue; }') + '\ .de-omitted { color: grey; font-style: italic; }\ .de-omitted:before { content: "' + Lng.postsOmitted[lang] + '"; }\ .de-opref::after { content: " [OP]"; }\ .de-parea { text-align: center; }\ .de-parea-btn-close:after { content: "' + Lng.hideForm[lang] + '" }\ .de-parea-btn-thrd:after { content: "' + Lng.makeThrd[lang] + '" }\ .de-parea-btn-reply:after { content: "' + Lng.makeReply[lang] + '" }\ .de-pview { position: absolute; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important; margin: 0 !important; display: block !important; }\ .de-pview-info { padding: 3px 6px !important; }\ .de-pview-link { font-weight: bold; }\ .de-ref-hid { text-decoration: line-through !important; }\ .de-refmap { margin: 10px 4px 4px 4px; font-size: 75%; font-style: italic; }\ .de-refmap:before { content: "' + Lng.replies[lang] + ' "; }\ .de-reflink { text-decoration: none; }\ .de-refcomma:last-child { display: none; }\ #de-sagebtn { margin-right: 7px; cursor: pointer; }\ .de-selected, .de-error-key { ' + (nav.Presto ? 'border-left: 4px solid red; border-right: 4px solid red; }' : 'box-shadow: 6px 0 2px -2px red, -6px 0 2px -2px red; }') + '\ #de-txt-resizer { display: inline-block !important; float: none !important; padding: 6px; margin: -2px -12px; vertical-align: bottom; border-bottom: 2px solid #555; border-right: 2px solid #444; cursor: se-resize; }\ #de-updater-btn:after { content: "' + Lng.getNewPosts[lang] + '" }\ #de-updater-div { clear: left; margin-top: 10px; }\ .de-viewed { color: #888 !important; }\ .de-hidden, small[id^="rfmap"], body > hr, .theader, .postarea, .thumbnailmsg { display: none !important; }\ form > hr { clear: both }\ ' + aib.css + aib.cssEn + '.de-post-hide > ' + aib.qHide + ' { display: none !important; }'; if(!nav.Firefox) { x = x.replace(/(transition|keyframes|transform|animation|linear-gradient)/g, nav.cssFix + '$1'); if(!nav.Presto) { x = x.replace(/\(to bottom/g, '(top').replace(/\(to top/g, '(bottom'); } } applyCSS(x); } function applyCSS(x) { $css(x).id = 'de-css'; $css('').id = 'de-css-dynamic'; $css('').id = 'de-css-user'; updateCSS(); } function updateCSS() { var x; if(Cfg['attachPanel']) { x = '.de-content { position: fixed; right: 0; bottom: 25px; z-index: 9999; max-height: 95%; overflow-x: visible; overflow-y: auto; }\ #de-panel { position: fixed; right: 0; bottom: 0; }' } else { x = '.de-content { clear: both; float: right; }\ #de-panel { float: right; clear: both; }' } if(Cfg['addPostForm'] === 3) { x += '#de-qarea { position: fixed; right: 0; bottom: 25px; z-index: 9990; padding: 3px; border: 1px solid gray; }\ #de-qarea-target { font-weight: bold; }\ #de-qarea-close { float: right; color: green; font: bold 20px arial; cursor: pointer; }'; } else { x += '#de-qarea { float: none; clear: left; width: 100%; padding: 3px 0 3px 3px; margin: 2px 0; }'; } if(!Cfg['panelCounter']) { x += '#de-panel-info { display: none; }'; } if(Cfg['maskImgs']) { x += '.de-img-pre, .de-video-obj, .thumb, .ca_thumb, .fileThumb, img[src*="spoiler"], img[src*="thumb"], img[src^="blob"] { opacity: 0.07 !important; }\ .de-img-pre:hover, .de-video-obj:hover, .thumb:hover, .ca_thumb:hover, .fileThumb:hover, img[src*="spoiler"]:hover, img[src*="thumb"]:hover, img[src^="blob"]:hover { opacity: 1 !important; }'; } if(!(aib.dobr || aib.krau)) { x += '.de-img-full { margin: 2px 10px; }'; } if(Cfg['delHiddPost']) { x += '.de-thr-hid, .de-thr-hid + div + br, .de-thr-hid + div + br + hr { display: none; }'; } if(Cfg['noPostNames']) { x += aib.qName + ', .' + aib.cTrip + ' { display: none; }'; } if(Cfg['noSpoilers']) { x += '.spoiler' + (aib.fch ? ', s' : '') + ' { background: #888 !important; color: #ccc !important; }'; } if(Cfg['noPostScrl']) { x += 'blockquote, blockquote > p, .code_part { max-height: 100% !important; overflow: visible !important; }'; } if(Cfg['noBoardRule']) { x += (aib.futa ? '.chui' : '.rules, #rules, #rules_row') + ' { display: none; }'; } if(aib.abu || aib.toho) { if(Cfg['addYouTube']) { x += 'div[id^="post_video"] { display: none !important; }'; } } $id('de-css-dynamic').textContent = x; $id('de-css-user').textContent = Cfg['userCSS'] ? Cfg['userCSSTxt'] : ''; } //============================================================================================================ // SCRIPT UPDATING //============================================================================================================ function checkForUpdates(isForce, Fn) { var day, temp = Cfg['scrUpdIntrv']; if(!isForce) { day = 2 * 1000 * 60 * 60 * 24; switch(temp) { case 0: temp = day; break; case 1: temp = day * 2; break; case 2: temp = day * 7; break; case 3: temp = day * 14; break; default: temp = day * 30; } if(Date.now() - +comCfg['lastUpd'] < temp) { return; } } GM_xmlhttpRequest({ 'method': 'GET', 'url': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js', 'headers': {'Content-Type': 'text/plain'}, 'onreadystatechange': function(xhr) { if(xhr.readyState !== 4) { return; } if(xhr.status === 200) { var dVer = xhr.responseText.match(/@version\s+([0-9.]+)/)[1].split('.'), cVer = version.split('.'), len = cVer.length > dVer.length ? cVer.length : dVer.length, i = 0, isUpd = false; if(!dVer) { if(isForce) { Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>'); } return; } saveComCfg('lastUpd', Date.now()); while(i < len) { if((+dVer[i] || 0) > (+cVer[i] || 0)) { isUpd = true; break; } else if((+dVer[i] || 0) < (+cVer[i] || 0)) { break; } i++; } if(isUpd) { Fn('<a style="color: blue; font-weight: bold;" href="https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.user.js">' + Lng.updAvail[lang] + '</a>'); } else if(isForce) { Fn(Lng.haveLatest[lang]); } } else if(isForce) { Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>'); } } }); } //============================================================================================================ // POSTFORM //============================================================================================================ function PostForm(form, ignoreForm, init, dc) { this.oeForm = $q('form[name="oeform"], form[action*="paint"]', dc); if(aib.abu && ($c('locked', form) || this.oeForm)) { this.form = null; if(this.oeForm) { this._init(); } return; } if(!ignoreForm && !form) { if(this.oeForm) { ajaxLoad(aib.getThrdUrl(brd, aib.getTNum(dForm)), false, function(dc, xhr) { pr = new PostForm($q(aib.qPostForm, dc), true, init, dc); }, function(eCode, eMsg, xhr) { pr = new PostForm(null, true, init, dc); }); } else { this.form = null; } return; } function $x(path, root) { return dc.evaluate(path, root, null, 8, null).singleNodeValue; } var p = './/tr[not(contains(@style,"none"))]//input[not(@type="hidden") and '; this.tNum = TNum; this.form = form; this.cap = $q('input[type="text"][name*="aptcha"], div[id*="captcha"]', form); this.txta = $q('tr:not([style*="none"]) textarea:not([style*="display:none"])', form); this.subm = $q('tr input[type="submit"]', form); this.file = $q('tr input[type="file"]', form); if(this.file) { this.fileTd = getAncestor(this.file, 'TD'); this.fileImgTd = getAncestor(this.txta, 'TD').previousElementSibling; this.fileInputs = []; } this.passw = $q('tr input[type="password"]', form); this.dpass = $q('input[type="password"], input[name="password"]', dForm); this.name = $x(p + '(@name="field1" or @name="name" or @name="internal_n" or @name="nya1" or @name="akane")]', form); this.mail = $x(p + ( aib._410 ? '@name="sage"]' : '(@name="field2" or @name="em" or @name="sage" or @name="email" or @name="nabiki" or @name="dont_bump")]' ), form); this.subj = $x(p + '(@name="field3" or @name="sub" or @name="subject" or @name="internal_s" or @name="nya3" or @name="kasumi")]', form); this.video = $q('tr input[name="video"], tr input[name="embed"]', form); this.gothr = aib.qPostRedir && (p = $q(aib.qPostRedir, form)) && getAncestor(p, 'TR'); if(init) { this._init(); } } PostForm.setUserName = function() { var el = $q('input[info="nameValue"]', doc); if(el) { saveCfg('nameValue', el.value); } pr.name.value = Cfg['userName'] ? Cfg['nameValue'] : ''; }; PostForm.setUserPassw = function() { var el = $q('input[info="passwValue"]', doc); if(el) { saveCfg('passwValue', el.value); } (pr.dpass || {}).value = pr.passw.value = Cfg['passwValue']; }; PostForm.prototype = { isHidden: false, isQuick: false, isTopForm: false, lastQuickPNum: -1, pForm: null, pArea: [], qArea: null, get fileImageTD() { var val = $t(aib.tiny ? 'th' : 'td', getAncestor(this.txta, 'TR')); val.innerHTML = ''; Object.defineProperty(this, 'fileImageTD', { value: val }); return val; }, get rarInput() { var val = doc.body.appendChild($new('input', {'type': 'file', 'style': 'display: none;'}, null)) Object.defineProperty(this, 'rarInput', { value: val }); return val; }, addTextPanel: function() { var i, len, tag, html, btns, tPanel = $id('de-txt-panel'); if(!Cfg['addTextBtns']) { $del(tPanel); return; } if(!tPanel) { tPanel = $new('span', {'id': 'de-txt-panel'}, { 'click': this, 'mouseover': this }); } tPanel.style.cssFloat = Cfg['txtBtnsLoc'] ? 'none' : 'right'; $after(Cfg['txtBtnsLoc'] ? $id('de-txt-resizer') || this.txta : aib._420 ? $c('popup', this.form) : this.subm, tPanel); for(html = '', i = 0, btns = aib.formButtons, len = btns['id'].length; i < len; ++i) { tag = btns['tag'][i]; if(tag === '') { continue; } html += '<span id="de-btn-' + btns['id'][i] + '" de-title="' + Lng.txtBtn[i][lang] + '" de-tag="' + tag + '"' + (btns['bb'][i] ? 'de-bb' : '') + '>' + ( Cfg['addTextBtns'] === 2 ? (i === 0 ? '[ ' : '') + '<a class="de-abtn" href="#">' + btns['val'][i] + '</a>' + (i === len - 1 ? ' ]' : ' / ') : Cfg['addTextBtns'] === 3 ? '<input type="button" value="' + btns['val'][i] + '" style="font-weight: bold;">' : '' ) + '</span>'; } tPanel.innerHTML = html; }, delFilesUtils: function() { for(var i = 0, ins = this.fileInputs, len = ins.length; i < len; ++i) { ins[i].delUtils(); } }, eventFiles: function(parent) { this.fileInputs = []; $each($Q('input[type="file"]', parent || this.fileTd), function(el) { if(!el.obj) { el.obj = new FileInput(this, el); el.obj.init(false); } this.fileInputs.push(el.obj); }.bind(this)); }, handleEvent: function(e) { var x, start, end, scrtop, title, id, txt, len, el = e.target; if(el.tagName !== 'SPAN') { el = el.parentNode; } id = el.id; if(id.startsWith('de-btn')) { if(e.type === 'mouseover') { if(id === 'de-btn-quote') { quotetxt = $txtSelect(); } x = -1; if(keyNav) { switch(id.substr(7)) { case 'bold': x = 12; break; case 'italic': x = 13; break; case 'strike': x = 14; break; case 'spoil': x = 15; break; case 'code': x = 16; break; } } KeyEditListener.setTitle(el, x); return; } x = pr.txta; start = x.selectionStart; end = x.selectionEnd; if(id === 'de-btn-quote') { $txtInsert(x, '> ' + (start === end ? quotetxt : x.value.substring(start, end)) .replace(/\n/gm, '\n> ')); } else { scrtop = x.scrollTop; txt = this._wrapText(el.hasAttribute('de-bb'), el.getAttribute('de-tag'), x.value.substring(start, end)); len = start + txt.length; x.value = x.value.substr(0, start) + txt + x.value.substr(end); x.setSelectionRange(len, len); x.focus(); x.scrollTop = scrtop; } $pd(e); e.stopPropagation(); } }, get isVisible() { if(!this.isHidden && this.isTopForm && $q(':focus', this.pForm)) { var cr = this.pForm.getBoundingClientRect(); return cr.bottom > 0 && cr.top < window.innerHeight; } return false; }, get topCoord() { return this.pForm.getBoundingClientRect().top; }, showQuickReply: function(post, pNum, closeReply) { var el, tNum = post.tNum; if(!this.isQuick) { this.isQuick = true; this.setReply(true, false); $t('a', this._pBtn[+this.isTopForm]).className = 'de-abtn de-parea-btn-' + (TNum ? 'reply' : 'thrd'); if(!TNum && !aib.kus && !aib.dobr) { if(this.oeForm) { $del($q('input[name="oek_parent"]', this.oeForm)); this.oeForm.insertAdjacentHTML('afterbegin', '<input type="hidden" value="' + tNum + '" name="oek_parent">'); } if(this.form) { $del($q('#thr_id, input[name="parent"]', this.form)); this.form.insertAdjacentHTML('afterbegin', '<input type="hidden" id="thr_id" value="' + tNum + '" name="' + ( aib.fch || aib.futa ? 'resto' : aib.tiny ? 'thread' : 'parent' ) + '">' ); } } } else if(closeReply && !quotetxt && post.wrap.nextElementSibling === this.qArea) { this.closeQReply(); return; } $after(post.wrap, this.qArea); if(!TNum) { this._toggleQuickReply(tNum); } if(!this.form) { return; } if(this._lastCapUpdate && ((!TNum && this.tNum !== tNum) || (Date.now() - this._lastCapUpdate > 3e5))) { this.tNum = tNum; this.refreshCapImg(false); } this.tNum = tNum; if(aib._420 && this.txta.value === 'Comment') { this.txta.value = ''; } $txtInsert(this.txta, (this.txta.value === '' || this.txta.value.slice(-1) === '\n' ? '' : '\n') + (this.lastQuickPNum === pNum && this.txta.value.contains('>>' + pNum) ? '' : '>>' + pNum + '\n') + (quotetxt ? quotetxt.replace(/^\n|\n$/g, '').replace(/(^|\n)(.)/gm, '$1> $2') + '\n': '')); if(Cfg['addPostForm'] === 3) { el = $t('a', this.qArea.firstChild); el.href = aib.getThrdUrl(brd, tNum); el.textContent = '#' + tNum; } this.lastQuickPNum = pNum; }, showMainReply: function(isTop, evt) { this.closeQReply(); if(this.isTopForm === isTop) { this.pForm.style.display = this.isHidden ? '' : 'none'; this.isHidden = !this.isHidden; this.updatePAreaBtns(); } else { this.isTopForm = isTop; this.setReply(false, false); } if(evt) { $pd(evt); } }, closeQReply: function() { if(this.isQuick) { this.isQuick = false; this.lastQuickPNum = -1; if(!TNum) { this._toggleQuickReply(0); $del($id('thr_id')); } this.setReply(false, !TNum || Cfg['addPostForm'] > 1); } }, refreshCapImg: function(focus) { var src, img; if(aib.abu && (img = $id('captcha_div')) && img.hasAttribute('onclick')) { src = {'isCustom': true, 'focus': focus}; img.dispatchEvent(new CustomEvent('click', { 'bubbles': true, 'cancelable': true, 'detail': (nav.Firefox ? cloneInto(src, document.defaultView) : src) })); return; } if(!this.cap || (aib.krau && !$q('input[name="captcha_name"]', this.form).hasAttribute('value'))) { return; } img = this.recap ? $id('recaptcha_image') : $t('img', this.capTr); if(aib.dobr || aib.krau || aib.dvachnet || this.recap) { img.click(); } else if(img) { src = img.getAttribute('src'); if(aib.kus || aib.tinyIb) { src = src.replace(/\?[^?]+$|$/, (aib._410 ? '?board=' + brd + '&' : '?') + Math.random()); } else { src = src.replace(/pl$/, 'pl?key=mainpage&amp;dummy=') .replace(/dummy=[\d\.]*/, 'dummy=' + Math.random()); src = this.tNum ? src.replace(/mainpage|res\d+/, 'res' + this.tNum) : src.replace(/res\d+/, 'mainpage'); } img.src = ''; img.src = src; } this.cap.value = ''; if(focus) { this.cap.focus(); } if(this._lastCapUpdate) { this._lastCapUpdate = Date.now(); } }, setReply: function(quick, hide) { if(quick) { this.qArea.appendChild(this.pForm); } else { $after(this.pArea[+this.isTopForm], this.qArea); $after(this._pBtn[+this.isTopForm], this.pForm); } this.isHidden = hide; this.qArea.style.display = quick ? '' : 'none'; this.pForm.style.display = hide ? 'none' : ''; this.updatePAreaBtns(); }, updatePAreaBtns: function() { var txt = 'de-abtn de-parea-btn-', rep = TNum ? 'reply' : 'thrd'; $t('a', this._pBtn[+this.isTopForm]).className = txt + (this.pForm.style.display === '' ? 'close' : rep); $t('a', this._pBtn[+!this.isTopForm]).className = txt + rep; }, _lastCapUpdate: 0, _pBtn: [], _init: function() { var btn, el; this.pForm = $New('div', {'id': 'de-pform'}, [this.form, this.oeForm]); dForm.insertAdjacentHTML('beforebegin', '<div class="de-parea"><div>[<a href="#"></a>]</div><hr></div>'); this.pArea[0] = dForm.previousSibling; this._pBtn[0] = this.pArea[0].firstChild; this._pBtn[0].firstElementChild.onclick = this.showMainReply.bind(this, false); el = aib.fch ? $c('board', dForm) : dForm; el.insertAdjacentHTML('afterend', '<div class="de-parea"><div>[<a href="#"></a>]</div><hr></div>'); this.pArea[1] = el.nextSibling; this._pBtn[1] = this.pArea[1].firstChild; this._pBtn[1].firstElementChild.onclick = this.showMainReply.bind(this, true); this.qArea = $add('<div id="de-qarea" class="' + aib.cReply + '" style="display: none;"></div>'); this.isTopForm = Cfg['addPostForm'] !== 0; this.setReply(false, !TNum || Cfg['addPostForm'] > 1); if(Cfg['addPostForm'] === 3) { $append(this.qArea, [ $add('<span id="de-qarea-target">' + Lng.replyTo[lang] + ' <a class="de-abtn"></a></span>'), $new('span', {'id': 'de-qarea-close', 'text': '\u2716'}, {'click': this.closeQReply.bind(this)}) ]); } if(aib.tire) { $each($Q('input[type="hidden"]', dForm), $del); dForm.appendChild($c('userdelete', doc.body)); this.dpass = $q('input[type="password"]', dForm); } if(!this.form) { return; } aib.disableRedirection(this.form); this.form.style.display = 'inline-block'; this.form.style.textAlign = 'left'; if(nav.Firefox) { this.txta.addEventListener('mouseup', function() { saveCfg('textaWidth', parseInt(this.style.width, 10)); saveCfg('textaHeight', parseInt(this.style.height, 10)); }, false); } else { this.txta.insertAdjacentHTML('afterend', '<div id="de-txt-resizer"></div>'); this.txta.nextSibling.addEventListener('mousedown', { el: this.txta, elStyle: this.txta.style, handleEvent: function(e) { switch(e.type) { case 'mousedown': doc.body.addEventListener('mousemove', this, false); doc.body.addEventListener('mouseup', this, false); $pd(e); return; case 'mousemove': var cr = this.el.getBoundingClientRect(); this.elStyle.width = (e.pageX - cr.left - window.pageXOffset) + 'px'; this.elStyle.height = (e.pageY - cr.top - window.pageYOffset) + 'px'; return; default: // mouseup doc.body.removeEventListener('mousemove', this, false); doc.body.removeEventListener('mouseup', this, false); saveCfg('textaWidth', parseInt(this.elStyle.width, 10)); saveCfg('textaHeight', parseInt(this.elStyle.height, 10)); } } }, false); } if(aib.kus) { while(this.subm.nextSibling) { $del(this.subm.nextSibling); } } if(Cfg['addSageBtn'] && this.mail) { btn = $new('span', {'id': 'de-sagebtn'}, {'click': function(e) { e.stopPropagation(); $pd(e); toggleCfg('sageReply'); this._setSage(); }.bind(this)}); el = getAncestor(this.mail, 'LABEL') || this.mail; if(el.nextElementSibling || el.previousElementSibling) { el.style.display = 'none'; $after(el, btn); } else { getAncestor(this.mail, 'TR').style.display = 'none'; $after(this.name || this.subm, btn); } this._setSage(); if(aib._2chru) { while(btn.nextSibling) { $del(btn.nextSibling); } } } this.addTextPanel(); this.txta.style.cssText = 'padding: 0; resize: both; width: ' + Cfg['textaWidth'] + 'px; height: ' + Cfg['textaHeight'] + 'px;'; this.txta.addEventListener('keypress', function(e) { var code = e.charCode || e.keyCode; if((code === 33 || code === 34) && e.which === 0) { e.target.blur(); window.focus(); } }, false); if(!aib.tiny) { this.subm.value = Lng.reply[lang]; } this.subm.addEventListener('click', function(e) { var temp, val = this.txta.value; if(aib._2chru && !aib.reqCaptcha) { GM_xmlhttpRequest({ 'method': 'GET', 'url': '/' + brd + '/api/requires-captcha', 'onreadystatechange': function(xhr) { if(xhr.readyState === 4 && xhr.status === 200) { aib.reqCaptcha = true; if(JSON.parse(xhr.responseText)['requires-captcha'] === '1') { $id('captcha_tr').style.display = 'table-row'; $after(this.cap, $new('span', { 'class': 'shortened', 'style': 'margin: 0px 0.5em;', 'text': 'проверить капчу'}, { 'click': function() { GM_xmlhttpRequest({ 'method': 'POST', 'url': '/' + brd + '/api/validate-captcha', 'onreadystatechange': function(str) { if(str.readyState === 4 && str.status === 200) { if(JSON.parse(str.responseText)['status'] === 'ok') { this.innerHTML = 'можно постить'; } else { this.innerHTML = 'неверная капча'; setTimeout(function() { this.innerHTML = 'проверить капчу'; }.bind(this), 1000); } } }.bind(this) }) } })) } else { this.subm.click(); } } }.bind(this) }); $pd(e); return; } if(Cfg['warnSubjTrip'] && this.subj && /#.|##./.test(this.subj.value)) { $pd(e); $alert(Lng.subjHasTrip[lang], 'upload', false); return; } if(spells.haveOutreps) { val = spells.outReplace(val); } if(this.tNum && pByNum[this.tNum].subj === 'Dollchan Extension Tools') { temp = '\n\n' + this._wrapText(aib.formButtons.bb[5], aib.formButtons.tag[5], '-'.repeat(50) + '\n' + nav.ua + '\nv' + version); if(!val.contains(temp)) { val += temp; } } this.txta.value = val; if(Cfg['ajaxReply']) { $alert(Lng.checking[lang], 'upload', true); } if(Cfg['favOnReply'] && this.tNum) { pByNum[this.tNum].thr.setFavorState(true); } if(this.video && (val = this.video.value) && (val = val.match(new YouTube().ytReg))) { this.video.value = 'http://www.youtube.com/watch?v=' + val[1]; } if(this.isQuick) { this.pForm.style.display = 'none'; this.qArea.style.display = 'none'; $after(this._pBtn[+this.isTopForm], this.pForm); } }.bind(this), false); $each($Q('input[type="text"], input[type="file"]', this.form), function(node) { node.size = 30; }); if(Cfg['noGoto'] && this.gothr) { this.gothr.style.display = 'none'; } if(Cfg['noPassword'] && this.passw) { getAncestor(this.passw, 'TR').style.display = 'none'; } window.addEventListener('load', function() { if(Cfg['userName'] && this.name) { setTimeout(PostForm.setUserName, 1e3); } if(this.passw) { setTimeout(PostForm.setUserPassw, 1e3); } }.bind(this), false); if(this.cap) { if(!(aib.fch && doc.cookie.indexOf('pass_enabled=1') > -1)) { this.capTr = getAncestor(this.cap, 'TR'); this.txta.addEventListener('focus', this._captchaInit.bind(this, this.capTr.innerHTML), false); if(this.file) { this.file.addEventListener('click', this._captchaInit.bind(this, this.capTr.innerHTML), false); } if(!aib.krau) { this.capTr.style.display = 'none'; } this.capTr.innerHTML = ''; } this.cap = null; } if(Cfg['ajaxReply'] === 2) { if(aib.krau) { this.form.removeAttribute('onsubmit'); } this.form.onsubmit = function(e) { $pd(e); if(aib.krau) { aib.addProgressTrack.click(); } new html5Submit(this.form, this.subm, checkUpload); }.bind(this); } else if(Cfg['ajaxReply'] === 1) { this.form.target = 'de-iframe-pform'; this.form.onsubmit = null; } if(el = this.file) { if('files' in el && el.files.length > 0) { el.obj = new FileInput(this, el); el.obj.clear(this.fileTd); } else { this.eventFiles(null); } } }, _setSage: function() { var c = Cfg['sageReply']; $id('de-sagebtn').innerHTML = '&nbsp;' + ( c ? '<span class="de-btn-sage"></span><b style="color: red;">SAGE</b>' : '<i>(no&nbsp;sage)</i>' ); if(this.mail.type === 'text') { this.mail.value = c ? 'sage' : aib.fch ? 'noko' : ''; } else { this.mail.checked = c; } }, _toggleQuickReply: function(tNum) { if(this.oeForm) { $q('input[name="oek_parent"], input[name="replyto"]', this.oeForm).value = tNum; } if(this.form) { $q('#thr_id, input[name*="thread"]', this.form).value = tNum; if(aib.pony) { $q('input[name="quickreply"]', this.form).value = tNum || ''; } } }, _captchaInit: function(html) { if(this.capInited) { return; } this.capTr.innerHTML = html; this.cap = $q('input[type="text"][name*="aptcha"]:not([name="recaptcha_challenge_field"])', this.capTr); if(aib.iich || aib.abu) { $t('td', this.capTr).textContent = 'Капча'; } if(aib.fch) { $script('loadRecaptcha()'); } if(aib.tire) { $script('show_captcha()'); } if(aib.krau) { aib.initCaptcha.click(); $id('captcha_image').setAttribute('onclick', 'requestCaptcha(true);'); } if(aib.dvachnet) { $script('get_captcha()'); } setTimeout(this._captchaUpd.bind(this), 100); }, _captchaUpd: function() { var img, a; if((this.recap = $id('recaptcha_response_field')) && (img = $id('recaptcha_image'))) { this.cap = this.recap; img.setAttribute('onclick', 'Recaptcha.reload()'); img.style.cssText = 'width: 300px; cursor: pointer;'; } else if(aib.fch) { setTimeout(this._captchaUpd.bind(this), 100); return; } this.capInited = true; this.cap.autocomplete = 'off'; this.cap.onkeypress = (function() { var ru = 'йцукенгшщзхъфывапролджэячсмитьбюё', en = 'qwertyuiop[]asdfghjkl;\'zxcvbnm,.`'; return function(e) { if(!Cfg['captchaLang'] || e.which === 0) { return; } var i, code = e.charCode || e.keyCode, chr = String.fromCharCode(code).toLowerCase(); if(Cfg['captchaLang'] === 1) { if(code < 0x0410 || code > 0x04FF || (i = ru.indexOf(chr)) === -1) { return; } chr = en[i]; } else { if(code < 0x0021 || code > 0x007A || (i = en.indexOf(chr)) === -1) { return; } chr = ru[i]; } $pd(e); $txtInsert(e.target, chr); }; })(); if(aib.krau) { return; } if(aib.abu || aib.dobr || aib.dvachnet || this.recap || !(img = $q('img', this.capTr))) { this.capTr.style.display = ''; return; } if(!aib.kus && !aib.tinyIb) { this._lastCapUpdate = Date.now(); this.cap.onfocus = function() { if(this._lastCapUpdate && (Date.now() - this._lastCapUpdate > 3e5)) { this.refreshCapImg(false); } }.bind(this); if(!TNum && this.isQuick) { this.refreshCapImg(false); } } img.title = Lng.refresh[lang]; img.alt = Lng.loading[lang]; img.style.cssText = 'display: block; border: none; cursor: pointer;'; img.onclick = this.refreshCapImg.bind(this, true); if((a = img.parentNode).tagName === 'A') { $after(a, img); $del(a); } this.capTr.style.display = ''; }, _wrapText: function(isBB, tag, text) { var m; if(isBB) { if(text.contains('\n')) { return '[' + tag + ']' + text + '[/' + tag + ']'; } m = text.match(/^(\s*)(.*?)(\s*)$/); return m[1] + '[' + tag + ']' + m[2] + '[/' + tag + ']' + m[3]; } for(var rv = '', i = 0, arr = text.split('\n'), len = arr.length; i < len; ++i) { m = arr[i].match(/^(\s*)(.*?)(\s*)$/); rv += '\n' + m[1] + (tag === '^H' ? m[2] + '^H'.repeat(m[2].length) : tag + m[2] + tag) + m[3]; } return rv.slice(1); } } function FileInput(form, el) { this.el = el; this.place = el.parentNode; this.form = form; } FileInput.prototype = { haveBtns: false, imgFile: null, thumb: null, clear: function(parent) { var form = this.form, cln = parent.cloneNode(false); cln.innerHTML = parent.innerHTML; parent.parentNode.replaceChild(cln, parent); this.el.obj = this; form.file = this.el = $q('input[type="file"]', cln); if(!form.fileTd.parentNode) { form.fileTd = cln; } form.eventFiles(cln); }, delUtils: function() { if(Cfg['fileThumb']) { this._delPview(); } else { $del(this._delUtil); $del(this._rjUtil); } this.imgFile = this._delUtil = this._rjUtil = null; this.haveBtns = false; this.clear(this.el.parentNode); }, updateUtils: function() { this.init(true); if(this._delUtil) { $after(this._buttonsPlace, this._delUtil); } if(this._rjUtil) { $after(this._buttonsPlace, this._rjUtil); } }, handleEvent: function(e) { switch(e.type) { case 'change': this._onFileChange(); break; case 'click': if(e.target === this._delUtil) { this.delUtils(); } else if(e.target === this._rjUtil) { this._addRarJpeg(); } else if(e.target.className === 'de-file-img') { this.el.click(); } e.stopPropagation(); $pd(e); break; case 'dragover': this.thumb.classList.add('de-file-drag'); $after(this.thumb, this.el); break; case 'dragleave': case 'drop': setTimeout(function() { this.thumb.classList.remove('de-file-drag'); var el = this.place.firstChild; if(el) { $before(el, this.el); } else { this.place.appendChild(this.el); } }.bind(this), 10); break; case 'mouseover': this.thumb.classList.add('de-file-hover'); break; case 'mouseout': this.thumb.classList.remove('de-file-hover'); } }, init: function(inited) { var imgTd, fileTr = this.form.fileTd.parentNode; if(Cfg['fileThumb']) { fileTr.style.display = 'none'; imgTd = this.form.fileImageTD; imgTd.insertAdjacentHTML('beforeend', '<div class="de-file de-file-off"><div class="de-file-img">' + '<div class="de-file-img" title="' + Lng.clickToAdd[lang] + '"></div></div></div>'); this.thumb = imgTd.lastChild; this.thumb.addEventListener('click', this, false); this.thumb.addEventListener('mouseover', this, false); this.thumb.addEventListener('mouseout', this, false); this.thumb.addEventListener('dragover', this, false); this.el.addEventListener('dragleave', this, false); this.el.addEventListener('drop', this, false); if(inited) { this._showPviewImage(); } } else if(inited) { fileTr.style.display = ''; this._delPview(); } if(!inited) { this.el.addEventListener('change', this, false); } }, _delUtil: null, _rjUtil: null, get _buttonsPlace() { return Cfg['fileThumb'] ? this.thumb.firstChild : this.el; }, _addRarJpeg: function() { var el = this.form.rarInput; el.onchange = function(e) { $del(this._rjUtil); var file = e.target.files[0], fr = new FileReader(), btnsPlace = this._buttonsPlace; btnsPlace.insertAdjacentHTML('afterend', '<span><span class="de-wait"></span>' + Lng.wait[lang] + '</span>'); this._rjUtil = btnsPlace.nextSibling; fr.onload = function(file, node, e) { if(this._buttonsPlace.nextSibling === node) { node.className = 'de-file-rarmsg de-file-utils'; node.title = this.el.files[0].name + ' + ' + file.name; node.textContent = this.el.files[0].name.replace(/^.+\./, '') + ' + ' + file.name.replace(/^.+\./, '') this.imgFile = e.target.result; } }.bind(this, file, btnsPlace.nextSibling); fr.readAsArrayBuffer(file); }.bind(this); el.click(); }, _delPview: function() { var thumb = this.thumb.firstChild.firstChild.firstChild; if(thumb) { window.URL.revokeObjectURL(thumb.src); } $del(this.thumb); this.thumb = null; }, _onFileChange: function() { if(Cfg['fileThumb']) { this._showPviewImage(); } else { this.form.eventFiles(null); } if(!this.haveBtns) { this.haveBtns = true; $after(this._buttonsPlace, this._delUtil = $new('span', { 'class': 'de-file-del de-file-utils', 'title': Lng.removeFile[lang]}, { 'click': this })); } else if(this.imgFile) { this.imgFile = null; } if(aib.fch || nav.Presto || !/^image\/(?:png|jpeg)$/.test(this.el.files[0].type)) { return; } if(this._rjUtil) { $del(this._rjUtil); this._rjUtil = null; } $after(this._buttonsPlace, this._rjUtil = $new('span', { 'class': 'de-file-rar de-file-utils', 'title': Lng.helpAddFile[lang]}, { 'click': this })); }, _showPviewImage: function() { var fr, files = this.el.files; if(files && files[0]) { fr = new FileReader(); fr.onload = function(e) { this.form.eventFiles(null); var file = this.el.files[0], thumb = this.thumb; if(!thumb) { return; } thumb.className = 'de-file'; thumb = thumb.firstChild.firstChild; thumb.title = file.name + ', ' + (file.size/1024).toFixed(2) + 'KB'; thumb.insertAdjacentHTML('afterbegin', file.type === 'video/webm' ? '<video class="de-file-img" loop autoplay muted src=""></video>' : '<img class="de-file-img" src="">'); thumb = thumb.firstChild; thumb.src = window.URL.createObjectURL(new Blob([e.target.result])); thumb = thumb.nextSibling; if(thumb) { window.URL.revokeObjectURL(thumb.src); $del(thumb); } }.bind(this); fr.readAsArrayBuffer(files[0]); } } } //============================================================================================================ // IMAGES //============================================================================================================ function genImgHash(data) { var i, j, l, c, t, u, g, buf = new Uint8Array(data[0]), oldw = data[1], oldh = data[2], tmp = oldw * oldh, newh = 8, neww = 8, levels = 3, areas = 256 / levels, values = 256 / (levels - 1), hash = 0; for(i = 0, j = 0; i < tmp; i++, j += 4) { buf[i] = buf[j] * 0.3 + buf[j + 1] * 0.59 + buf[j + 2] * 0.11; } for(i = 0; i < newh; i++) { for(j = 0; j < neww; j++) { tmp = i / (newh - 1) * (oldh - 1); l = Math.min(tmp | 0, oldh - 2); u = tmp - l; tmp = j / (neww - 1) * (oldw - 1); c = Math.min(tmp | 0, oldw - 2); t = tmp - c; hash = (hash << 4) + Math.min(values * (((buf[l * oldw + c] * ((1 - t) * (1 - u)) + buf[l * oldw + c + 1] * (t * (1 - u)) + buf[(l + 1) * oldw + c + 1] * (t * u) + buf[(l + 1) * oldw + c] * ((1 - t) * u)) / areas) | 0), 255); if(g = hash & 0xF0000000) { hash ^= g >>> 24; } hash &= ~g; } } return {hash: hash}; } function ImgBtnsShowHider(nextFn, prevFn) { dForm.insertAdjacentHTML('beforeend', '<div style="display: none;">' + '<div id="de-img-btn-next" de-title="' + Lng.nextImg[lang] + '"><div></div></div>' + '<div id="de-img-btn-prev" de-title="' + Lng.prevImg[lang] + '"><div></div></div></div>'); var btns = dForm.lastChild; this._btns = btns; this._btnsStyle = btns.style; this._nextFn = nextFn; this._prevFn = prevFn; window.addEventListener('mousemove', this, false); btns.addEventListener('mouseover', this, false); } ImgBtnsShowHider.prototype = { handleEvent: function(e) { switch(e.type) { case 'mousemove': var curX = e.clientX, curY = e.clientY; if(this._oldX !== curX || this._oldY !== curY) { this._oldX = curX; this._oldY = curY; this.show(); } break; case 'mouseover': if(!this.hasEvents) { this.hasEvents = true; this._btns.addEventListener('mouseout', this, false); this._btns.addEventListener('click', this, false); } if(!this._hidden) { clearTimeout(this._hideTmt); KeyEditListener.setTitle(this._btns.firstChild, 17); KeyEditListener.setTitle(this._btns.lastChild, 4); } break; case 'mouseout': this._setHideTmt(); break; case 'click': switch(e.target.parentNode.id) { case 'de-img-btn-next': this._nextFn(); return; case 'de-img-btn-prev': this._prevFn(); return; default: return; } } }, hide: function() { this._btnsStyle.display = 'none'; this._hidden = true; this._oldX = this._oldY = -1; }, remove: function() { $del(this._btns); window.removeEventListener('mousemove', this, false); clearTimeout(this._hideTmt); }, show: function() { if(this._hidden) { this._btnsStyle.display = ''; this._hidden = false; this._setHideTmt(); } }, _hasEvents: false, _hideTmt: 0, _hidden: true, _oldX: -1, _oldY: -1, _setHideTmt: function() { clearTimeout(this._hideTmt); this._hideTmt = setTimeout(this.hide.bind(this), 2000); } }; function AttachmentViewer(data) { this._show(data); } AttachmentViewer.prototype = { data: null, close: function(e) { if(this.hasOwnProperty('_btns')) { this._btns.remove(); } this._remove(e); }, handleEvent: function(e) { var temp, isOverEvent = false; if(this.data.isVideo && this.data.isControlClick(e, this._elStyle.height)) { return; } switch(e.type) { case 'mousedown': this._oldX = e.clientX; this._oldY = e.clientY; doc.body.addEventListener('mousemove', this, true); doc.body.addEventListener('mouseup', this, true); break; case 'mousemove': var curX = e.clientX, curY = e.clientY; if(curX !== this._oldX || curY !== this._oldY) { this._elStyle.left = parseInt(this._elStyle.left, 10) + curX - this._oldX + 'px'; this._elStyle.top = parseInt(this._elStyle.top, 10) + curY - this._oldY + 'px'; this._oldX = curX; this._oldY = curY; this._moved = true; } return; case 'mouseup': doc.body.removeEventListener('mousemove', this, true); doc.body.removeEventListener('mouseup', this, true); return; case 'click': if(e.button === 0) { if(this._moved) { this._moved = false; } else { this.close(e); Attachment.viewer = null; } e.stopPropagation(); break; } return; case 'mouseover': isOverEvent = true; case 'mouseout': temp = e.relatedTarget; if(!temp || (temp !== this._obj && !this._obj.contains(temp))) { if(isOverEvent) { Pview.mouseEnter(this.data.post); } else if(Pview.top && this.data.post.el !== temp && !this.data.post.el.contains(temp)) { Pview.top.markToDel(); } } return; default: // wheel event var curX = e.clientX, curY = e.clientY, oldL = parseInt(this._elStyle.left, 10), oldT = parseInt(this._elStyle.top, 10), oldW = parseFloat(this._elStyle.width), oldH = parseFloat(this._elStyle.height), d = nav.Firefox ? -e.detail : e.wheelDelta, newW = oldW * (d > 0 ? 1.25 : 0.8), newH = oldH * (d > 0 ? 1.25 : 0.8); this._elStyle.width = newW + 'px'; this._elStyle.height = newH + 'px'; this._elStyle.left = parseInt(curX - (newW/oldW) * (curX - oldL), 10) + 'px'; this._elStyle.top = parseInt(curY - (newH/oldH) * (curY - oldT), 10) + 'px'; } $pd(e); }, navigate: function(isForward) { var data = this.data; do { data = this._navigateHelper(data, isForward); } while(!data.isVideo && !data.isImage); this.update(data, null); }, update: function(data, showButtons, e) { this._remove(e); this._show(data, showButtons); }, _data: null, _elStyle: null, _obj: null, _oldX: 0, _oldY: 0, _moved: false, get _btns() { var val = new ImgBtnsShowHider(this.navigate.bind(this, true), this.navigate.bind(this, false)); Object.defineProperty(this, '_btns', { value: val }); return val; }, _getHolder: function(data) { var obj, html, size = data.computeFullSize(false), el = data.getFullObject(), screenWidth = Post.sizing.wWidth, screenHeight = Post.sizing.wHeight; html = '<div class="de-pic-holder de-img-center" style="top:' + ((screenHeight - size[1]) / 2 - 1) + 'px; left:' + ((screenWidth - size[0]) / 2 - 1) + 'px; width:' + size[0] + 'px; height:' + size[1] + 'px; display: block"></div>'; obj = $add(html); if(data.isImage) { obj.insertAdjacentHTML('afterbegin', '<a href="' + data.src + '"></a>'); obj.firstChild.appendChild(el); } else { obj.appendChild(el); } return obj; }, _navigateHelper: function(data, isForward) { var post = data.post, imgs = post.allImages; if(isForward ? data.idx + 1 === imgs.length : data.idx === 0) { do { post = post.getAdjacentVisPost(!isForward); if(!post) { post = isForward ? firstThr.op : lastThr.last; if(post.hidden || post.thr.hidden) { post = post.getAdjacentVisPost(!isForward); } } imgs = post.allImages; } while(imgs.length === 0); return imgs[isForward ? 0 : imgs.length - 1]; } return imgs[isForward ? data.idx + 1 : data.idx - 1] }, _show: function(data) { var obj = this._getHolder(data), style = obj.style; this._elStyle = style; this.data = data; this._obj = obj; obj.addEventListener(nav.Firefox ? 'DOMMouseScroll' : 'mousewheel', this, true); obj.addEventListener('mousedown', this, true); obj.addEventListener('click', this, true); if(data.inPview) { obj.addEventListener('mouseover', this, true); obj.addEventListener('mouseout', this, true); } if(!data.inPview) { this._btns.show(); } else if(this.hasOwnProperty('_btns')) { this._btns.hide(); } dForm.appendChild(obj); }, _remove: function(e) { $del(this._obj); if(e && this.data.inPview) { this.data.sendCloseEvent(e, false); } } }; function IAttachmentData() {} IAttachmentData.prototype = { expanded: false, get inPview() { var val = this.post.isPview; Object.defineProperty(this, 'inPview', { value: val }); return val; }, get isImage() { var val = /\.jpe?g|\.png|\.gif/i.test(this.src) || (this.src.startsWith('blob:') && !this.el.hasAttribute('de-video')); Object.defineProperty(this, 'isImage', { value: val }); return val; }, get isVideo() { var val = /\.webm$/i.test(this.src) || (this.src.startsWith('blob:') && this.el.hasAttribute('de-video')); Object.defineProperty(this, 'isVideo', { value: val }); return val; }, get height() { var dat = this._getImageSize(); Object.defineProperties(this, { 'width': { value: dat[0] }, 'height': { value: dat[1] } }); return dat[1]; }, get src() { var val = this._getImageSrc();; Object.defineProperty(this, 'src', { value: val }); return val; }, get width() { var dat = this._getImageSize(); Object.defineProperties(this, { 'width': { value: dat[0] }, 'height': { value: dat[1] } }); return dat[0]; }, get wrap() { var val = this._getImageWrap(); Object.defineProperty(this, 'wrap', { value: val }); return val; }, collapse: function(e) { if(!this.isVideo || !this.isControlClick(e, this._fullEl.style.height)) { this.expanded = false; $del(this._fullEl); this._fullEl = null; this.el.parentNode.style.display = ''; $del((aib.hasPicWrap ? this.wrap : this.el.parentNode).nextSibling); if(e && this.inPview) { this.sendCloseEvent(e, true); } return true; } return false; }, computeFullSize: function(inPost) { var newH, newW, scrH, scrW = inPost ? Post.sizing.wWidth - this._offset : Post.sizing.wWidth; newW = !Cfg['resizeImgs'] || this.width < (scrW - 5) ? this.width : scrW - 5; newH = newW * this.height / this.width; if(!inPost) { scrH = Post.sizing.wHeight; if(Cfg['resizeImgs'] && newH > scrH) { newH = scrH - 2; newW = newH * this.width / this.height; } } return [newW / Post.sizing.dPxRatio, newH / Post.sizing.dPxRatio]; }, expand: function(inPost, e) { var size, el = this.el; if(!inPost) { if(Attachment.viewer) { if(Attachment.viewer.data === this) { Attachment.viewer.close(e); Attachment.viewer = null; return; } Attachment.viewer.update(this, e); } else { Attachment.viewer = new AttachmentViewer(this); } return; } this.expanded = true; (aib.hasPicWrap ? this.wrap : el.parentNode).insertAdjacentHTML('afterend', '<div class="de-after-fimg"></div>'); size = this.computeFullSize(inPost); el.parentNode.style.display = 'none'; this._fullEl = this.getFullObject(); this._fullEl.className = 'de-img-full'; this._fullEl.style.width = size[0] + 'px'; this._fullEl.style.height = size[1] + 'px'; $after(el.parentNode, this._fullEl); }, getFullObject: function() { var obj; if(this.isVideo) { if(nav.canPlayWebm) { obj = $add('<video style="width: 100%; height: 100%" src="' + this.src + '" loop autoplay ' + (Cfg['webmControl'] ? 'controls ' : '') + (Cfg['webmVolume'] === 0 ? 'muted ' : '') + '></video>'); if(Cfg['webmVolume'] !== 0) { obj.oncanplay = function() { this.volume = Cfg['webmVolume'] / 100; }; } obj.onerror = function() { if(!this.onceLoaded) { this.load(); this.onceLoaded = true; } }; obj.onvolumechange = function() { saveCfg('webmVolume', Math.round(this.volume * 100)); }; } else { obj = $add('<object style="width: 100%; height: 100%" data="' + this.src + '" type="video/quicktime">' + '<param name="pluginurl" value="http://www.apple.com/quicktime/download/" />' + '<param name="controller" value="' + (Cfg['webmControl'] ? 'true' : 'false') + '" />' + '<param name="autoplay" value="true" />' + '<param name="scale" value="tofit" />' + '<param name="volume" value="' + Math.round(Cfg['webmVolume'] * 2.55) + '" />' + '<param name="wmode" value="transparent" /></object>'); } } else { obj = $add('<img style="width: 100%; height: 100%" src="' + this.src + '" alt="' + this.src + '"></a>'); obj.onload = obj.onerror = function(e) { if(this.naturalHeight + this.naturalWidth === 0 && !this.onceLoaded) { this.src = this.src; this.onceLoaded = true; } }; } return obj; }, isControlClick: function(e, styleHeight) { return Cfg['webmControl'] && e.clientY > (e.target.getBoundingClientRect().top + parseInt(styleHeight, 10) - 30); }, sendCloseEvent: function(e, inPost) { var pv = this.post, cr = pv.el.getBoundingClientRect(), x = e.pageX - pageXOffset, y = e.pageY - pageYOffset; if(!inPost) { while(x > cr.right || x < cr.left || y > cr.bottom || y < cr.top) { if(pv = pv.parent) { cr = pv.el.getBoundingClientRect(); } else { if(Pview.top) { Pview.top.markToDel(); } return; } } if(pv.kid) { pv.kid.markToDel(); } else { clearTimeout(Pview.delTO); } } else if(x > cr.right || y > cr.bottom && Pview.top) { Pview.top.markToDel(); } }, _fullEl: null, get _offset() { var val = -1; if(this._useCache) { val = this._glob._offset; } if(val === -1) { if(this.post.hidden) { this.post.hideContent(false); val = this.el.getBoundingClientRect().left + window.pageXOffset; this.post.hideContent(true); } else { val = this.el.getBoundingClientRect().left + window.pageXOffset; } if(this._useCache) { this._glob._offset = val; } } Object.defineProperty(this, '_offset', { value: val }); return val; } }; function EmbeddedImage(post, el, idx) { this.post = post; this.el = el; this.idx = idx; } EmbeddedImage.prototype = Object.create(IAttachmentData.prototype, { _useCache: { value: false }, _getImageSize: { value: function() { var iEl = new Image(); iEl.src = this.el.src; return [iEl.width, iEl.height]; } }, _getImageSrc: { value: function() { return this.el.src; } }, _getImageWrap: { value: function() { return this.el.parentNode; } } }); function Attachment(post, el, idx) { this.post = post; this.el = el; this.idx = idx; } Attachment.viewer = null; Attachment.prototype = Object.create(IAttachmentData.prototype, { data: { get: function() { var img = this.el, cnv = this._glob.canvas, w = cnv.width = img.naturalWidth, h = cnv.height = img.naturalHeight, ctx = cnv.getContext('2d'); ctx.drawImage(img, 0, 0); return [ctx.getImageData(0, 0, w, h).data.buffer, w, h]; } }, hash: { configurable: true, get: function() { var hash; if(this._processing) { this._needToHide = true; } else if(aib.fch || this.el.complete) { hash = this._maybeGetHash(null); if(hash !== null) { return hash; } } else { this.el.onload = this.el.onerror = this._onload.bind(this); } this.post.hashImgsBusy++; return null; } }, info: { configurable: true, get: function() { var el = $c(aib.cFileInfo, this.wrap), val = el ? el.textContent : ''; Object.defineProperty(this, 'info', { value: val }); return val; } }, weight: { configurable: true, get: function() { var val = aib.getImgWeight(this.info); Object.defineProperty(this, 'weight', { value: val }); return val; } }, getHash: { value: function atGetHash(Fn) { if(this.hasOwnProperty('hash')) { Fn(this.hash); } else { this.callback = Fn; if(!this._processing) { var hash = this._maybeGetHash(); if(hash !== null) { Fn(hash); } } } } }, _glob: { value: { get canvas() { var val = doc.createElement('canvas'); Object.defineProperty(this, 'canvas', { value: val }); return val; }, get storage() { try { var val = JSON.parse(sesStorage['de-imageshash']); } finally { if(!val) { val = {}; } spells.addCompleteFunc(this._saveStorage.bind(this)); Object.defineProperty(this, 'storage', { value: val }); return val; } }, get workers() { var val = new workerQueue(4, genImgHash, function(e) {}); spells.addCompleteFunc(this._clearWorkers.bind(this)); Object.defineProperty(this, 'workers', { value: val, configurable: true }); return val; }, _expAttach: null, _offset: -1, _saveStorage: function() { sesStorage['de-imageshash'] = JSON.stringify(this.storage); }, _clearWorkers: function() { this.workers.clear(); delete this.workers; } } }, _callback: { writable: true, value: null }, _processing: { writable: true, value: false }, _needToHide: { writable: true, value: false }, _useCache: { configurable: true, get: function() { var val = !this.inPview && this.post.count > 4; Object.defineProperty(this, '_useCache', { value: val }); return val; } }, _getImageSize: { value: function atGetImgSize() { return aib.getImgSize(this.info); } }, _getImageSrc: { value: function atGetImageSrc() { return aib.getImgLink(this.el).href; } }, _getImageWrap: { value: function atGetImageWrap() { return aib.getImgWrap(this.el.parentNode); } }, _endLoad: { value: function atEndLoad(hash) { this.post.hashImgsBusy--; if(this.post.hashHideFun !== null) { this.post.hashHideFun(hash); } } }, _maybeGetHash: { value: function atMaybeGetHash() { var data, val; if(this.src in this._glob.storage) { val = this._glob.storage[this.src]; } else if(aib.fch) { downloadImgData(this.el.src, this._onload4chan.bind(this)); this._callback = null; return null; } else if(this.el.naturalWidth + this.el.naturalHeight === 0) { val = -1; } else { data = this.data; this._glob.workers.run(data, [data[0]], this._wrkEnd.bind(this)); this._callback = null; return null; } Object.defineProperty(this, 'hash', { value: val }); return val; } }, _onload: { value: function atOnLoad() { var hash = this._maybeGetHash(null); if(hash !== null) { this._endLoad(hash); } } }, _onload4chan: { value: function atOnload4chan(maybeData) { if(maybeData === null) { Object.defineProperty(this, 'hash', { value: -1 }); this._endLoad(-1); } else { var buffer = maybeData.buffer, data = [buffer, this.el.naturalWidth, this.el.naturalHeight]; this._glob.workers.run(data, [buffer], this._wrkEnd.bind(this)); } } }, _wrkEnd: { value: function atWrkEnd(data) { var hash = data.hash; Object.defineProperty(this, 'hash', { value: hash }); this._endLoad(hash); if(this.callback) { this.callback(hash); this.callback = null; } this._glob.storage[this.src] = hash; } } }); function addImagesSearch(el) { for(var link, i = 0, els = $Q(aib.qImgLink, el), len = els.length; i < len; i++) { link = els[i]; if(/google\.|tineye\.com|iqdb\.org/.test(link.href)) { $del(link); continue; } if(link.firstElementChild) { continue; } link.insertAdjacentHTML('beforebegin', '<span class="de-btn-src" de-menu="imgsrc"></span>'); } } function embedImagesLinks(el) { for(var a, link, i = 0, els = $Q(aib.qMsgImgLink, el); link = els[i++];) { if(link.parentNode.tagName === 'SMALL') { return; } a = link.cloneNode(false); a.target = '_blank'; a.innerHTML = '<img class="de-img-pre" src="' + a.href + '">'; $before(link, a); } } //============================================================================================================ // POST //============================================================================================================ function Post(el, thr, num, count, isOp, prev) { var refEl, html; this.count = count; this.el = el; this.isOp = isOp; this.num = num; this._pref = refEl = $q(aib.qRef, el); this.prev = prev; this.thr = thr; this.ref = []; if(prev) { prev.next = this; } el.post = this; html = '<span class="de-ppanel' + (isOp ? '' : ' de-ppanel-cnt') + '"><span class="de-btn-hide" de-menu="hide"></span><span class="de-btn-rep"></span>'; if(isOp) { if(!TNum && !aib.arch) { html += '<span class="de-btn-expthr" de-menu="expand"></span>'; } html += '<span class="de-btn-fav"></span>'; } if(this.sage = aib.getSage(this.el)) { html += '<span class="de-btn-sage" title="SAGE"></span>'; } // html += '<span class="de-btn-udolil" style="font-weight: bold; color: red; cursor: pointer;">[УДОЛИЛ!!11]</span>'; refEl.insertAdjacentHTML('afterend', html + '</span>'); this.btns = refEl.nextSibling; if(Cfg['expandPosts'] === 1 && this.trunc) { this._getFull(this.trunc, true); } el.addEventListener('mouseover', this, true); } Post.hiddenNums = []; Post.getWrds = function(text) { return text.replace(/\s+/g, ' ').replace(/[^a-zа-яё ]/ig, '').substring(0, 800).split(' '); }; Post.findSameText = function(oNum, oHid, oWords, date, post) { var j, words = Post.getWrds(post.text), len = words.length, i = oWords.length, olen = i, _olen = i, n = 0; if(len < olen * 0.4 || len > olen * 3) { return; } while(i--) { if(olen > 6 && oWords[i].length < 3) { _olen--; continue; } j = len; while(j--) { if(words[j] === oWords[i] || oWords[i].match(/>>\d+/) && words[j].match(/>>\d+/)) { n++; } } } if(n < _olen * 0.4 || len > _olen * 3) { return; } if(oHid) { post.note = ''; if(!post.spellHidden) { post.setVisib(false); } if(post.userToggled) { delete bUVis[brd][post.num]; post.userToggled = false; } } else { post.setUserVisib(true, date, true); post.note = 'similar to >>' + oNum; } return false; }; Post.sizing = { get dPxRatio() { var val = window.devicePixelRatio || 1; Object.defineProperty(this, 'dPxRatio', { value: val }); return val; }, get wHeight() { var val = window.innerHeight; if(!this._enabled) { window.addEventListener('resize', this, false); this._enabled = true; } Object.defineProperties(this, { 'wWidth': { writable: true, configurable: true, value: doc.documentElement.clientWidth }, 'wHeight': { writable: true, configurable: true, value: val } }); return val; }, get wWidth() { var val = doc.documentElement.clientWidth; if(!this._enabled) { window.addEventListener('resize', this, false); this._enabled = true; } Object.defineProperties(this, { 'wWidth': { writable: true, configurable: true, value: val }, 'wHeight': { writable: true, configurable: true, value: window.innerHeight } }); return val; }, handleEvent: function() { this.wHeight = window.innerHeight; this.wWidth = doc.documentElement.clientWidth; }, _enabled: false }; Post.prototype = { banned: false, deleted: false, hasRef: false, hasYTube: false, hidden: false, hashHideFun: null, hashImgsBusy: 0, imagesExpanded: false, inited: true, isPview: false, kid: null, next: null, omitted: false, parent: null, prev: null, spellHidden: false, sticked: false, userToggled: false, viewed: false, ytHideFun: null, ytInfo: null, ytLinksLoading: 0, addFuncs: function() { updRefMap(this, true); embedMP3Links(this); if(Cfg['addImgs']) { embedImagesLinks(this.el); } if(isExpImg) { this.toggleImages(true); } }, handleEvent: function(e) { var temp, el = e.target, type = e.type, isOutEvent = type === 'mouseout'; if(type === 'click') { if(e.button !== 0) { return; } switch(el.tagName) { case 'IMG': if(el.classList.contains('de-video-thumb')) { if(Cfg['addYouTube'] === 3) { this.ytLink.classList.add('de-current'); new YouTube().addPlayer(this.ytObj, this.ytInfo, el.classList.contains('de-ytube')); $pd(e); } } else if(Cfg['expandImgs'] !== 0) { this._clickImage(el, e); } return; case 'VIDEO': if(Cfg['expandImgs'] !== 0 && !(Cfg['webmControl'] && e.clientY > (el.getBoundingClientRect().top + parseInt(el.style.height, 10) - 30))) { this._clickImage(el, e); } return; case 'A': if(el.classList.contains('de-video-link')) { var m = el.ytInfo; if(this.ytInfo === m) { if(Cfg['addYouTube'] === 3) { if($c('de-video-thumb', this.ytObj)) { el.classList.add('de-current'); new YouTube().addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } else { el.classList.remove('de-current'); new YouTube().addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } } else { el.classList.remove('de-current'); this.ytObj.innerHTML = ''; this.ytInfo = null; } } else if(Cfg['addYouTube'] > 2) { this.ytLink.classList.remove('de-current'); this.ytLink = el; new YouTube().addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } else { this.ytLink.classList.remove('de-current'); this.ytLink = el; el.classList.add('de-current'); new YouTube().addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } $pd(e); } else { temp = el.parentNode; if(temp === this.trunc) { this._getFull(temp, false); $pd(e); e.stopPropagation(); } else if(Cfg['insertNum'] && pr.form && temp === this._pref && !/Reply|Ответ/.test(el.textContent)) { if(TNum && Cfg['addPostForm'] > 1 && !pr.isQuick) { pr.showQuickReply(this, this.num, true); } else { if(aib._420 && pr.txta.value === 'Comment') { pr.txta.value = ''; } $txtInsert(pr.txta, '>>' + this.num); } $pd(e); e.stopPropagation(); } } return; } switch(el.className) { case 'de-btn-expthr': this.thr.load(1, false, null); $del(this._menu); this._menu = null; return; case 'de-btn-fav': this.thr.setFavorState(true); return; case 'de-btn-fav-sel': this.thr.setFavorState(false); return; case 'de-btn-hide': case 'de-btn-hide-user': if(this.isPview) { pByNum[this.num].toggleUserVisib(); this.btns.firstChild.className = 'de-btn-hide-user'; if(pByNum[this.num].hidden) { this.btns.classList.add('de-post-hide'); } else { this.btns.classList.remove('de-post-hide'); } } else { this.toggleUserVisib(); } $del(this._menu); this._menu = null; return; case 'de-btn-rep': pr.showQuickReply(this.isPview ? this.getTopParent() : this, this.num, !this.isPview); return; case 'de-btn-sage': addSpell(9, '', false); return; case 'de-btn-stick': case 'de-btn-stick-on': el.className = this.sticked ? 'de-btn-stick' : 'de-btn-stick-on'; this.sticked = !this.sticked; return; case 'de-btn-udolil': this.thr.deletePost(this, false, true); return; } if(el.classList[0] === 'de-menu-item') { this._clickMenu(el); } return; } if(!this._hasEvents) { this._hasEvents = true; this.el.addEventListener('click', this, true); this.el.addEventListener('mouseout', this, true); } else if(this.isPview && isOutEvent) { this._handleMouseEvents(e.relatedTarget, false); } switch(el.classList[0]) { case 'de-reflink': case 'de-preflink': if(Cfg['linksNavig']) { if(isOutEvent) { clearTimeout(this._linkDelay); if(this.kid) { this.kid.markToDel(); } } else { clearTimeout(Pview.delTO); this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']); } $pd(e); e.stopPropagation(); } return; case 'de-btn-expthr': case 'de-btn-hide': case 'de-btn-hide-user': this._addButtonTitle(el); case 'de-btn-src': if(isOutEvent) { this._closeMenu(e.relatedTarget); } else { this._menuDelay = setTimeout(this._addMenu.bind(this, el), Cfg['linksOver']); } return; case 'de-btn-rep': this._addButtonTitle(el); if(!isOutEvent) { quotetxt = $txtSelect(); } return; case 'de-menu': case 'de-menu-item': if(isOutEvent) { this._closeMenu(e.relatedTarget); } else { clearTimeout(this._menuDelay); } return; } if(Cfg['linksNavig'] && el.tagName === 'A' && !el.lchecked) { if(el.textContent.startsWith('>>')) { el.className = 'de-preflink ' + el.className; clearTimeout(Pview.delTO); this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']); $pd(e); e.stopPropagation(); } else { el.lchecked = true; } return; } if(this.isPview && !isOutEvent) { this._handleMouseEvents(e.relatedTarget, true); } }, hideContent: function(hide) { if(hide) { this.el.classList.add('de-post-hide'); } else { this.el.classList.remove('de-post-hide'); } if(nav.Chrome) { if(hide) { this.el.classList.remove('de-post-unhide'); } else { this.el.classList.add('de-post-unhide'); } if(!chromeCssUpd) { chromeCssUpd = setTimeout(function() { doc.head.insertAdjacentHTML('beforeend', '<style id="de-csshide" type="text/css">\ .de-post-hide > ' + aib.qHide + ' { display: none !important; }\ .de-post-unhide > ' + aib.qHide + ' { display: !important; }\ </style>'); $del(doc.head.lastChild); chromeCssUpd = null; }, 200); } } }, hideRefs: function() { if(!Cfg['hideRefPsts'] || !this.hasRef) { return; } this.ref.forEach(function(num) { var pst = pByNum[num]; if(pst && !pst.userToggled) { pst.setVisib(true); pst.note = 'reference to >>' + this.num; pst.hideRefs(); } }, this); }, getAdjacentVisPost: function(toUp) { var post = toUp ? this.prev : this.next; while(post) { if(post.thr.hidden) { post = toUp ? post.thr.op.prev : post.thr.last.next; } else if(post.hidden || post.omitted) { post = toUp ? post.prev : post.next } else { return post; } } return null; }, get html() { var val = this.el.innerHTML; Object.defineProperty(this, 'html', { configurable: true, value: val }); return val; }, get images() { var i, len, el, els = $Q(aib.qThumbImages, this.el), imgs = []; for(i = 0, len = els.length; i < len; ++i) { el = els[i]; el.imgIdx = i; imgs.push(new Attachment(this, el, i)); } Object.defineProperty(this, 'images', { value: imgs }); return imgs; }, get allImages() { var i, len, el, els, val = this.images.slice(), allIdx = val.length; if(Cfg['addImgs']) { for(i = 0, els = $C('de-img-pre', this.el), len = els.length; i < len; ++i, ++allIdx) { el = els[i]; el.imgIdx = allIdx; val.push(new EmbeddedImage(this, el, allIdx)); } } Object.defineProperty(this, 'allImages', { value: val }); return val; }, get mp3Obj() { var val = $new('div', {'class': 'de-mp3'}, null); $before(this.msg, val); Object.defineProperty(this, 'mp3Obj', { value: val }); return val; }, get msg() { var val = $q(aib.qMsg, this.el); Object.defineProperty(this, 'msg', { configurable: true, value: val }); return val; }, get nextInThread() { var post = this.next; return !post || post.count === 0 ? null : post; }, get nextNotDeleted() { var post = this.nextInThread; while(post && post.deleted) { post = post.nextInThread; } return post; }, set note(val) { if(this.isOp) { this.noteEl.textContent = val ? '(autohide: ' + val + ')' : '(' + this.title + ')'; } else if(!Cfg['delHiddPost']) { this.noteEl.textContent = val ? 'autohide: ' + val : ''; } }, get noteEl() { var val; if(this.isOp) { val = this.thr.el.previousElementSibling.lastChild; } else { this.btns.insertAdjacentHTML('beforeend', '<span class="de-post-note"></span>'); val = this.btns.lastChild; } Object.defineProperty(this, 'noteEl', { value: val }); return val; }, get posterName() { var pName = $q(aib.qName, this.el), val = pName ? pName.textContent : ''; Object.defineProperty(this, 'posterName', { value: val }); return val; }, get posterTrip() { var pTrip = $c(aib.cTrip, this.el), val = pTrip ? pTrip.textContent : ''; Object.defineProperty(this, 'posterTrip', { value: val }); return val; }, select: function() { if(this.isOp) { if(this.hidden) { this.thr.el.previousElementSibling.classList.add('de-selected'); } this.thr.el.classList.add('de-selected'); } else { this.el.classList.add('de-selected'); } }, setUserVisib: function(hide, date, sync) { this.setVisib(hide); this.btns.firstChild.className = 'de-btn-hide-user'; this.userToggled = true; if(hide) { this.note = ''; this.hideRefs(); } else { this.unhideRefs(); } bUVis[brd][this.num] = [+!hide, date]; if(sync) { locStorage['__de-post'] = JSON.stringify({ 'brd': brd, 'date': date, 'isOp': this.isOp, 'num': this.num, 'hide': hide, 'title': this.isOp ? this.title : '' }); locStorage.removeItem('__de-post'); } }, setVisib: function(hide) { var el, tEl; if(this.hidden === hide) { return; } if(this.isOp) { this.hidden = this.thr.hidden = hide; tEl = this.thr.el; tEl.style.display = hide ? 'none' : ''; el = $id('de-thr-hid-' + this.num); if(el) { el.style.display = hide ? '' : 'none'; } else { tEl.insertAdjacentHTML('beforebegin', '<div class="' + aib.cReply + ' de-thr-hid" id="de-thr-hid-' + this.num + '">' + Lng.hiddenThrd[lang] + ' <a href="#">№' + this.num + '</a> <span class="de-thread-note"></span></div>'); el = $t('a', tEl.previousSibling); el.onclick = el.onmouseover = el.onmouseout = function(e) { switch(e.type) { case 'click': this.toggleUserVisib(); $pd(e); return; case 'mouseover': this.thr.el.style.display = ''; return; default: // mouseout if(this.hidden) { this.thr.el.style.display = 'none'; } } }.bind(this); } return; } if(Cfg['delHiddPost']) { if(hide) { this.wrap.classList.add('de-hidden'); this.wrap.insertAdjacentHTML('beforebegin', '<span style="counter-increment: de-cnt 1;"></span>'); } else if(this.hidden) { this.wrap.classList.remove('de-hidden'); $del(this.wrap.previousSibling); } } else { if(!hide) { this.note = ''; } this._pref.onmouseover = this._pref.onmouseout = hide && function(e) { this.hideContent(e.type === 'mouseout'); }.bind(this); } this.hidden = hide; this.hideContent(hide); if(Cfg['strikeHidd']) { setTimeout(this._strikePostNum.bind(this, hide), 50); } }, spellHide: function(note) { this.spellHidden = true; if(!this.userToggled) { if(TNum && !this.deleted) { sVis[this.count] = 0; } if(!this.hidden) { this.hideRefs(); } this.setVisib(true); this.note = note; } }, spellUnhide: function() { this.spellHidden = false; if(!this.userToggled) { if(TNum && !this.deleted) { sVis[this.count] = 1; } this.setVisib(false); this.unhideRefs(); } }, get subj() { var subj = $c(aib.cSubj, this.el), val = subj ? subj.textContent : ''; Object.defineProperty(this, 'subj', { value: val }); return val; }, get text() { var val = this.msg.innerHTML .replace(/<\/?(?:br|p|li)[^>]*?>/gi,'\n') .replace(/<[^>]+?>/g,'') .replace(/&gt;/g, '>') .replace(/&lt;/g, '<') .replace(/&nbsp;/g, '\u00A0') .trim(); Object.defineProperty(this, 'text', { configurable: true, value: val }); return val; }, get title() { var val = this.subj || this.text.substring(0, 70).replace(/\s+/g, ' ') Object.defineProperty(this, 'title', { value: val }); return val; }, get tNum() { return this.thr.num; }, toggleImages: function(expand) { for(var dat, i = 0, imgs = this.allImages, len = imgs.length; i < len; ++i) { dat = imgs[i]; if(dat.isImage && (dat.expanded ^ expand)) { if(expand) { dat.expand(true, null); } else { dat.collapse(null); } } } this.imagesExpanded = expand; }, toggleUserVisib: function() { var isOp = this.isOp, hide = !this.hidden, date = Date.now(); this.setUserVisib(hide, date, true); if(isOp) { if(hide) { hThr[brd][this.num] = this.title; } else { delete hThr[brd][this.num]; } saveHiddenThreads(false); } saveUserPosts(true); }, get topCoord() { var el = this.isOp && this.hidden ? this.thr.el.previousElementSibling : this.el; return el.getBoundingClientRect().top; }, get trunc() { var el = $q(aib.qTrunc, this.el), val = null; if(el && /long|full comment|gekürzt|слишком|длинн|мног|полная версия/i.test(el.textContent)) { val = el; } Object.defineProperty(this, 'trunc', { configurable: true, value: val }); return val; }, unhideRefs: function() { if(!Cfg['hideRefPsts'] || !this.hasRef) { return; } this.ref.forEach(function(num) { var pst = pByNum[num]; if(pst && pst.hidden && !pst.userToggled && !pst.spellHidden) { pst.setVisib(false); pst.unhideRefs(); } }); }, unselect: function() { if(this.isOp) { var el = $id('de-thr-hid-' + this.num); if(el) { el.classList.remove('de-selected'); } this.thr.el.classList.remove('de-selected'); } else { this.el.classList.remove('de-selected'); } }, updateMsg: function(newMsg) { var origMsg = aib.dobr ? this.msg.firstElementChild : this.msg, ytExt = $c('de-video-ext', origMsg), ytLinks = $Q(':not(.de-video-ext) > .de-video-link', origMsg); origMsg.parentNode.replaceChild(newMsg, origMsg); Object.defineProperties(this, { 'msg': { configurable: true, value: newMsg }, 'trunc': { configurable: true, value: null } }); delete this.html; delete this.text; new YouTube().updatePost(this, ytLinks, $Q('a[href*="youtu"]', newMsg), false); if(ytExt) { newMsg.appendChild(ytExt); } this.addFuncs(); spells.check(this); closeAlert($id('de-alert-load-fullmsg')); }, get wrap() { var val = aib.getWrap(this.el, this.isOp); Object.defineProperty(this, 'wrap', { value: val }); return val; }, get ytData() { var val = []; Object.defineProperty(this, 'ytData', { value: val }); return val; }, get ytObj() { var val = aib.insertYtPlayer(this.msg, '<div class="de-video-obj"></div>'); Object.defineProperty(this, 'ytObj', { value: val }); return val; }, _hasEvents: false, _linkDelay: 0, _menu: null, _menuDelay: 0, _selRange: null, _selText: '', _addButtonTitle: function(el) { if(el.hasTitle) { return; } el.hasTitle = true; switch(el.className) { case 'de-btn-hide': case 'de-btn-hide-user': el.title = Lng.togglePost[lang]; return; case 'de-btn-expthr': el.title = Lng.expandThrd[lang]; return; case 'de-btn-rep': el.title = Lng.replyToPost[lang]; return; } }, _addMenu: function(el) { var html, cr = el.getBoundingClientRect(), isLeft = false, className = 'de-menu ' + aib.cReply, xOffset = window.pageXOffset; switch(el.getAttribute('de-menu')) { case 'hide': if(!Cfg['menuHiddBtn']) { return; } html = this._addMenuHide(); break; case 'expand': html = '<span class="de-menu-item" info="thr-exp">' + Lng.selExpandThrd[lang] .join('</span><span class="de-menu-item" info="thr-exp">') + '</span>'; break; case 'imgsrc': isLeft = true; className += ' de-imgmenu'; html = this._addMenuImgSrc(el); break; } doc.body.insertAdjacentHTML('beforeend', '<div class="' + className + '" style="position: absolute; ' + ( isLeft ? 'left: ' + (cr.left + xOffset) : 'right: ' + (doc.documentElement.clientWidth - cr.right - xOffset) ) + 'px; top: ' + (window.pageYOffset + cr.bottom) + 'px;">' + html + '</div>'); if(this._menu) { clearTimeout(this._menuDelay); $del(this._menu); } this._menu = doc.body.lastChild; this._menu.addEventListener('click', this, false); this._menu.addEventListener('mouseover', this, false); this._menu.addEventListener('mouseout', this, false); }, _addMenuHide: function() { var sel, ssel, str = '', addItem = function(name) { str += '<span info="spell-' + name + '" class="de-menu-item">' + Lng.selHiderMenu[name][lang] + '</span>'; }; sel = nav.Presto ? doc.getSelection() : window.getSelection(); if(ssel = sel.toString()) { this._selText = ssel; this._selRange = sel.getRangeAt(0); addItem('sel'); } if(this.posterName) { addItem('name'); } if(this.posterTrip) { addItem('trip'); } if(this.images.length === 0) { addItem('noimg'); } else { addItem('img'); addItem('ihash'); } if(this.text) { addItem('text'); } else { addItem('notext'); } return str; }, _addMenuImgSrc: function(el) { var p = el.nextSibling.href + '" target="_blank">' + Lng.search[lang], c = doc.body.getAttribute('de-image-search'), str = ''; if(c) { c = c.split(';'); c.forEach(function(el) { var info = el.split(','); str += '<a class="de-src' + info[0] + (!info[1] ? '" onclick="de_isearch(event, \'' + info[0] + '\')" de-url="' : '" href="' + info[1] ) + p + info[0] + '</a>'; }); } return '<a class="de-menu-item de-imgmenu de-src-iqdb" href="http://iqdb.org/?url=' + p + 'IQDB</a>' + '<a class="de-menu-item de-imgmenu de-src-tineye" href="http://tineye.com/search/?url=' + p + 'TinEye</a>' + '<a class="de-menu-item de-imgmenu de-src-google" href="http://google.com/searchbyimage?image_url=' + p + 'Google</a>' + '<a class="de-menu-item de-imgmenu de-src-saucenao" href="http://saucenao.com/search.php?url=' + p + 'SauceNAO</a>' + str; }, _addPview: function(link) { var tNum = (link.pathname.match(/.+?\/[^\d]*(\d+)/) || [,0])[1], pNum = (link.textContent.trim().match(/\d+$/) || [tNum])[0], pv = this.isPview ? this.kid : Pview.top; if(pv && pv.num === pNum) { Pview.del(pv.kid); setPviewPosition(link, pv.el, Cfg['animation'] && animPVMove); if(pv.parent.num !== this.num) { $each($C('de-pview-link', pv.el), function(el) { el.classList.remove('de-pview-link'); }); pv._markLink(this.num); } this.kid = pv; pv.parent = this; } else { this.kid = new Pview(this, link, tNum, pNum); } }, _clickImage: function(el, e) { // We need to get allImages getter before imgIdx property, do not remove allImgs var var data, allImgs = this.allImages; if(el.classList.contains('de-img-full')) { if(!allImgs[el.previousSibling.firstElementChild.imgIdx].collapse(e)) { return; } } else if(el.imgIdx === undefined || !(data = allImgs[el.imgIdx]) || !(data.isImage || data.isVideo)) { return; } else { data.expand((Cfg['expandImgs'] === 1) ^ e.ctrlKey, e); } $pd(e); e.stopPropagation(); }, _clickMenu: function(el) { $del(this._menu); this._menu = null; switch(el.getAttribute('info')) { case 'spell-sel': var start = this._selRange.startContainer, end = this._selRange.endContainer; if(start.nodeType === 3) { start = start.parentNode; } if(end.nodeType === 3) { end = end.parentNode; } if((nav.matchesSelector(start, aib.qMsg + ' *') && nav.matchesSelector(end, aib.qMsg + ' *')) || (nav.matchesSelector(start, '.' + aib.cSubj) && nav.matchesSelector(end, '.' + aib.cSubj)) ) { if(this._selText.contains('\n')) { addSpell(1 /* #exp */, '/' + regQuote(this._selText).replace(/\r?\n/g, '\\n') + '/', false); } else { addSpell(0 /* #words */, this._selText.replace(/\)/g, '\\)').toLowerCase(), false); } } else { dummy.innerHTML = ''; dummy.appendChild(this._selRange.cloneContents()); addSpell(2 /* #exph */, '/' + regQuote(dummy.innerHTML.replace(/^<[^>]+>|<[^>]+>$/g, '')) + '/', false); } return; case 'spell-name': addSpell(6 /* #name */, this.posterName.replace(/\)/g, '\\)'), false); return; case 'spell-trip': addSpell(7 /* #trip */, this.posterTrip.replace(/\)/g, '\\)'), false); return; case 'spell-img': var img = this.images[0], w = img.weight, wi = img.width, h = img.height; addSpell(8 /* #img */, [0, [w, w], [wi, wi, h, h]], false); return; case 'spell-ihash': this.images[0].getHash(function(hash) { addSpell(4 /* #ihash */, hash, false); }); return; case 'spell-noimg': addSpell(0x108 /* (#all & !#img) */, '', true); return; case 'spell-text': var num = this.num, hidden = this.hidden, wrds = Post.getWrds(this.text), time = Date.now(); for(var post = firstThr.op; post; post = post.next) { Post.findSameText(num, hidden, wrds, time, post); } saveUserPosts(true); return; case 'spell-notext': addSpell(0x10B /* (#all & !#tlen) */, '', true); return; case 'thr-exp': this.thr.load(parseInt(el.textContent, 10), false, null); return; } }, _closeMenu: function(rt) { clearTimeout(this._menuDelay); if(this._menu && (!rt || rt.className !== 'de-menu-item')) { this._menuDelay = setTimeout(function() { $del(this._menu); this._menu = null; }.bind(this), 75); } }, _getFull: function(node, isInit) { if(aib.dobr) { $del(node.nextSibling); $del(node.previousSibling); $del(node); if(isInit) { this.msg.replaceChild($q('.alternate > div', this.el), this.msg.firstElementChild); } else { this.updateMsg($q('.alternate > div', this.el)); } return; } if(!isInit) { $alert(Lng.loading[lang], 'load-fullmsg', true); } ajaxLoad(aib.getThrdUrl(brd, this.tNum), true, function(node, form, xhr) { if(this.isOp) { this.updateMsg(replacePost($q(aib.qMsg, form))); $del(node); } else { for(var i = 0, els = aib.getPosts(form), len = els.length; i < len; i++) { if(this.num === aib.getPNum(els[i])) { this.updateMsg(replacePost($q(aib.qMsg, els[i]))); $del(node); return; } } } }.bind(this, node), null); }, _markLink: function(pNum) { $each($Q('a[href*="' + pNum + '"]', this.el), function(num, el) { if(el.textContent === '>>' + num) { el.classList.add('de-pview-link'); } }.bind(null, pNum)); }, _strikePostNum: function(isHide) { var idx, num = this.num; if(isHide) { Post.hiddenNums.push(+num); } else { idx = Post.hiddenNums.indexOf(+num); if(idx !== -1) { Post.hiddenNums.splice(idx, 1); } } $each($Q('a[href*="#' + num + '"]', dForm), isHide ? function(el) { el.classList.add('de-ref-hid'); } : function(el) { el.classList.remove('de-ref-hid'); }); } }; //============================================================================================================ // PREVIEW //============================================================================================================ function Pview(parent, link, tNum, pNum) { var b, post = pByNum[pNum]; if(Cfg['noNavigHidd'] && post && post.hidden) { return; } this.parent = parent; this._link = link; this.num = pNum; this.thr = parent.thr; Object.defineProperty(this, 'tNum', { value: tNum }); if(post && (!post.isOp || !parent.isPview || !parent._loaded)) { this._showPost(post); return; } b = link.pathname.match(/^\/?(.+\/)/)[1].replace(aib.res, '').replace(/\/$/, ''); if(post = this._cache && this._cache[b + tNum] && this._cache[b + tNum].getPost(pNum)) { this._loaded = true; this._showPost(post); } else { this._showText('<span class="de-wait">' + Lng.loading[lang] + '</span>'); ajaxLoad(aib.getThrdUrl(b, tNum), true, this._onload.bind(this, b), this._onerror.bind(this)); } } Pview.clearCache = function() { Pview.prototype._cache = {}; }; Pview.del = function(pv) { if(!pv) { return; } var el, vPost = Attachment.viewer && Attachment.viewer.data.post; pv.parent.kid = null; if(!pv.parent.isPview) { Pview.top = null; } do { clearTimeout(pv._readDelay); if(vPost === pv) { Attachment.viewer.close(null); Attachment.viewer = vPost = null; } el = pv.el; if(Cfg['animation']) { nav.animEvent(el, $del); el.classList.add('de-pview-anim'); el.style[nav.animName] = 'de-post-close-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r'); } else { $del(el); } } while(pv = pv.kid); }; Pview.mouseEnter = function(post) { if(post.kid) { post.kid.markToDel(); } else { clearTimeout(Pview.delTO); } }; Pview.delTO = 0; Pview.top = null; Pview.prototype = Object.create(Post.prototype, { isPview: { value: true }, getTopParent: { value: function pvGetBoardParent() { var post = this.parent; while(post.isPview) { post = post.parent; } return post; } }, markToDel: { value: function pvMarkToDel() { clearTimeout(Pview.delTO); var lastSticked, el = this; do { if(el.sticked) { lastSticked = el; } } while(el = el.kid); if(!lastSticked || lastSticked.kid) { Pview.delTO = setTimeout(Pview.del, Cfg['linksOut'], lastSticked ? lastSticked.kid : this); } } }, _loaded: { value: false, writable: true }, _cache: { value: {}, writable: true }, _readDelay: { value: 0, writable: true }, _handleMouseEvents: { value: function pvHandleMouseEvents(el, isOverEvent) { if(!el || (el !== this.el && !this.el.contains(el))) { if(isOverEvent) { Pview.mouseEnter(this); } else if(Pview.top && (!this._menu || (this._menu !== el && !this._menu.contains(el)))) { Pview.top.markToDel(); } } } }, _onerror: { value: function(eCode, eMsg, xhr) { Pview.del(this); this._showText(eCode === 404 ? Lng.postNotFound[lang] : getErrorMessage(eCode, eMsg)); } }, _onload: { value: function pvOnload(b, form, xhr) { var rm, parent = this.parent, parentNum = parent.num, cache = this._cache[b + this.tNum] = new PviewsCache(form, b, this.tNum), post = cache.getPost(this.num); if(post && (brd !== b || !post.hasRef || post.ref.indexOf(parentNum) === -1)) { if(post.hasRef) { rm = $c('de-refmap', post.el) } else { post.msg.insertAdjacentHTML('afterend', '<div class="de-refmap"></div>'); rm = post.msg.nextSibling; } rm.insertAdjacentHTML('afterbegin', '<a class="de-reflink" href="' + aib.getThrdUrl(b, parent.tNum) + aib.anchor + parentNum + '">&gt;&gt;' + (brd === b ? '' : '/' + brd + '/') + parentNum + '</a><span class="de-refcomma">, </span>'); } if(parent.kid === this) { Pview.del(this); if(post) { this._loaded = true; this._showPost(post); } else { this._showText(Lng.postNotFound[lang]); } } } }, _showPost: { value: function pvShowPost(post) { var btns, el = this.el = post.el.cloneNode(true), pText = '<span class="de-btn-rep" title="' + Lng.replyToPost[lang] + '"></span>' + (post.sage ? '<span class="de-btn-sage" title="SAGE"></span>' : '') + '<span class="de-btn-stick" title="' + Lng.attachPview[lang] + '"></span>' + (post.deleted ? '' : '<span style="margin-right: 4px; vertical-align: 1px; color: #4f7942; ' + 'font: bold 11px tahoma; cursor: default;">' + (post.isOp ? 'OP' : post.count + 1) + '</span>'); el.post = this; el.className = aib.cReply + ' de-pview' + (post.viewed ? ' de-viewed' : ''); el.style.display = ''; if(Cfg['linksNavig'] === 2) { this._markLink(this.parent.num); } this._pref = $q(aib.qRef, el); if(post.inited) { this.btns = btns = $c('de-ppanel', el); this.isOp = post.isOp; btns.classList.remove('de-ppanel-cnt'); if(post.hidden) { btns.classList.add('de-post-hide'); } btns.innerHTML = '<span class="de-btn-hide' + (post.userToggled ? '-user' : '') + '" de-menu="hide" title="' + Lng.togglePost[lang] + '"></span>' + pText; $each($Q((!TNum && post.isOp ? aib.qOmitted + ', ' : '') + '.de-img-full, .de-after-fimg', el), $del); $each($Q(aib.qThumbImages, el), function(el) { el.parentNode.style.display = ''; }); if(post.hasYTube) { if(post.ytInfo !== null) { Object.defineProperty(this, 'ytObj', { value: $c('de-video-obj', el) }); this.ytInfo = post.ytInfo; } new YouTube().updatePost(this, $C('de-video-link', post.el), $C('de-video-link', el), true); } if(Cfg['addImgs']) { $each($C('de-img-pre', el), function(el) { el.style.display = ''; }); } if(Cfg['markViewed']) { this._readDelay = setTimeout(function(pst) { if(!pst.viewed) { pst.el.classList.add('de-viewed'); pst.viewed = true; } var arr = (sesStorage['de-viewed'] || '').split(','); arr.push(pst.num); sesStorage['de-viewed'] = arr; }, post.text.length > 100 ? 2e3 : 500, post); } } else { this._pref.insertAdjacentHTML('afterend', '<span class="de-ppanel">' + pText + '</span'); embedMP3Links(this); new YouTube().parseLinks(this); if(Cfg['addImgs']) { embedImagesLinks(el); } if(Cfg['imgSrcBtns']) { addImagesSearch(el); } } el.addEventListener('click', this, true); this._showPview(el); } }, _showPview: { value: function pvShowPview(el, id) { if(this.parent.isPview) { Pview.del(this.parent.kid); } else { Pview.del(Pview.top); Pview.top = this; } this.parent.kid = this; el.addEventListener('mouseover', this, true); el.addEventListener('mouseout', this, true); (aib.arch ? doc.body : dForm).appendChild(el); setPviewPosition(this._link, el, false); if(Cfg['animation']) { nav.animEvent(el, function(node) { node.classList.remove('de-pview-anim'); node.style[nav.animName] = ''; }); el.classList.add('de-pview-anim'); el.style[nav.animName] = 'de-post-open-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r'); } } }, _showText: { value: function pvShowText(txt) { this._showPview(this.el = $add('<div class="' + aib.cReply + ' de-pview-info de-pview">' + txt + '</div>')); } }, }); function PviewsCache(form, b, tNum) { var i, len, post, pBn = {}, pProto = Post.prototype, thr = $q(aib.qThread, form) || form, posts = aib.getPosts(thr); for(i = 0, len = posts.length; i < len; ++i) { post = posts[i]; pBn[aib.getPNum(post)] = Object.create(pProto, { count: { value: i + 1 }, el: { value: post, writable: true }, inited: { value: false }, pvInited: { value: false, writable: true }, ref: { value: [], writable: true } }); } pBn[tNum] = this._opObj = Object.create(pProto, { inited: { value: false }, isOp: { value: true }, msg: { value: $q(aib.qMsg, thr), writable: true }, ref: { value: [], writable: true } }); this._brd = b; this._thr = thr; this._tNum = tNum; this._tUrl = aib.getThrdUrl(b, tNum); this._posts = pBn; if(Cfg['linksNavig'] === 2) { genRefMap(pBn, this._tUrl); } } PviewsCache.prototype = { getPost: function(num) { if(num === this._tNum) { return this._op; } var pst = this._posts[num]; if(pst && !pst.pvInited) { pst.el = replacePost(pst.el); delete pst.msg; if(pst.hasRef) { addRefMap(pst, this._tUrl); } pst.pvInited = true; } return pst; }, get _op() { var i, j, len, num, nRef, oRef, rRef, oOp, op = this._opObj; op.el = replacePost(aib.getOp(this._thr)); op.msg = $q(aib.qMsg, op.el); if(this._brd === brd && (oOp = pByNum[this._tNum])) { oRef = op.ref; rRef = []; for(i = j = 0, nRef = oOp.ref, len = nRef.length; j < len; ++j) { num = nRef[j]; if(oRef[i] === num) { i++; } else if(oRef.indexOf(num) !== -1) { continue; } rRef.push(num) } for(len = oRef.length; i < len; i++) { rRef.push(oRef[i]); } op.ref = rRef; if(rRef.length !== 0) { op.hasRef = true; addRefMap(op, this._tUrl); } } else if(op.hasRef) { addRefMap(op, this._tUrl); } Object.defineProperty(this, '_op', { value: op }); return op; } }; function PviewMoved() { if(this.style[nav.animName]) { this.classList.remove('de-pview-anim'); this.style.cssText = this.newPos; this.newPos = false; $each($C('de-css-move', doc.head), $del); this.removeEventListener(nav.animEnd, PviewMoved, false); } } function animPVMove(pView, lmw, top, oldCSS) { var uId = 'de-movecss-' + Math.round(Math.random() * 1e3); $css('@' + nav.cssFix + 'keyframes ' + uId + ' {to { ' + lmw + ' top:' + top + '; }}').className = 'de-css-move'; if(pView.newPos) { pView.style.cssText = pView.newPos; pView.removeEventListener(nav.animEnd, PviewMoved, false); } else { pView.style.cssText = oldCSS; } pView.newPos = lmw + ' top:' + top + ';'; pView.addEventListener(nav.animEnd, PviewMoved, false); pView.classList.add('de-pview-anim'); pView.style[nav.animName] = uId; } function setPviewPosition(link, pView, animFun) { if(pView.link === link) { return; } pView.link = link; var isTop, top, oldCSS, cr = link.getBoundingClientRect(), offX = cr.left + window.pageXOffset + link.offsetWidth / 2, offY = cr.top + window.pageYOffset, bWidth = doc.documentElement.clientWidth, isLeft = offX < bWidth / 2, tmp = (isLeft ? offX : offX - Math.min(parseInt(pView.offsetWidth, 10), offX - 10)), lmw = 'max-width:' + (bWidth - tmp - 10) + 'px; left:' + tmp + 'px;'; if(animFun) { oldCSS = pView.style.cssText; pView.style.cssText = 'opacity: 0; ' + lmw; } else { pView.style.cssText = lmw; } top = pView.offsetHeight; isTop = top + cr.top + link.offsetHeight < window.innerHeight || cr.top - top < 5; top = (isTop ? offY + link.offsetHeight : offY - top) + 'px'; pView.aLeft = isLeft; pView.aTop = isTop; if(animFun) { animFun(pView, lmw, top, oldCSS); } else { pView.style.top = top; } } function addRefMap(post, tUrl) { var i, ref, len, bStr = '<a ' + aib.rLinkClick + ' href="' + tUrl + aib.anchor, html = ['<div class="de-refmap">']; for(i = 0, ref = post.ref, len = ref.length; i < len; ++i) { html.push(bStr, ref[i], '" class="de-reflink">&gt;&gt;', ref[i], '</a><span class="de-refcomma">, </span>'); } html.push('</div>'); if(aib.dobr) { post.msg.nextElementSibling.insertAdjacentHTML('beforeend', html.join('')); } else { post.msg.insertAdjacentHTML('afterend', html.join('')); } } function genRefMap(posts, thrURL) { var tc, lNum, post, ref, i, len, links, url, pNum, opNums = Thread.tNums; for(pNum in posts) { for(i = 0, links = $T('a', posts[pNum].msg), len = links.length; i < len; ++i) { tc = links[i].textContent; if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in posts)) { post = posts[lNum]; ref = post.ref; if(ref.indexOf(pNum) === -1) { ref.push(pNum); post.hasRef = true; } if(opNums.indexOf(lNum) !== -1) { links[i].classList.add('de-opref'); } if(thrURL) { url = links[i].getAttribute('href'); if(url[0] === '#') { links[i].setAttribute('href', thrURL + url); } } } } } } function updRefMap(post, add) { var tc, ref, idx, link, lNum, lPost, i, len, links, pNum = post.num, strNums = add && Cfg['strikeHidd'] && Post.hiddenNums.length !== 0 ? Post.hiddenNums : null, opNums = add && Thread.tNums; for(i = 0, links = $T('a', post.msg), len = links.length; i < len; ++i) { link = links[i]; tc = link.textContent; if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in pByNum)) { lPost = pByNum[lNum]; if(!TNum) { link.href = '#' + (aib.fch ? 'p' : '') + lNum; } if(add) { if(strNums && strNums.lastIndexOf(lNum) !== -1) { link.classList.add('de-ref-hid'); } if(opNums.indexOf(lNum) !== -1) { link.classList.add('de-opref'); } if(lPost.ref.indexOf(pNum) === -1) { lPost.ref.push(pNum); post.hasRef = true; if(Cfg['hideRefPsts'] && lPost.hidden) { if(!post.hidden) { post.hideRefs(); } post.setVisib(true); post.note = 'reference to >>' + lNum; } } else { continue; } } else if(lPost.hasRef) { ref = lPost.ref; idx = ref.indexOf(pNum); if(idx === -1) { continue; } ref.splice(idx, 1); if(ref.length === 0) { lPost.hasRef = false; $del($c('de-refmap', lPost.el)); continue; } } $del($c('de-refmap', lPost.el)); addRefMap(lPost, ''); } } } //============================================================================================================ // THREAD //============================================================================================================ function Thread(el, prev) { if(aib._420 || aib.tiny) { $after(el, el.lastChild); $del($c('clear', el)); } var i, pEl, lastPost, els = aib.getPosts(el), len = els.length, num = aib.getTNum(el), omt = TNum ? 1 : aib.getOmitted($q(aib.qOmitted, el), len); this.num = num; Thread.tNums.push(+num); this.pcount = omt + len; pByNum[num] = lastPost = this.op = el.post = new Post(aib.getOp(el), this, num, 0, true, prev ? prev.last : null); for(i = 0; i < len; i++) { num = aib.getPNum(pEl = els[i]); pByNum[num] = lastPost = new Post(pEl, this, num, omt + i, false, lastPost); } this.last = lastPost; el.style.counterReset = 'de-cnt ' + omt; el.removeAttribute('id'); el.setAttribute('de-thread', null); visPosts = Math.max(visPosts, len); this.el = el; this.prev = prev; if(prev) { prev.next = this; } } Thread.parsed = false; Thread.clearPostsMark = function() { firstThr.clearPostsMarks(); }; Thread.loadNewPosts = function(e) { if(e) { $pd(e); } $alert(Lng.loading[lang], 'newposts', true); firstThr.clearPostsMarks(); updater.forceLoad(); }; Thread.tNums = []; Thread.prototype = { hasNew: false, hidden: false, loadedOnce: false, next: null, get lastNotDeleted() { var post = this.last; while(post.deleted) { post = post.prev; } return post; }, get nextNotHidden() { for(var thr = this.next; thr && thr.hidden; thr = thr.next) {} return thr; }, get prevNotHidden() { for(var thr = this.prev; thr && thr.hidden; thr = thr.prev) {} return thr; }, get topCoord() { return this.op.topCoord; }, clearPostsMarks: function() { if(this.hasNew) { this.hasNew = false; $each($Q('.de-new-post', this.el), function(el) { el.classList.remove('de-new-post'); }); doc.removeEventListener('click', Thread.clearPostsMark, true); } }, deletePost: function(post, delAll, removePost) { var tPost, idx = post.count, count = 0; do { if(removePost) { $del(post.wrap); delete pByNum[post.num]; if(post.hidden) { post.unhideRefs(); } updRefMap(post, false); if(post.prev.next = post.next) { post.next.prev = post.prev; } if(this.last === post) { this.last = post.prev; } } else { post.deleted = true; post.btns.classList.remove('de-ppanel-cnt'); post.btns.classList.add('de-ppanel-del'); ($q('input[type="checkbox"]', post.el) || {}).disabled = true; } post = post.nextNotDeleted; count++; } while(delAll && post); if(!spells.hasNumSpell) { sVis.splice(idx, count); } for(tPost = post; tPost; tPost = tPost.nextInThread) { tPost.count -= count; } this.pcount -= count; return post; }, load: function(last, smartScroll, Fn) { if(!Fn) { $alert(Lng.loading[lang], 'load-thr', true); } ajaxLoad(aib.getThrdUrl(brd, this.num), true, function threadOnload(last, smartScroll, Fn, form, xhr) { this.loadFromForm(last, smartScroll, form); Fn && Fn(); }.bind(this, last, smartScroll, Fn), function(eCode, eMsg, xhr) { $alert(getErrorMessage(eCode, eMsg), 'load-thr', false); if(typeof this === 'function') { this(); } }.bind(Fn)); }, loadFromForm: function(last, smartScroll, form) { var nextCoord, els = aib.getPosts(form), op = this.op, thrEl = this.el, expEl = $c('de-expand', thrEl), nOmt = last === 1 ? 0 : Math.max(els.length - last, 0); if(smartScroll) { if(this.next) { nextCoord = this.next.topCoord; } else { smartScroll = false; } } pr.closeQReply(); $del($q(aib.qOmitted + ', .de-omitted', thrEl)); if(!this.loadedOnce) { if(op.trunc) { op.updateMsg(replacePost($q(aib.qMsg, form))); } op.ref = []; this.loadedOnce = true; } this._checkBans(op, form); this._parsePosts(els); thrEl.style.counterReset = 'de-cnt ' + (nOmt + 1); if(this._processExpandThread(els, last === 1 ? els.length : last)) { $del(expEl); } else if(!expEl) { thrEl.insertAdjacentHTML('beforeend', '<span class="de-expand">[<a href="' + aib.getThrdUrl(brd, this.num) + aib.anchor + this.last.num + '">' + Lng.collapseThrd[lang] + '</a>]</span>'); thrEl.lastChild.onclick = function(e) { $pd(e); this.load(visPosts, true, null); }.bind(this); } else if(expEl !== thrEl.lastChild) { thrEl.appendChild(expEl); } if(nOmt !== 0) { op.el.insertAdjacentHTML('afterend', '<div class="de-omitted">' + nOmt + '</div>'); } if(smartScroll) { scrollTo(pageXOffset, pageYOffset - (nextCoord - this.next.topCoord)); } closeAlert($id('de-alert-load-thr')); }, loadNew: function(Fn, useAPI) { if(aib.dobr && useAPI) { return getJsonPosts('/api/thread/' + brd + '/' + TNum + '.json', function checkNewPosts(status, sText, json, xhr) { if(status !== 200 || json['error']) { Fn(status, sText || json['message'], 0, xhr); } else { if(this._lastModified !== json['last_modified'] || this.pcount !== json['posts_count']) { this._lastModified = json['last_modified']; updater.updateXHR(this.loadNew(Fn, false)); } else { Fn(200, '', 0, xhr); } Fn = null; } }.bind(this) ); } return ajaxLoad(aib.getThrdUrl(brd, TNum), true, function parseNewPosts(form, xhr) { Fn(200, '', this.loadNewFromForm(form), xhr); Fn = null; }.bind(this), function(eCode, eMsg, xhr) { Fn(eCode, eMsg, 0, xhr); Fn = null; }); }, loadNewFromForm: function(form) { this._checkBans(firstThr.op, form); var lastOffset = pr.isVisible ? pr.topCoord : null, info = this._parsePosts(aib.getPosts(form)); if(lastOffset !== null) { scrollTo(pageXOffset, pageYOffset - (lastOffset - pr.topCoord)); } if(info[0] !== 0) { $id('de-panel-info').firstChild.textContent = this.pcount + '/' + $Q(aib.qThumbImages, dForm).length; } return info[1]; }, setFavorState: function(val) { var fav = 'de-btn-fav', favSel = 'de-btn-fav-sel'; ($c(val ? fav : favSel, this.op.btns) || {}).className = val ? favSel : fav; getStoredObj('DESU_Favorites', function(fav) { var h = aib.host, b = brd, num = this.num; if(val) { if(!fav[h]) { fav[h] = {}; } if(!fav[h][brd]) { fav[h][brd] = {}; } fav[h][brd]['url'] = aib.prot + '//' + aib.host + aib.getPageUrl(brd, 0); fav[h][brd][num] = { 'cnt': this.pcount, 'new': 0, 'txt': this.op.title, 'url': aib.getThrdUrl(brd, num) }; } else { removeFavoriteEntry(fav, h, b, num, false); } saveFavorites(fav); }.bind(this)); }, updateHidden: function(data) { var realHid, date = Date.now(), thr = this; do { realHid = thr.num in data; if(thr.hidden ^ realHid) { if(realHid) { thr.op.setUserVisib(true, date, false); data[thr.num] = thr.op.title; } else if(thr.hidden) { thr.op.setUserVisib(false, date, false); } } } while(thr = thr.next); }, _lastModified: '', _addPost: function(parent, el, i, prev) { var post, num = aib.getPNum(el), wrap = aib.getWrap(el, false); el = replacePost(el); pByNum[num] = post = new Post(el, this, num, i, false, prev); Object.defineProperty(post, 'wrap', { value: wrap }); parent.appendChild(wrap); if(TNum && Cfg['animation']) { nav.animEvent(post.el, function(node) { node.classList.remove('de-post-new'); }); post.el.classList.add('de-post-new'); } new YouTube().parseLinks(post); if(Cfg['imgSrcBtns']) { addImagesSearch(el); } post.addFuncs(); preloadImages(el); if(TNum && Cfg['markNewPosts']) { this._addPostMark(el); } return post; }, _addPostMark: function(postEl) { if(updater.focused) { this.clearPostsMarks(); } else { if(!this.hasNew) { this.hasNew = true; doc.addEventListener('click', Thread.clearPostsMark, true); } postEl.classList.add('de-new-post'); } }, _checkBans: function(op, thrNode) { var pEl, bEl, post, i, bEls, len; if(aib.qBan) { for(i = 0, bEls = $Q(aib.qBan, thrNode), len = bEls.length; i < len; ++i) { bEl = bEls[i]; pEl = aib.getPostEl(bEl); post = pEl ? pByNum[aib.getPNum(pEl)] : op; if(post && !post.banned) { if(!$q(aib.qBan, post.el)) { post.msg.appendChild(bEl); } post.banned = true; } } } }, _importPosts: function(last, newPosts, begin, end) { var newCount, newVisCount, fragm = doc.createDocumentFragment(), newCount = newVisCount = end - begin; for(; begin < end; ++begin) { last = this._addPost(fragm, newPosts[begin], begin + 1, last); newVisCount -= spells.check(last); } return [newCount, newVisCount, fragm, last]; }, _parsePosts: function(nPosts) { var i, cnt, firstChangedPost, res, temp, saveSpells = false, newPosts = 0, newVisPosts = 0, len = nPosts.length, post = this.lastNotDeleted; if(aib.dobr || (post.count !== 0 && (post.count > len || aib.getPNum(nPosts[post.count - 1]) !== post.num))) { firstChangedPost = null; post = this.op.nextNotDeleted; for(i = post.count - 1; i < len && post; ) { if(post.num !== aib.getPNum(nPosts[i])) { if(+post.num > +aib.getPNum(nPosts[i])) { if(!firstChangedPost) { firstChangedPost = post.prev; } cnt = 0; do { cnt++; i++; } while(+aib.getPNum(nPosts[i]) < +post.num); res = this._importPosts(post.prev, nPosts, i - cnt, i); newPosts += res[0]; this.pcount += res[0]; newVisPosts += res[1]; $after(post.prev.wrap, res[2]); res[3].next = post; post.prev = res[3]; for(temp = post; temp; temp = temp.nextInThread) { temp.count += cnt; } } else { if(!firstChangedPost) { firstChangedPost = post; } post = this.deletePost(post, false, !TNum); } } else { i++; post = post.nextNotDeleted; } } if(i === len && post) { this.deletePost(post, true, !TNum); } if(firstChangedPost && spells.hasNumSpell) { disableSpells(); for(post = firstChangedPost.nextInThread; post; post = post.nextInThread) { spells.check(post); } saveSpells = true; } if(newPosts !== 0) { for(post = firstChangedPost; post; post = post.nextInThread) { updRefMap(post, true); } } } if(len + 1 > this.pcount) { res = this._importPosts(this.last, nPosts, this.lastNotDeleted.count, len); newPosts += res[0]; newVisPosts += res[1]; this.el.appendChild(res[2]); this.last = res[3]; this.pcount = len + 1; saveSpells = true; } getStoredObj('DESU_Favorites', function(fav) { var el, f, h = aib.host; if(fav[h] && fav[h][brd] && (f = fav[h][brd][this.op.num])) { if(el = $id('de-content-fav')) { el = $q('.de-fav-current > .de-entry[de-num="' + this.op.num + '"] .de-fav-inf-old', el); el.textContent = this.pcount; el = el.nextElementSibling; el.style.display = 'none'; el.textContent = 0; } f['cnt'] = this.pcount; f['new'] = 0; saveFavorites(fav); } }.bind(this)); if(saveSpells) { spells.end(savePosts); } return [newPosts, newVisPosts]; }, _processExpandThread: function(nPosts, num) { var i, fragm, tPost, len, needRMUpdate, post = this.op.next, vPosts = this.pcount === 1 ? 0 : this.last.count - post.count + 1; if(vPosts > num) { while(vPosts-- !== num) { post.wrap.classList.add('de-hidden'); post.omitted = true; post = post.next; } needRMUpdate = false; } else if(vPosts < num) { fragm = doc.createDocumentFragment(); tPost = this.op; len = nPosts.length; for(i = Math.max(0, len - num), len -= vPosts; i < len; ++i) { tPost = this._addPost(fragm, nPosts[i], i + 1, tPost); spells.check(tPost); } $after(this.op.el, fragm); tPost.next = post; if(post) { post.prev = tPost; } needRMUpdate = true; num = Math.min(len + vPosts, num); } else { return num <= visPosts; } while(vPosts-- !== 0) { if(post.trunc) { post.updateMsg(replacePost($q(aib.qMsg, nPosts[post.count - 1]))); } if(post.omitted) { post.wrap.classList.remove('de-hidden'); post.omitted = false; } if(needRMUpdate) { updRefMap(post, true); } post = post.next; } return num <= visPosts; } }; //============================================================================================================ // IMAGEBOARD //============================================================================================================ function getImageBoard(checkDomains, checkOther) { var ibDomains = { '02ch.net': [{ qPostRedir: { value: 'input[name="gb2"][value="thread"]' }, ru: { value: true }, timePattern: { value: 'yyyy+nn+dd++w++hh+ii+ss' } }], get '22chan.net'() { return this['ernstchan.com']; }, '2chru.net': [{ _2chru: { value: true } }, 'form[action*="imgboard.php?delete"]'], get '2-chru.net'() { return this['2chru.net']; }, get '2ch.cm'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.hk'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.pm'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.re'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.tf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.wf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.yt'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2-ch.so'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2-ch.su'() { return this['2--ch.ru']; }, '2--ch.ru': [{ tire: { value: true }, qPages: { value: 'table[border="1"] tr:first-of-type > td:first-of-type a' }, qPostRedir: { value: null }, qTable: { value: 'table:not(.postfiles)' }, qThread: { value: '.threadz' }, getOmitted: { value: function(el, len) { var txt; return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] - len : 1; } }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 0 ? p : 0) + '.memhtml'; } }, css: { value: 'span[id$="_display"], #fastload { display: none !important; }' }, docExt: { value: '.html' }, hasPicWrap: { value: true }, isBB: { value: true }, ru: { value: true } }], '410chan.org': [{ _410: { value: true }, qPostRedir: { value: 'input#noko' }, getSage: { value: function(post) { var el = $c('filetitle', post); return el && el.textContent.contains('\u21E9'); } }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['**', '*', '__', '^^', '%%', '`', '', '', 'q'] } }); } }, isBB: { value: false }, timePattern: { value: 'dd+nn+yyyy++w++hh+ii+ss' } }, 'script[src*="kusaba"]'], '420chan.org': [{ // Posting doesn't work (antispam protection) _420: { value: true }, qBan: { value: '.ban' }, qError: { value: 'pre' }, qHide: { value: '.replyheader ~ *' }, qPages: { value: '.pagelist > a:last-child' }, qPostRedir: { value: null }, qThread: { value: '[id*="thread"]' }, getTNum: { value: function(op) { return $q('a[id]', op).id.match(/\d+/)[0]; } }, css: { value: '#content > hr, .hidethread, .ignorebtn, .opqrbtn, .qrbtn, noscript { display: none !important; }\ .de-thr-hid { margin: 1em 0; }' }, docExt: { value: '.php' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['**', '*', '', '', '%', 'pre', '', '', 'q'] } }); } }, isBB: { value: true } }], '4chan.org': [{ fch: { value: true }, cFileInfo: { value: 'fileText' }, cOPost: { value: 'op' }, cReply: { value: 'post reply' }, cSubj: { value: 'subject' }, qBan: { value: 'strong[style="color: red;"]' }, qDelBut: { value: '.deleteform > input[type="submit"]' }, qError: { value: '#errmsg' }, qHide: { value: '.postInfo ~ *' }, qImgLink: { value: '.fileText > a' }, qName: { value: '.name' }, qOmitted: { value: '.summary.desktop' }, qPages: { value: '.pagelist > .pages:not(.cataloglink) > a:last-of-type' }, qPostForm: { value: 'form[name="post"]' }, qPostRedir: { value: null }, qRef: { value: '.postInfo > .postNum' }, qTable: { value: '.replyContainer' }, qThumbImages: { value: '.fileThumb > img' }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 1 ? p : ''); } }, getSage: { value: function(post) { return !!$q('.id_Heaven, .useremail[href^="mailto:sage"]', post); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, getWrap: { value: function(el, isOp) { return el.parentNode; } }, anchor: { value: '#p' }, css: { value: '.backlink, .extButton, hr.desktop, .navLinks, .postMenuBtn, #togglePostFormLink { display: none !important; }\ .postForm { display: table !important; }\ textarea { margin-right: 0 !important; }' }, docExt: { value: '' }, firstPage: { value: 1 }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['**', '*', '__', '^H', 'spoiler', 'code', '', '', 'q'] }, bb: { value: [false, false, false, false, true, true, false, false, false] } }); } }, rLinkClick: { value: '' }, rep: { value: true }, res: { value: 'thread/' }, timePattern: { value: 'nn+dd+yy+w+hh+ii-?s?s?' } }], '55ch.org': [{ _55ch: { value: true }, init: { value: function() { $script('$ = function() {}'); } } }, 'form[name*="postcontrols"]'], '7chan.org': [{ init: { value: function() { return true; } } }], 'belchan.org': [{ belch: { value: true } }, 'script[src*="kusaba"]'], 'britfa.gs': [{ init: { value: function() { return true; } } }], get 'dmirrgetyojz735v.onion'() { return this['2chru.net']; }, 'dobrochan.com': [{ dobr: { value: true }, anchor: { value: '#i' }, cFileInfo: { value: 'fileinfo' }, cSubj: { value: 'replytitle' }, qDForm: { value: 'form[action*="delete"]' }, qError: { value: '.post-error, h2' }, qMsg: { value: '.postbody' }, qOmitted: { value: '.abbrev > span:first-of-type' }, qPages: { value: '.pages > tbody > tr > td' }, qPostRedir: { value: 'select[name="goto"]' }, qTrunc: { value: '.abbrev > span:nth-last-child(2)' }, getImgLink: { value: function(img) { var el = img.parentNode; if(el.tagName === 'A') { return el; } return $q('.fileinfo > a', img.previousElementSibling ? el : el.parentNode); } }, getImgWrap: { value: function(el) { return el.tagName === 'A' ? (el.previousElementSibling ? el : el.parentNode).parentNode : el.firstElementChild.tagName === 'IMG' ? el.parentNode : el; } }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 0 ? p + this.docExt : 'index.xhtml'); } }, getTNum: { value: function(op) { return $q('a[name]', op).name.match(/\d+/)[0]; } }, insertYtPlayer: { value: function(msg, playerHtml) { var prev = msg.previousElementSibling, node = prev.tagName === 'BR' ? prev : msg; node.insertAdjacentHTML('beforebegin', playerHtml); return node.previousSibling; } }, css: { value: '.delete > img, .popup, .reply_, .search_google, .search_iqdb { display: none !important; }\ .delete { background: none; }\ .delete_checkbox { position: static !important; }\ .file + .de-video-obj { float: left; margin: 5px 20px 5px 5px; }\ .de-video-obj + div { clear: left; }' }, disableRedirection: { value: function(el) { ($q(this.qPostRedir, el) || {}).selectedIndex = 1; } }, hasPicWrap: { value: true }, init: { value: function() { if(window.location.pathname === '/settings') { nav = getNavFuncs(); $q('input[type="button"]', doc).addEventListener('click', function() { readCfg(function() { saveCfg('__hanarating', $id('rating').value); }); }, false); return true; } } }, rLinkClick: { value: 'onclick="Highlight(event, this.getAttribute(\'de-num\'))"' }, ru: { value: true }, timePattern: { value: 'dd+m+?+?+?+?+?+yyyy++w++hh+ii-?s?s?' } }], get 'dobrochan.org'() { return this['dobrochan.com']; }, 'dva-ch.net': [{ dvachnet: { value: true }, }], 'ernstchan.com': [{ cOPost: { value: 'thread_OP' }, cReply: { value: 'post' }, cRPost: { value: 'thread_reply' }, qError: { value: '.error' }, qMsg: { value: '.text' }, css: { value: '.content > hr, .de-parea > hr { display: none !important }' } }, 'link[href$="phutaba.css"]'], 'hiddenchan.i2p': [{ hid: { value: true } }, 'script[src*="kusaba"]'], get 'honokakawai.com'() { return this['2--ch.ru']; }, 'iichan.hk': [{ iich: { value: true } }], 'inach.org': [{ qPostRedir: { value: 'input[name="fieldnoko"]' }, css: { value: '#postform > table > tbody > tr:first-child { display: none !important; }' }, isBB: { value: true } }], 'krautchan.net': [{ krau: { value: true }, cFileInfo: { value: 'fileinfo' }, cReply: { value: 'postreply' }, cRPost: { value: 'postreply' }, cSubj: { value: 'postsubject' }, qBan: { value: '.ban_mark' }, qDForm: { value: 'form[action*="delete"]' }, qError: { value: '.message_text' }, qHide: { value: 'div:not(.postheader)' }, qImgLink: { value: '.filename > a' }, qOmitted: { value: '.omittedinfo' }, qPages: { value: 'table[border="1"] > tbody > tr > td > a:nth-last-child(2) + a' }, qPostRedir: { value: 'input#forward_thread' }, qRef: { value: '.postnumber' }, qThread: { value: '.thread_body' }, qThumbImages: { value: 'img[id^="thumbnail_"]' }, qTrunc: { value: 'p[id^="post_truncated"]' }, getImgWrap: { value: function(el) { return el.parentNode; } }, getSage: { value: function(post) { return !!$c('sage', post); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, insertYtPlayer: { value: function(msg, playerHtml) { var pMsg = msg.parentNode, prev = pMsg.previousElementSibling, node = prev.hasAttribute('style') ? prev : pMsg; node.insertAdjacentHTML('beforebegin', playerHtml); return node.previousSibling; } }, css: { value: 'img[id^="translate_button"], img[src$="button-expand.gif"], img[src$="button-close.gif"], body > center > hr, form > div:first-of-type > hr, h2, .sage { display: none !important; }\ div[id^="Wz"] { z-index: 10000 !important; }\ .de-thr-hid { margin-bottom: ' + (!TNum ? '7' : '2') + 'px; float: none !important; }\ .file_reply + .de-video-obj, .file_thread + .de-video-obj { margin: 5px 20px 5px 5px; float: left; }\ .de-video-obj + div { clear: left; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'aa', '', '', 'q'] }, }); } }, hasPicWrap: { value: true }, init: { value: function() { doc.body.insertAdjacentHTML('beforeend', '<div style="display: none;">' + '<div onclick="window.lastUpdateTime = 0;"></div>' + '<div onclick="if(boardRequiresCaptcha) { requestCaptcha(true); }"></div>' + '<div onclick="setupProgressTracking();"></div>' + '</div>'); var els = doc.body.lastChild.children; this.btnZeroLUTime = els[0]; this.initCaptcha = els[1]; this.addProgressTrack = els[2]; } }, isBB: { value: true }, rep: { value: true }, res: { value: 'thread-' }, rLinkClick: { value: 'onclick="highlightPost(this.textContent.substr(2)))"' }, timePattern: { value: 'yyyy+nn+dd+hh+ii+ss+--?-?-?-?-?' } }], 'lambdadelta.net': [{ qHide: { value: '.de-ppanel ~ *' }, css: { value: '.content > hr { display: none !important }' } }, 'link[href$="phutaba.css"]'], 'mlpg.co': [{ getWrap: { value: function(el, isOp) { return el.parentNode; } }, css: { value: '.image-hover, form > div[style="text-align: center;"], form > div[style="text-align: center;"] + hr { display: none !important; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', '-', 'spoiler', 'c', '', '', 'q'] }, }); } }, isBB: { value: true } }, 'form[name*="postcontrols"]'], 'ponychan.net': [{ pony: { value: true }, cOPost: { value: 'op' }, qPages: { value: 'table[border="0"] > tbody > tr > td:nth-child(2) > a:last-of-type' }, css: { value: '#bodywrap3 > hr { display: none !important; }' } }, 'script[src*="kusaba"]'], 'syn-ch.ru': [{ css: { value: '.fa-sort, .image_id { display: none !important; }\ time:after { content: none; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sub', 'sup', 'q'] }, }); } }, init: { value: function() { $script('$ = function() {}'); } }, isBB: { value: true } }, 'form[name*="postcontrols"]'], get 'syn-ch.com'() { return this['syn-ch.ru']; }, get 'syn-ch.org'() { return this['syn-ch.ru']; }, 'touhouchan.org': [{ toho: { value: true }, qPostRedir: { value: 'input[name="gb2"][value="thread"]' }, css: { value: 'span[id$="_display"], #bottom_lnks { display: none !important; }' }, isBB: { value: true } }] }; var ibEngines = { '#ABU_css, #ShowLakeSettings': { abu: { value: true }, qBan: { value: 'font[color="#C12267"]' }, qDForm: { value: '#posts_form, #delform' }, qOmitted: { value: '.mess_post, .omittedposts' }, qPostRedir: { value: null }, getImgWrap: { value: function(el) { return el.parentNode.parentNode; } }, getSage: { writable: true, value: function(post) { if($c('postertripid', dForm)) { this.getSage = function(post) { return !$c('postertripid', post); }; } else { this.getSage = Object.getPrototypeOf(this).getSage; } return this.getSage(post); } }, cssEn: { value: '#ABU_alert_wait, .ABU_refmap, #captcha_div + font, #CommentToolbar, .postpanel, #usrFlds + tbody > tr:first-child, body > center { display: none !important; }\ .de-abtn { transition: none; }\ #de-txt-panel { font-size: 16px !important; }\ .reflink:before { content: none !important; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sup', 'sub', 'q'] } }); } }, init: { value: function() { var cd = $id('captcha_div'), img = cd && $t('img', cd); if(img) { cd.setAttribute('onclick', ['var el, i = 4,', 'isCustom = (typeof event.detail === "object") && event.detail.isCustom;', "if(!isCustom && event.target.tagName !== 'IMG') {", 'return;', '}', 'do {', img.getAttribute('onclick'), '} while(--i > 0 && !/<img|не нужно/i.test(this.innerHTML));', "if(el = this.getElementsByTagName('img')[0]) {", "el.removeAttribute('onclick');", "if((!isCustom || event.detail.focus) && (el = this.querySelector('input[type=\\'text\\']'))) {", 'el.focus();', '}', '}' ].join('')); img.removeAttribute('onclick'); } } }, isBB: { value: true } }, 'form[action*="futaba.php"]': { futa: { value: true }, qDForm: { value: 'form:not([enctype])' }, qImgLink: { value: 'a[href$=".jpg"], a[href$=".png"], a[href$=".gif"]' }, qOmitted: { value: 'font[color="#707070"]' }, qPostForm: { value: 'form:nth-of-type(1)' }, qPostRedir: { value: null }, qRef: { value: '.del' }, qThumbImages: { value: 'a[href$=".jpg"] > img, a[href$=".png"] > img, a[href$=".gif"] > img' }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 0 ? p + this.docExt : 'futaba.htm'); } }, getPNum: { value: function(post) { return $t('input', post).name; } }, getPostEl: { value: function(el) { while(el && el.tagName !== 'TD' && !el.hasAttribute('de-thread')) { el = el.parentElement; } return el; } }, getPosts: { value: function(thr) { return $Q('td:nth-child(2)', thr); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, cssEn: { value: '.de-cfg-body, .de-content { font-family: arial; }\ .ftbl { width: auto; margin: 0; }\ .reply { background: #f0e0d6; }\ span { font-size: inherit; }' }, docExt: { value: '.htm' } }, 'form[action*="imgboard.php?delete"]': { tinyIb: { value: true }, qPostRedir: { value: null }, ru: { value: true } }, 'form[name*="postcontrols"]': { tiny: { value: true }, cFileInfo: { value: 'fileinfo' }, cOPost: { value: 'op' }, cReply: { value: 'post reply' }, cSubj: { value: 'subject' }, cTrip: { value: 'trip' }, qDForm: { value: 'form[name="postcontrols"]' }, qHide: { value: '.intro ~ *'}, qImgLink: { value: 'p.fileinfo > a:first-of-type' }, qMsg: { value: '.body' }, qName: { value: '.name' }, qOmitted: { value: '.omitted' }, qPages: { value: '.pages > a:nth-last-of-type(2)' }, qPostForm: { value: 'form[name="post"]' }, qPostRedir: { value: null }, qRef: { value: '.post_no:nth-of-type(2)' }, qTrunc: { value: '.toolong' }, firstPage: { value: 1 }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ["'''", "''", '__', '^H', '**', '`', '', '', 'q'] }, }); } }, timePattern: { value: 'nn+dd+yy++w++hh+ii+ss' }, getPageUrl: { value: function(b, p) { return p > 1 ? fixBrd(b) + p + this.docExt : fixBrd(b); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, cssEn: { get: function() { return '.banner, .mentioned, .post-hover { display: none !important; }\ div.post.reply { float: left; clear: left; display: block; }\ form, form table { margin: 0; }'; } } }, 'script[src*="kusaba"]': { kus: { value: true }, cOPost: { value: 'postnode' }, qError: { value: 'h1, h2, div[style*="1.25em"]' }, qPostRedir: { value: null }, cssEn: { value: '.extrabtns, #newposts_get, .replymode, .ui-resizable-handle, blockquote + a { display: none !important; }\ .ui-wrapper { display: inline-block; width: auto !important; height: auto !important; padding: 0 !important; }' }, isBB: { value: true }, rLinkClick: { value: 'onclick="highlight(this.textContent.substr(2), true)"' } }, 'link[href$="phutaba.css"]': { cSubj: { value: 'subject' }, cTrip: { value: 'tripcode' }, qHide: { value: '.post > .post_body' }, qPages: { value: '.pagelist > li:nth-last-child(2)' }, qPostRedir: { value: 'input[name="gb2"][value="thread"]' }, getImgWrap: { value: function(el) { return el.parentNode.parentNode; } }, getSage: { value: function(post) { return !!$q('.sage', post); } }, docExt: { value: '' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] }, }); } }, isBB: { value: true }, res: { value: 'thread/' } } }; var ibBase = { cFileInfo: 'filesize', cOPost: 'oppost', cReply: 'reply', cRPost: 'reply', cSubj: 'filetitle', cTrip: 'postertrip', qBan: '', qDelBut: 'input[type="submit"]', qDForm: '#delform, form[name="delform"]', qError: 'h1, h2, font[size="5"]', qHide: '.de-ppanel ~ *', get qImgLink() { var val = '.' + this.cFileInfo + ' a[href$=".jpg"]:nth-of-type(1), ' + '.' + this.cFileInfo + ' a[href$=".png"]:nth-of-type(1), ' + '.' + this.cFileInfo + ' a[href$=".gif"]:nth-of-type(1), ' + '.' + this.cFileInfo + ' a[href$=".webm"]:nth-of-type(1)'; Object.defineProperty(this, 'qImgLink', { value: val }); return val; }, qMsg: 'blockquote', get qMsgImgLink() { var val = this.qMsg + ' a[href*=".jpg"], ' + this.qMsg + ' a[href*=".png"], ' + this.qMsg + ' a[href*=".gif"], ' + this.qMsg + ' a[href*=".jpeg"]'; Object.defineProperty(this, 'qMsgImgLink', { value: val }); return val; }, qName: '.postername, .commentpostername', qOmitted: '.omittedposts', qPages: 'table[border="1"] > tbody > tr > td:nth-child(2) > a:last-of-type', qPostForm: '#postform', qPostRedir: 'input[name="postredir"][value="1"]', qRef: '.reflink', qTable: 'form > table, div > table', qThumbImages: '.thumb, .de-thumb, .ca_thumb, img[src*="thumb"], img[src*="/spoiler"], img[src^="blob:"]', get qThread() { var val = $c('thread', doc) ? '.thread' : $q('div[id*="_info"][style*="float"]', doc) ? 'div[id^="t"]:not([style])' : '[id^="thread"]'; Object.defineProperty(this, 'qThread', { value: val }); return val; }, qTrunc: '.abbrev, .abbr, .shortened', getImgLink: function(img) { var el = img.parentNode; return el.tagName === 'SPAN' ? el.parentNode : el; }, getImgSize: function(info) { if(info) { var sz = info.match(/(\d+)\s?[x×]\s?(\d+)/); return [sz[1], sz[2]]; } return [-1, -1]; }, getImgWeight: function(info) { var w = info.match(/(\d+(?:[\.,]\d+)?)\s*([mkк])?i?[bб]/i); return w[2] === 'M' ? (w[1] * 1e3) | 0 : !w[2] ? Math.round(w[1] / 1e3) : w[1]; }, getImgWrap: function(el) { var node = (el.tagName === 'SPAN' ? el.parentNode : el).parentNode; return node.tagName === 'SPAN' ? node.parentNode : node; }, getOmitted: function(el, len) { var txt; return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] + 1 : 1; }, getOp: function(thr) { var el, op, opEnd; if(op = $c(this.cOPost, thr)) { return op; } op = thr.ownerDocument.createElement('div'), opEnd = $q(this.qTable + ', div[id^="repl"]', thr); while((el = thr.firstChild) !== opEnd) { op.appendChild(el); } if(thr.hasChildNodes()) { thr.insertBefore(op, thr.firstChild); } else { thr.appendChild(op); } return op; }, getPNum: function(post) { return post.id.match(/\d+/)[0]; }, getPageUrl: function(b, p) { return fixBrd(b) + (p > 0 ? p + this.docExt : ''); }, getPostEl: function(el) { while(el && !el.classList.contains(this.cRPost) && !el.hasAttribute('de-thread')) { el = el.parentElement; } return el; }, getPosts: function(thr) { return $Q('.' + this.cRPost, thr); }, getSage: function(post) { var a = $q('a[href^="mailto:"], a[href="sage"]', post); return !!a && /sage/i.test(a.href); }, getThrdUrl: function(b, tNum) { return this.prot + '//' + this.host + fixBrd(b) + this.res + tNum + this.docExt; }, getTNum: function(op) { return $q('input[type="checkbox"]', op).value; }, getWrap: function(el, isOp) { if(isOp) { return el; } if(el.tagName === 'TD') { Object.defineProperty(this, 'getWrap', { value: function(el, isOp) { return isOp ? el : getAncestor(el, 'TABLE'); }}); } else { Object.defineProperty(this, 'getWrap', { value: function(el, isOp) { return el; }}); } return this.getWrap(el, isOp); }, insertYtPlayer: function(msg, playerHtml) { msg.insertAdjacentHTML('beforebegin', playerHtml); return msg.previousSibling; }, anchor: '#', css: '', cssEn: '', disableRedirection: function(el) { if(this.qPostRedir) { ($q(this.qPostRedir, el) || {}).checked = true; } }, dm: '', docExt: '.html', firstPage: 0, get _formButtons() { var bb = this.isBB; return { id: ['bold', 'italic', 'under', 'strike', 'spoil', 'code', 'sup', 'sub', 'quote'], val: ['B', 'i', 'U', 'S', '%', 'C', 'v', '^', '&gt;'], tag: bb ? ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] : ['**', '*', '', '^H', '%%', '`', '', '', 'q'], bb: [bb, bb, bb, bb, bb, bb, bb, bb, bb] }; }, get formButtons() { return this._formButtons; }, hasPicWrap: false, host: window.location.hostname, init: null, isBB: false, get lastPage() { var el = $q(this.qPages, doc), val = el && +aProto.pop.call(el.textContent.match(/\d+/g) || []) || 0; if(pageNum === val + 1) { val++; } Object.defineProperty(this, 'lastPage', { value: val }); return val; }, prot: window.location.protocol, get reCrossLinks() { var val = new RegExp('>https?:\\/\\/[^\\/]*' + this.dm + '\\/([a-z0-9]+)\\/' + regQuote(this.res) + '(\\d+)(?:[^#<]+)?(?:#i?(\\d+))?<', 'g'); Object.defineProperty(this, 'reCrossLinks', { value: val }); return val; }, get rep() { var val = dTime || spells.haveReps || Cfg['crossLinks']; Object.defineProperty(this, 'rep', { value: val }); return val; }, res: 'res/', rLinkClick: 'onclick="highlight(this.textContent.substr(2))"', ru: false, timePattern: 'w+dd+m+yyyy+hh+ii+ss' }; var i, ibObj = null, dm = window.location.hostname .match(/(?:(?:[^.]+\.)(?=org\.|net\.|com\.))?[^.]+\.[^.]+$|^\d+\.\d+\.\d+\.\d+$|localhost/)[0]; if(checkDomains) { if(dm in ibDomains) { ibObj = (function createBoard(info) { return Object.create( info[2] ? createBoard(ibDomains[info[2]]) : info[1] ? Object.create(ibBase, ibEngines[info[1]]) : ibBase, info[0] ); })(ibDomains[dm]); checkOther = false; } } if(checkOther) { for(i in ibEngines) { if($q(i, doc)) { ibObj = Object.create(ibBase, ibEngines[i]); break; } } if(!ibObj) { ibObj = ibBase; } } if(ibObj) { ibObj.dm = dm; } return ibObj; }; //============================================================================================================ // BROWSER //============================================================================================================ function getNavFuncs() { if(!('contains' in String.prototype)) { String.prototype.contains = function(s) { return this.indexOf(s) !== -1; }; String.prototype.startsWith = function(s) { return this.indexOf(s) === 0; }; } if(!('repeat' in String.prototype)) { String.prototype.repeat = function(nTimes) { return new Array(nTimes + 1).join(this.valueOf()); }; } if(!('clz32' in Math)) { Math.clz32 = function(x) { return x < 1 ? x === 0 ? 32 : 0 : 31 - ((Math.log(x) / Math.LN2) >> 0); }; } if('toJSON' in aProto) { delete aProto.toJSON; } if(!('URL' in window)) { window.URL = window.webkitURL; } var ua = window.navigator.userAgent, presto = window.opera ? +window.opera.version() : 0, opera11 = presto ? presto < 12.1 : false, webkit = ua.contains('WebKit/'), chrome = webkit && ua.contains('Chrome/'), safari = webkit && !chrome, isGM = typeof GM_setValue === 'function' && (!chrome || !GM_setValue.toString().contains('not supported')), isChromeStorage = window.chrome && !!window.chrome.storage, isScriptStorage = !!scriptStorage && !ua.contains('Opera Mobi'); if(!window.GM_xmlhttpRequest) { window.GM_xmlhttpRequest = $xhr; } return { get ua() { return navigator.userAgent + (this.Firefox ? ' [' + navigator.buildID + ']' : ''); }, Firefox: ua.contains('Gecko/'), Opera11: opera11, Presto: presto, WebKit: webkit, Chrome: chrome, Safari: safari, isGM: isGM, isChromeStorage: isChromeStorage, isScriptStorage: isScriptStorage, isGlobal: isGM || isChromeStorage || isScriptStorage, cssFix: webkit ? '-webkit-' : opera11 ? '-o-' : '', Anim: !opera11, animName: webkit ? 'webkitAnimationName' : opera11 ? 'OAnimationName' : 'animationName', animEnd: webkit ? 'webkitAnimationEnd' : opera11 ? 'oAnimationEnd' : 'animationend', animEvent: function(el, Fn) { el.addEventListener(this.animEnd, function aEvent() { this.removeEventListener(nav.animEnd, aEvent, false); Fn(this); Fn = null; }, false); }, fixLink: safari ? getAbsLink : function fixLink(url) { return url; }, get hasWorker() { var val = 'Worker' in (this.Firefox ? unsafeWindow : Window); Object.defineProperty(this, 'hasWorker', { value: val }); return val; }, get canPlayMP3() { var val = !!new Audio().canPlayType('audio/mp3; codecs="mp3"'); Object.defineProperty(this, 'canPlayMP3', { value: val }); return val; }, get canPlayWebm() { var val = !!new Audio().canPlayType('video/webm; codecs="vp8,vorbis"'); Object.defineProperty(this, 'canPlayWebm', { value: val }); return val; }, get matchesSelector() { var dE = doc.documentElement, fun = dE.matchesSelector || dE.mozMatchesSelector || dE.webkitMatchesSelector || dE.oMatchesSelector, val = Function.prototype.call.bind(fun); Object.defineProperty(this, 'matchesSelector', { value: val }); return val; } }; } //============================================================================================================ // INITIALIZATION //============================================================================================================ function Initialization(checkDomains) { if(/^(?:about|chrome|opera|res)/i.test(window.location)) { return false; } try { locStorage = window.localStorage; sesStorage = window.sessionStorage; sesStorage['__de-test'] = 1; } catch(e) { if(typeof unsafeWindow !== 'undefined') { locStorage = unsafeWindow.localStorage; sesStorage = unsafeWindow.sessionStorage; } } if(!(locStorage && typeof locStorage === 'object' && sesStorage)) { GM_log('WEBSTORAGE ERROR: please, enable webstorage!'); return false; } var intrv, url; switch(window.name) { case '': break; case 'de-iframe-pform': case 'de-iframe-dform': $script('window.top.postMessage("A' + window.name + '" + document.documentElement.outerHTML, "*");'); return false; case 'de-iframe-fav': intrv = setInterval(function() { $script('window.top.postMessage("B' + (doc.body.offsetHeight + 5) + '", "*");'); }, 1500); window.addEventListener('load', setTimeout.bind(window, clearInterval, 3e4, intrv), false); liteMode = true; pr = {}; } if(!aib) { aib = getImageBoard(checkDomains, true); } if(aib.init && aib.init()) { return false; } dForm = $q(aib.qDForm, doc); if(!dForm || $id('de-panel')) { return false; } nav = getNavFuncs(); window.addEventListener('storage', function(e) { var data, temp, post, val = e.newValue; if(!val) { return; } switch(e.key) { case '__de-post': { try { data = JSON.parse(val); } catch(e) { return; } temp = data['hide']; if(data['brd'] === brd && (post = pByNum[data['num']]) && (post.hidden ^ temp)) { post.setUserVisib(temp, data['date'], false); } else { if(!(data['brd'] in bUVis)) { bUVis[data['brd']] = {}; } bUVis[data['brd']][data['num']] = [+!temp, data['date']]; } if(data['isOp']) { if(!(data['brd'] in hThr)) { if(temp) { hThr[data['brd']] = {}; } else { break; } } if(temp) { hThr[data['brd']][data['num']] = data['title']; } else { delete hThr[data['brd']][data['num']]; } } break; } case '__de-threads': { try { hThr = JSON.parse(val); } catch(e) { return; } if(!(brd in hThr)) { hThr[brd] = {}; } firstThr.updateHidden(hThr[brd]); break; } case '__de-spells': { try { data = JSON.parse(val); } catch(e) { return; } Cfg['hideBySpell'] = data['hide']; if(temp = $q('input[info="hideBySpell"]', doc)) { temp.checked = data['hide']; } doc.body.style.display = 'none'; disableSpells(); if(data['data']) { spells.setSpells(data['data'], false); if(temp = $id('de-spell-edit')) { temp.value = spells.list; } } else { if(data['data'] === '') { spells.disable(); if(temp = $id('de-spell-edit')) { temp.value = ''; } saveCfg('spells', ''); } spells.enable = false; } doc.body.style.display = ''; } default: return; } toggleContent('hid', true); }, false); url = (window.location.pathname || '').match(new RegExp( '^(?:\\/?([^\\.]*?(?:\\/[^\\/]*?)?)\\/?)?' + '(' + regQuote(aib.res) + ')?' + '(\\d+|index|wakaba|futaba)?' + '(\\.(?:[a-z]+))?(?:\\/|$)' )); brd = url[1].replace(/\/$/, ''); TNum = url[2] ? url[3] : aib.futa ? +(window.location.search.match(/\d+/) || [false])[0] : false; pageNum = url[3] && !TNum ? +url[3] || aib.firstPage : aib.firstPage; if(!aib.hasOwnProperty('docExt') && url[4]) { aib.docExt = url[4]; } dummy = doc.createElement('div'); return true; } function parseThreadNodes(form, threads) { var el, i, len, node, fNodes = aProto.slice.call(form.childNodes), cThr = doc.createElement('div'); for(i = 0, len = fNodes.length - 1; i < len; ++i) { node = fNodes[i]; if(node.tagName === 'HR') { form.insertBefore(cThr, node); form.insertBefore(cThr.lastElementChild, node); el = cThr.lastElementChild; if(el.tagName === 'BR') { form.insertBefore(el, node); } threads.push(cThr); cThr = doc.createElement('div'); } else { cThr.appendChild(node); } } cThr.appendChild(fNodes[i]); form.appendChild(cThr); return threads; } function parseDelform(node, thrds) { var i, lThr, len = thrds.length; $each($T('script', node), $del); if(len === 0) { Thread.parsed = true; thrds = parseThreadNodes(dForm, []); len = thrds.length; } if(len) { firstThr = lThr = new Thread(thrds[0], null); } for(i = 1; i < len; i++) { lThr = new Thread(thrds[i], lThr); } lastThr = lThr; node.setAttribute('de-form', ''); node.removeAttribute('id'); if(aib.abu && TNum) { lThr = firstThr.el; while((node = lThr.nextSibling) && node.tagName !== 'HR') { $del(node); } } } function replaceString(txt) { if(dTime) { txt = dTime.fix(txt); } if(aib.fch || aib.krau) { if(aib.fch) { txt = txt.replace(/(?:<span>)?([^\s<>]+)<wbr>([^\s<>]+)(?:<\/span>)?/g, '$1$2'); } txt = txt.replace(/(^|>|\s|&gt;)(https*:\/\/.*?)(<\/a>)?(?=$|<|\s)/ig, function(x, a, b, c) { return c ? x : a + '<a href="' + b + '">' + b + '</a>'; }); } if(spells.haveReps) { txt = spells.replace(txt); } if(Cfg['crossLinks']) { txt = txt.replace(aib.reCrossLinks, function(str, b, tNum, pNum) { return '>&gt;&gt;/' + b + '/' + (pNum || tNum) + '<'; }); } return txt; } function replacePost(el) { if(aib.rep) { el.innerHTML = replaceString(el.innerHTML); } return el; } function replaceDelform() { if(liteMode) { doc.body.insertAdjacentHTML('afterbegin', dForm.outerHTML); dForm = doc.body.firstChild; window.addEventListener('load', function() { while(dForm.nextSibling) { $del(dForm.nextSibling); } }, false); } else if(aib.rep) { dForm.insertAdjacentHTML('beforebegin', replaceString(dForm.outerHTML)); dForm.style.display = 'none'; dForm.id = 'de-dform-old'; dForm = dForm.previousSibling; window.addEventListener('load', function() { $del($id('de-dform-old')); }, false); } } function initDelformAjax() { var btn; if(Cfg['ajaxReply'] === 2) { dForm.onsubmit = $pd; if(btn = $q(aib.qDelBut, dForm)) { btn.onclick = function(e) { $pd(e); pr.closeQReply(); $alert(Lng.deleting[lang], 'deleting', true); new html5Submit(dForm, e.target, checkDelete); }; } } else if(Cfg['ajaxReply'] === 1) { dForm.insertAdjacentHTML('beforeend', '<iframe name="de-iframe-pform" src="about:blank" style="display: none;"></iframe>' + '<iframe name="de-iframe-dform" src="about:blank" style="display: none;"></iframe>' ); dForm.target = 'de-iframe-dform'; dForm.onsubmit = function() { pr.closeQReply(); $alert(Lng.deleting[lang], 'deleting', true); }; } } function initThreadUpdater(title, enableUpdate) { var focused, delay, checked404, loadTO, audioRep, currentXHR, audioEl, stateButton, hasAudio, initDelay, favIntrv, favNorm, favHref, notifGranted, enabled = false, disabledByUser = true, inited = false, lastECode = 200, sendError = false, newPosts = 0, aPlayers = 0; if(('hidden' in doc) || ('webkitHidden' in doc)) { focused = !(doc.hidden || doc.webkitHidden); doc.addEventListener((nav.WebKit ? 'webkit' : '') + 'visibilitychange', function() { if(doc.hidden || doc.webkitHidden) { focused = false; firstThr && firstThr.clearPostsMarks(); } else { onVis(); } }, false); } else { focused = false; window.addEventListener('focus', onVis, false); window.addEventListener('blur', function() { focused = false; firstThr.clearPostsMarks(); }, false); window.addEventListener('mousemove', function mouseMove() { window.removeEventListener('mousemove', mouseMove, false); onVis(); }, false); } if(enableUpdate) { init(); } if(focused && Cfg['desktNotif'] && ('permission' in Notification)) { switch(Notification.permission.toLowerCase()) { case 'default': requestNotifPermission(); break; case 'denied': saveCfg('desktNotif', 0); } } function init() { audioEl = null; stateButton = null; hasAudio = false; initDelay = Cfg['updThrDelay'] * 1e3; favIntrv = 0; favNorm = notifGranted = inited = true; favHref = ($q('head link[rel="shortcut icon"]', doc) || {}).href; enable(true); } function enable(startLoading) { enabled = true; checked404 = false; newPosts = 0; delay = initDelay; if(startLoading) { loadTO = setTimeout(loadPostsFun, delay); } } function disable(byUser) { disabledByUser = byUser; if(enabled) { clearTimeout(loadTO); enabled = hasAudio = false; setState('off'); var btn = $id('de-btn-audio-on'); if(btn) { btn.id = 'de-btn-audio-off'; } } } function toggleAudio(aRep) { if(!audioEl) { audioEl = $new('audio', { 'preload': 'auto', 'src': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/signal.ogg' }, null); } audioRep = aRep; return hasAudio = !hasAudio; } function audioNotif() { if(focused) { hasAudio = false; } else { audioEl.play() setTimeout(audioNotif, audioRep); hasAudio = true; } } function requestNotifPermission() { notifGranted = false; Notification.requestPermission(function(state) { if(state.toLowerCase() === 'denied') { saveCfg('desktNotif', 0); } else { notifGranted = true; } }); } function loadPostsFun() { currentXHR = firstThr.loadNew(onLoaded, true); } function forceLoadPosts() { if(currentXHR) { currentXHR.abort(); } if(!enabled && !disabledByUser) { enable(false); } else { clearTimeout(loadTO); delay = initDelay; } loadPostsFun(); } function onLoaded(eCode, eMsg, lPosts, xhr) { if(currentXHR !== xhr && eCode === 0) { // Loading aborted return; } currentXHR = null; infoLoadErrors(eCode, eMsg, -1); if(eCode !== 200 && eCode !== 304) { lastECode = eCode; if(!Cfg['noErrInTitle']) { updateTitle(); } if(eCode !== 0 && Math.floor(eCode / 500) === 0) { if(eCode === 404 && !checked404) { checked404 = true; } else { updateTitle(); disable(false); return; } } setState('warn'); if(enabled) { loadTO = setTimeout(loadPostsFun, delay); } return; } if(lastECode !== 200) { lastECode = 200; setState('on'); checked404 = false; if((focused || lPosts === 0) && !Cfg['noErrInTitle']) { updateTitle(); } } if(!focused) { if(lPosts !== 0) { if(Cfg['favIcoBlink'] && favHref && newPosts === 0) { favIntrv = setInterval(function() { $del($q('link[rel="shortcut icon"]', doc.head)); doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' + (!favNorm ? favHref : 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAA' + 'AQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVR' + 'Ix2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII=') + '">'); favNorm = !favNorm; }, 800); } newPosts += lPosts; updateTitle(); if(Cfg['desktNotif'] && notifGranted) { var post = firstThr.last, imgs = post.images, notif = new Notification(aib.dm + '/' + brd + '/' + TNum + ': ' + newPosts + Lng.newPost[lang][lang !== 0 ? +(newPosts !== 1) : (newPosts % 10) > 4 || (newPosts % 10) === 0 || (((newPosts % 100) / 10) | 0) === 1 ? 2 : (newPosts % 10) === 1 ? 0 : 1] + Lng.newPost[lang][3], { 'body': post.text.substring(0, 250).replace(/\s+/g, ' '), 'tag': aib.dm + brd + TNum, 'icon': imgs.length === 0 ? favHref : imgs[0].src }); notif.onshow = function() { setTimeout(this.close.bind(this), 12e3); }; notif.onclick = function() { window.focus(); }; notif.onerror = function() { window.focus(); requestNotifPermission(); }; } if(hasAudio) { if(audioRep) { audioNotif(); } else { audioEl.play() } } delay = initDelay; } else if(delay !== 12e4) { delay = Math.min(delay + initDelay, 12e4); } } if(enabled) { loadTO = setTimeout(loadPostsFun, delay); } } function setState(state) { var btn = stateButton || (stateButton = $q('a[id^="de-btn-upd"]', doc)); btn.id = 'de-btn-upd-' + state; btn.title = Lng.panelBtn['upd-' + (state === 'off' ? 'off' : 'on')][lang]; } function onVis() { if(Cfg['favIcoBlink'] && favHref) { clearInterval(favIntrv); favNorm = true; $del($q('link[rel="shortcut icon"]', doc.head)); doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' + favHref + '">'); } newPosts = 0; focused = true; sendError = false; setTimeout(function() { updateTitle(); if(enabled) { forceLoadPosts(); } }, 200); } function updateTitle() { doc.title = (aPlayers === 0 ? '' : '♫ ') + (sendError === true ? '{' + Lng.error[lang] + '} ' : '') + (lastECode === 200 ? '' : '{' + lastECode + '} ') + (newPosts === 0 ? '' : '[' + newPosts + '] ') + title; } function addPlayingTag() { aPlayers++; if(aPlayers === 1) { updateTitle(); } } function removePlayingTag() { aPlayers = Math.max(aPlayers - 1, 0); if(aPlayers === 0) { updateTitle(); } } function sendErrNotif() { if(Cfg['sendErrNotif'] && !focused) { sendError = true; updateTitle(); } } return { get enabled() { return enabled; }, get focused() { return focused; }, forceLoad: forceLoadPosts, enable: function() { if(!inited) { init(); } else if(!enabled) { enable(true); } else { return; } setState('on'); }, disable: function() { disable(true); }, updateXHR: function(newXHR) { currentXHR = newXHR; }, toggleAudio: toggleAudio, addPlayingTag: addPlayingTag, removePlayingTag: removePlayingTag, sendErrNotif: sendErrNotif }; } function initPage() { if(Cfg['updScript']) { checkForUpdates(false, function(html) { $alert(html, 'updavail', false); }); } if(TNum) { if(Cfg['rePageTitle']) { if(aib.abu) { window.addEventListener('load', function() { doc.title = '/' + brd + ' - ' + firstThr.op.title; }, false); } doc.title = '/' + brd + ' - ' + firstThr.op.title; } firstThr.el.insertAdjacentHTML('afterend', '<div id="de-updater-div">&gt;&gt; [<a class="de-abtn" id="de-updater-btn" href="#"></a>]</div>'); firstThr.el.nextSibling.addEventListener('click', Thread.loadNewPosts, false); } else if(needScroll) { setTimeout(window.scrollTo, 20, 0, 0); } updater = initThreadUpdater(doc.title, TNum && Cfg['ajaxUpdThr']); } //============================================================================================================ // MAIN //============================================================================================================ function addDelformStuff(isLog) { preloadImages(null); isLog && new Logger().log('Preload images'); embedMP3Links(null); isLog && new Logger().log('MP3 links'); new YouTube().parseLinks(null); isLog && new Logger().log('YouTube links'); if(Cfg['addImgs']) { embedImagesLinks(dForm); isLog && new Logger().log('Image links'); } if(Cfg['imgSrcBtns']) { addImagesSearch(dForm); isLog && new Logger().log('Sauce buttons'); } if(firstThr && Cfg['linksNavig'] === 2) { genRefMap(pByNum, ''); for(var post = firstThr.op; post; post = post.next) { if(post.hasRef) { addRefMap(post, ''); } } isLog && new Logger().log('Reflinks map'); } } function initScript(checkDomains) { new Logger().init(); if(!Initialization(checkDomains)) { return; } new Logger().log('Init'); readCfg(doScript); } function doScript() { new Logger().log('Config loading'); if(Cfg['disabled']) { addPanel(); scriptCSS(); return; } spells = new Spells(!!Cfg['hideBySpell']); new Logger().log('Parsing spells'); doc.body.style.display = 'none'; replaceDelform(); new Logger().log('Replace delform'); pr = new PostForm($q(aib.qPostForm, doc), false, !liteMode, doc); pByNum = Object.create(null); try { parseDelform(dForm, $Q(aib.qThread, dForm)); } catch(e) { GM_log('DELFORM ERROR:\n' + getPrettyErrorMessage(e)); doc.body.style.display = ''; return; } initDelformAjax(); readViewedPosts(); new Logger().log('Parse delform'); if(Cfg['keybNavig']) { keyNav = new KeyNavigation(); new Logger().log('Init keybinds'); } if(!liteMode) { initPage(); new Logger().log('Init page'); addPanel(); new Logger().log('Add panel'); } initMessageFunctions(); addDelformStuff(true); scriptCSS(); doc.body.style.display = ''; new Logger().log('Apply CSS'); readPosts(); readUserPosts(); readFavoritesPosts(); new Logger().log('Apply spells'); new Logger().finish(); } if(doc.readyState === 'interactive' || doc.readyState === 'complete') { needScroll = false; initScript(true); } else { aib = getImageBoard(true, false); needScroll = true; doc.addEventListener(doc.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll", function wheelFunc(e) { needScroll = false; doc.removeEventListener(e.type, wheelFunc, false); }, false); doc.addEventListener('DOMContentLoaded', initScript.bind(null, false), false); } })(window.opera && window.opera.scriptStorage);
Dollchan_Extension_Tools.user.js
// ==UserScript== // @name Dollchan Extension Tools // @version 14.7.25.0 // @namespace http://www.freedollchan.org/scripts/* // @author Sthephan Shinkufag @ FreeDollChan // @copyright (C)2084, Bender Bending Rodriguez // @description Doing some profit for imageboards // @icon https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Icon.png // @updateURL https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js // @run-at document-start // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_openInTab // @grant GM_xmlhttpRequest // @grant GM_log // @grant unsafeWindow // @include * // ==/UserScript== (function de_main_func(scriptStorage) { 'use strict'; var version = '14.7.25.0', defaultCfg = { 'disabled': 0, // script enabled by default 'language': 0, // script language [0=ru, 1=en] 'hideBySpell': 1, // hide posts by spells 'spells': '', // user defined spells 'sortSpells': 0, // sort spells when applying 'menuHiddBtn': 1, // menu on hide button 'hideRefPsts': 0, // hide post with references to hidden posts 'delHiddPost': 0, // delete hidden posts 'ajaxUpdThr': 1, // auto update threads 'updThrDelay': 60, // threads update interval in sec 'noErrInTitle': 0, // don't show error number in title except 404 'favIcoBlink': 0, // favicon blinking, if new posts detected 'markNewPosts': 1, // new posts marking on page focus 'desktNotif': 0, // desktop notifications, if new posts detected 'expandPosts': 2, // expand shorted posts [0=off, 1=auto, 2=on click] 'postBtnsCSS': 2, // post buttons style [0=text, 1=classic, 2=solid grey] 'noSpoilers': 1, // open spoilers 'noPostNames': 0, // hide post names 'noPostScrl': 1, // no scroll in posts 'correctTime': 0, // correct time in posts 'timeOffset': '+0', // offset in hours 'timePattern': '', // find pattern 'timeRPattern': '', // replace pattern 'expandImgs': 2, // expand images by click [0=off, 1=in post, 2=by center] 'resizeImgs': 1, // resize large images 'webmControl': 1, // control bar fow webm files 'webmVolume': 100, // default volume for webm files 'maskImgs': 0, // mask images 'preLoadImgs': 0, // pre-load images 'findImgFile': 0, // detect built-in files in images 'openImgs': 0, // open images in posts 'openGIFs': 0, // open only GIFs in posts 'imgSrcBtns': 1, // add image search buttons 'linksNavig': 2, // navigation by >>links [0=off, 1=no map, 2=+refmap] 'linksOver': 100, // delay appearance in ms 'linksOut': 1500, // delay disappearance in ms 'markViewed': 0, // mark viewed posts 'strikeHidd': 0, // strike >>links to hidden posts 'noNavigHidd': 0, // don't show previews for hidden posts 'crossLinks': 0, // replace http: to >>/b/links 'insertNum': 1, // insert >>link on postnumber click 'addMP3': 1, // embed mp3 links 'addImgs': 0, // embed links to images 'addYouTube': 3, // embed YouTube links [0=off, 1=onclick, 2=player, 3=preview+player, 4=only preview] 'YTubeType': 0, // player type [0=flash, 1=HTML5] 'YTubeWidth': 360, // player width 'YTubeHeigh': 270, // player height 'YTubeHD': 0, // hd video quality 'YTubeTitles': 0, // convert links to titles 'addVimeo': 1, // embed vimeo links 'ajaxReply': 2, // posting with AJAX (0=no, 1=iframe, 2=HTML5) 'postSameImg': 1, // ability to post same images 'removeEXIF': 1, // remove EXIF data from JPEGs 'removeFName': 0, // remove file name 'sendErrNotif': 1, // inform about post send error if page is blurred 'scrAfterRep': 0, // scroll to the bottom after reply 'addPostForm': 2, // postform displayed [0=at top, 1=at bottom, 2=hidden, 3=hanging] 'favOnReply': 1, // add thread to favorites on reply 'warnSubjTrip': 0, // warn if subject field contains tripcode 'fileThumb': 1, // file preview area instead of file button 'addSageBtn': 1, // email field -> sage button 'saveSage': 1, // remember sage 'sageReply': 0, // reply with sage 'captchaLang': 1, // language input in captcha [0=off, 1=en, 2=ru] 'addTextBtns': 1, // text format buttons [0=off, 1=graphics, 2=text, 3=usual] 'txtBtnsLoc': 0, // located at [0=top, 1=bottom] 'passwValue': '', // user password value 'userName': 0, // user name 'nameValue': '', // value 'noBoardRule': 1, // hide board rules 'noGoto': 1, // hide goto field 'noPassword': 1, // hide password field 'scriptStyle': 0, // script style [0=glass black, 1=glass blue, 2=solid grey] 'userCSS': 0, // user style 'userCSSTxt': '', // css text 'expandPanel': 0, // show full main panel 'attachPanel': 1, // attach main panel 'panelCounter': 1, // posts/images counter in script panel 'rePageTitle': 1, // replace page title in threads 'animation': 1, // CSS3 animation in script 'closePopups': 0, // auto-close popups 'keybNavig': 1, // keyboard navigation 'loadPages': 1, // number of pages that are loaded on F5 'updScript': 1, // check for script's update 'scrUpdIntrv': 1, // check interval in days (every val+1 day) 'turnOff': 0, // enable script only for this site 'textaWidth': 500, // textarea width 'textaHeight': 160 // textarea height }, Lng = { cfg: { 'hideBySpell': ['Заклинания: ', 'Magic spells: '], 'sortSpells': ['Сортировать спеллы и удалять дубликаты', 'Sort spells and delete duplicates'], 'menuHiddBtn': ['Дополнительное меню кнопок скрытия ', 'Additional menu of hide buttons'], 'hideRefPsts': ['Скрывать ответы на скрытые посты*', 'Hide replies to hidden posts*'], 'delHiddPost': ['Удалять скрытые посты', 'Delete hidden posts'], 'ajaxUpdThr': ['AJAX обновление треда ', 'AJAX thread update '], 'updThrDelay': [' (сек)', ' (sec)'], 'noErrInTitle': ['Не показывать номер ошибки в заголовке', 'Don\'t show error number in title'], 'favIcoBlink': ['Мигать фавиконом при новых постах', 'Favicon blinking on new posts'], 'markNewPosts': ['Выделять новые посты при переключении на тред', 'Mark new posts on page focus'], 'desktNotif': ['Уведомления на рабочем столе', 'Desktop notifications'], 'expandPosts': { sel: [['Откл.', 'Авто', 'По клику'], ['Disable', 'Auto', 'On click']], txt: ['AJAX загрузка сокращенных постов*', 'AJAX upload of shorted posts*'] }, 'postBtnsCSS': { sel: [['Text', 'Classic', 'Solid grey'], ['Text', 'Classic', 'Solid grey']], txt: ['Стиль кнопок постов*', 'Post buttons style*'] }, 'noSpoilers': ['Открывать текстовые спойлеры', 'Open text spoilers'], 'noPostNames': ['Скрывать имена в постах', 'Hide names in posts'], 'noPostScrl': ['Без скролла в постах', 'No scroll in posts'], 'keybNavig': ['Навигация с помощью клавиатуры ', 'Navigation with keyboard '], 'loadPages': [' Количество страниц, загружаемых по F5', ' Number of pages that are loaded on F5 '], 'correctTime': ['Корректировать время в постах* ', 'Correct time in posts* '], 'timeOffset': [' Разница во времени', ' Time difference'], 'timePattern': [' Шаблон поиска', ' Find pattern'], 'timeRPattern': [' Шаблон замены', ' Replace pattern'], 'expandImgs': { sel: [['Откл.', 'В посте', 'По центру'], ['Disable', 'In post', 'By center']], txt: ['раскрывать изображения по клику', 'expand images on click'] }, 'resizeImgs': ['Уменьшать в экран большие изображения', 'Resize large images to fit screen'], 'webmControl': ['Показывать контрол-бар для webm-файлов', 'Show control bar for webm files'], 'webmVolume': [' Громкость webm-файлов [0-100]', ' Default volume for webm files [0-100]'], 'preLoadImgs': ['Предварительно загружать изображения*', 'Pre-load images*'], 'findImgFile': ['Распознавать встроенные файлы в изображениях*', 'Detect built-in files in images*'], 'openImgs': ['Скачивать полные версии изображений*', 'Download full version of images*'], 'openGIFs': ['Скачивать только GIFы*', 'Download GIFs only*'], 'imgSrcBtns': ['Добавлять кнопки для поиска изображений*', 'Add image search buttons*'], 'linksNavig': { sel: [['Откл.', 'Без карты', 'С картой'], ['Disable', 'No map', 'With map']], txt: ['навигация по >>ссылкам* ', 'navigation by >>links* '] }, 'linksOver': [' задержка появления (мс)', ' delay appearance (ms)'], 'linksOut': [' задержка пропадания (мс)', ' delay disappearance (ms)'], 'markViewed': ['Отмечать просмотренные посты*', 'Mark viewed posts*'], 'strikeHidd': ['Зачеркивать >>ссылки на скрытые посты', 'Strike >>links to hidden posts'], 'noNavigHidd': ['Не отображать превью для скрытых постов', 'Don\'t show previews for hidden posts'], 'crossLinks': ['Преобразовывать http:// в >>/b/ссылки*', 'Replace http:// with >>/b/links*'], 'insertNum': ['Вставлять >>ссылку по клику на №поста*', 'Insert >>link on №postnumber click*'], 'addMP3': ['Добавлять плейер к mp3 ссылкам* ', 'Add player to mp3 links* '], 'addVimeo': ['Добавлять плейер к Vimeo ссылкам* ', 'Add player to Vimeo links* '], 'addImgs': ['Загружать изображения к jpg, png, gif ссылкам*', 'Load images to jpg, png, gif links*'], 'addYouTube': { sel: [['Ничего', 'Плейер по клику', 'Авто плейер', 'Превью+плейер', 'Только превью'], ['Nothing', 'On click player', 'Auto player', 'Preview+player', 'Only preview']], txt: ['к YouTube-ссылкам* ', 'to YouTube-links* '] }, 'YTubeType': { sel: [['Flash', 'HTML5'], ['Flash', 'HTML5']], txt: ['', ''] }, 'YTubeHD': ['HD ', 'HD '], 'YTubeTitles': ['Загружать названия к YouTube-ссылкам*', 'Load titles into YouTube-links*'], 'ajaxReply': { sel: [['Откл.', 'Iframe', 'HTML5'], ['Disable', 'Iframe', 'HTML5']], txt: ['AJAX отправка постов*', 'posting with AJAX*'] }, 'postSameImg': ['Возможность отправки одинаковых изображений', 'Ability to post same images'], 'removeEXIF': ['Удалять EXIF из JPEG ', 'Remove EXIF from JPEG '], 'removeFName': ['Удалять имя из файлов', 'Remove names from files'], 'sendErrNotif': ['Оповещать в заголовке об ошибке отправки поста', 'Inform in title about post send error'], 'scrAfterRep': ['Перемещаться в конец треда после отправки', 'Scroll to the bottom after reply'], 'addPostForm': { sel: [['Сверху', 'Внизу', 'Скрытая', 'Отдельная'], ['At top', 'At bottom', 'Hidden', 'Hanging']], txt: ['форма ответа в треде* ', 'reply form in thread* '] }, 'favOnReply': ['Добавлять тред в избранное при ответе', 'Add thread to favorites on reply'], 'warnSubjTrip': ['Предупреждать при наличии трип-кода в поле "Тема"', 'Warn if "Subject" field contains trip-code'], 'fileThumb': ['Область превью картинок вместо кнопки "Файл"', 'File thumbnail area instead of "File" button'], 'addSageBtn': ['Кнопка Sage вместо поля "E-mail"* ', 'Sage button instead of "E-mail" field* '], 'saveSage': ['запоминать сажу', 'remember sage'], 'captchaLang': { sel: [['Откл.', 'Eng', 'Rus'], ['Disable', 'Eng', 'Rus']], txt: ['язык ввода капчи', 'language input in captcha'] }, 'addTextBtns': { sel: [['Откл.', 'Графич.', 'Упрощ.', 'Стандарт.'], ['Disable', 'As images', 'As text', 'Standard']], txt: ['кнопки форматирования текста ', 'text format buttons '] }, 'txtBtnsLoc': ['внизу', 'at bottom'], 'userPassw': [' Постоянный пароль ', ' Fixed password '], 'userName': ['Постоянное имя', 'Fixed name'], 'noBoardRule': ['правила', 'rules'], 'noGoto': ['поле goto', 'goto field'], 'noPassword': ['пароль', 'password'], 'scriptStyle': { sel: [['Glass black', 'Glass blue', 'Solid grey'], ['Glass black', 'Glass blue', 'Solid grey']], txt: ['стиль скрипта', 'script style'] }, 'userCSS': ['Пользовательский CSS ', 'User CSS '], 'attachPanel': ['Прикрепить главную панель', 'Attach main panel'], 'panelCounter': ['Счетчик постов/изображений на главной панели', 'Counter of posts/images on main panel'], 'rePageTitle': ['Название треда в заголовке вкладки*', 'Thread title in page tab*'], 'animation': ['CSS3 анимация в скрипте', 'CSS3 animation in script'], 'closePopups': ['Автоматически закрывать уведомления', 'Close popups automatically'], 'updScript': ['Автоматически проверять обновления скрипта', 'Check for script update automatically'], 'turnOff': ['Включать скрипт только на этом сайте', 'Enable script only on this site'], 'scrUpdIntrv': { sel: [['Каждый день', 'Каждые 2 дня', 'Каждую неделю', 'Каждые 2 недели', 'Каждый месяц'], ['Every day', 'Every 2 days', 'Every week', 'Every 2 week', 'Every month']], txt: ['', ''] }, 'language': { sel: [['Ru', 'En'], ['Ru', 'En']], txt: ['', ''] } }, txtBtn: [ ['Жирный', 'Bold'], ['Наклонный', 'Italic'], ['Подчеркнутый', 'Underlined'], ['Зачеркнутый', 'Strike'], ['Спойлер', 'Spoiler'], ['Код', 'Code'], ['Верхний индекс', 'Superscript'], ['Нижний индекс', 'Subscript'], ['Цитировать выделенное', 'Quote selected'] ], cfgTab: { 'filters': ['Фильтры', 'Filters'], 'posts': ['Посты', 'Posts'], 'images': ['Картинки', 'Images'], 'links': ['Ссылки', 'Links'], 'form': ['Форма', 'Form'], 'common': ['Общее', 'Common'], 'info': ['Инфо', 'Info'] }, panelBtn: { 'attach': ['Прикрепить/Открепить', 'Attach/Detach'], 'settings': ['Настройки', 'Settings'], 'hidden': ['Скрытое', 'Hidden'], 'favor': ['Избранное', 'Favorites'], 'refresh': ['Обновить', 'Refresh'], 'goback': ['Назад', 'Go back'], 'gonext': ['Следующая', 'Next'], 'goup': ['Наверх', 'To the top'], 'godown': ['В конец', 'To the bottom'], 'expimg': ['Раскрыть картинки', 'Expand images'], 'preimg': ['Предзагрузка картинок ([Ctrl+Click] только для новых постов)', 'Preload images ([Ctrl+Click] for new posts only)'], 'maskimg': ['Маскировать картинки', 'Mask images'], 'upd-on': ['Выключить автообновление треда', 'Disable thread autoupdate'], 'upd-off': ['Включить автообновление треда', 'Enable thread autoupdate'], 'audio-off':['Звуковое оповещение о новых постах', 'Sound notification about new posts'], 'catalog': ['Каталог', 'Catalog'], 'counter': ['Постов/Изображений в треде', 'Posts/Images in thread'], 'imgload': ['Сохранить изображения из треда', 'Save images from thread'], 'enable': ['Включить/выключить скрипт', 'Turn on/off the script'] }, selHiderMenu: { 'sel': ['Скрывать выделенное', 'Hide selected text'], 'name': ['Скрывать имя', 'Hide name'], 'trip': ['Скрывать трип-код', 'Hide with trip-code'], 'img': ['Скрывать изображение', 'Hide with image'], 'ihash': ['Скрывать схожие изобр.', 'Hide similar images'], 'text': ['Скрыть схожий текст', 'Hide similar text'], 'noimg': ['Скрывать без изображений', 'Hide without images'], 'notext': ['Скрывать без текста', 'Hide without text'] }, selExpandThrd: [ ['5 постов', '15 постов', '30 постов', '50 постов', '100 постов'], ['5 posts', '15 posts', '30 posts', '50 posts', '100 posts'] ], selAjaxPages: [ ['1 страница', '2 страницы', '3 страницы', '4 страницы', '5 страниц'], ['1 page', '2 pages', '3 pages', '4 pages', '5 pages'] ], selAudioNotif: [ ['Каждые 30 сек.', 'Каждую минуту', 'Каждые 2 мин.', 'Каждые 5 мин.'], ['Every 30 sec.', 'Every minute', 'Every 2 min.', 'Every 5 min.'] ], keyNavEdit: [ '%l%i24 – предыдущая страница/изображение%/l' + '%l%i217 – следующая страница/изображение%/l' + '%l%i23 – скрыть текущий пост/тред%/l' + '%l%i33 – раскрыть текущий тред%/l' + '%l%i22 – быстрый ответ или создать тред%/l' + '%l%i25t – отправить пост%/l' + '%l%i21 – тред (на доске)/пост (в треде) ниже%/l' + '%l%i20 – тред (на доске)/пост (в треде) выше%/l' + '%l%i31 – пост (на доске) ниже%/l' + '%l%i30 – пост (на доске) выше%/l' + '%l%i32 – открыть тред%/l' + '%l%i210 – открыть/закрыть настройки%/l' + '%l%i26 – открыть/закрыть избранное%/l' + '%l%i27 – открыть/закрыть скрытые посты%/l' + '%l%i28 – открыть/закрыть панель%/l' + '%l%i29 – включить/выключить маскировку изображений%/l' + '%l%i40 – обновить тред%/l' + '%l%i211 – раскрыть изображение текущего поста%/l' + '%l%i212t – жирный%/l' + '%l%i213t – курсив%/l' + '%l%i214t – зачеркнутый%/l' + '%l%i215t – спойлер%/l' + '%l%i216t – код%/l', '%l%i24 – previous page/image%/l' + '%l%i217 – next page/image%/l' + '%l%i23 – hide current post/thread%/l' + '%l%i33 – expand current thread%/l' + '%l%i22 – quick reply or create thread%/l' + '%l%i25t – send post%/l' + '%l%i21 – thread (on board)/post (in thread) below%/l' + '%l%i20 – thread (on board)/post (in thread) above%/l' + '%l%i31 – on board post below%/l' + '%l%i30 – on board post above%/l' + '%l%i32 – open thread%/l' + '%l%i210 – open/close Settings%/l' + '%l%i26 – open/close Favorites%/l' + '%l%i27 – open/close Hidden Posts Table%/l' + '%l%i28 – open/close the main panel%/l' + '%l%i29 – turn on/off masking images%/l' + '%l%i40 – update thread%/l' + '%l%i211 – expand current post\'s images%/l' + '%l%i212t – bold%/l' + '%l%i213t – italic%/l' + '%l%i214t – strike%/l' + '%l%i215t – spoiler%/l' + '%l%i216t – code%/l' ], month: [ ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] ], fullMonth: [ ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'], ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] ], week: [ ['Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] ], editor: { cfg: ['Редактирование настроек:', 'Edit settings:'], hidden: ['Редактирование скрытых тредов:', 'Edit hidden threads:'], favor: ['Редактирование избранного:', 'Edit favorites:'], css: ['Редактирование CSS', 'Edit CSS'] }, newPost: [ [' новый пост', ' новых поста', ' новых постов', '. Последний:'], [' new post', ' new posts', ' new posts', '. Latest: '] ], add: ['Добавить', 'Add'], apply: ['Применить', 'Apply'], clear: ['Очистить', 'Clear'], refresh: ['Обновить', 'Refresh'], load: ['Загрузить', 'Load'], save: ['Сохранить', 'Save'], edit: ['Правка', 'Edit'], reset: ['Сброс', 'Reset'], remove: ['Удалить', 'Remove'], info: ['Инфо', 'Info'], undo: ['Отмена', 'Undo'], change: ['Сменить', 'Change'], reply: ['Ответ', 'Reply'], loading: ['Загрузка...', 'Loading...'], checking: ['Проверка...', 'Checking...'], deleting: ['Удаление...', 'Deleting...'], error: ['Ошибка', 'Error'], noConnect: ['Ошибка подключения', 'Connection failed'], thrNotFound: ['Тред недоступен (№', 'Thread is unavailable (№'], succDeleted: ['Успешно удалено!', 'Succesfully deleted!'], errDelete: ['Не могу удалить:\n', 'Can\'t delete:\n'], cTimeError: ['Неправильные настройки времени', 'Invalid time settings'], noGlobalCfg: ['Глобальные настройки не найдены', 'Global config not found'], postNotFound: ['Пост не найден', 'Post not found'], dontShow: ['Скрыть: ', 'Hide: '], checkNow: ['Проверить сейчас', 'Check now'], updAvail: ['Доступно обновление!', 'Update available!'], haveLatest: ['У вас стоит самая последняя версия!', 'You have latest version!'], storage: ['Хранение: ', 'Storage: '], thrViewed: ['Тредов просмотрено: ', 'Threads viewed: '], thrCreated: ['Тредов создано: ', 'Threads created: '], thrHidden: ['Тредов скрыто: ', 'Threads hidden: '], postsSent: ['Постов отправлено: ', 'Posts sent: '], total: ['Всего: ', 'Total: '], debug: ['Отладка', 'Debug'], infoDebug: ['Информация для отладки', 'Information for debugging'], loadGlobal: ['Загрузить глобальные настройки', 'Load global settings'], saveGlobal: ['Сохранить настройки как глобальные', 'Save settings as global'], editInTxt: ['Правка в текстовом формате', 'Edit in text format'], resetCfg: ['Сбросить в настройки по умолчанию', 'Reset settings to defaults'], conReset: ['Данное действие удалит все ваши настройки и закладки. Продолжить?', 'This will delete all your preferences and favourites. Continue?'], clrSelected: ['Удалить выделенные записи', 'Remove selected notes'], saveChanges: ['Сохранить внесенные изменения', 'Save your changes'], infoCount: ['Обновить счетчики постов', 'Refresh posts counters'], infoPage: ['Проверить актуальность тредов (до 5 страницы)', 'Check for threads actuality (up to 5 page)'], clrDeleted: ['Очистить записи недоступных тредов', 'Clear notes of inaccessible threads'], hiddenPosts: ['Скрытые посты на странице', 'Hidden posts on the page'], hiddenThrds: ['Скрытые треды', 'Hidden threads'], noHidPosts: ['На этой странице нет скрытых постов...', 'No hidden posts on this page...'], noHidThrds: ['Нет скрытых тредов...', 'No hidden threads...'], expandAll: ['Раскрыть все', 'Expand all'], invalidData: ['Некорректный формат данных', 'Incorrect data format'], favThrds: ['Избранные треды:', 'Favorite threads:'], noFavThrds: ['Нет избранных тредов...', 'Favorites is empty...'], replyTo: ['Ответ в', 'Reply to'], replies: ['Ответы:', 'Replies:'], postsOmitted: ['Пропущено ответов: ', 'Posts omitted: '], collapseThrd: ['Свернуть тред', 'Collapse thread'], deleted: ['удалён', 'deleted'], getNewPosts: ['Получить новые посты', 'Get new posts'], page: ['Страница', 'Page'], hiddenThrd: ['Скрытый тред:', 'Hidden thread:'], makeThrd: ['Создать тред', 'Create thread'], makeReply: ['Ответить', 'Make reply'], hideForm: ['Скрыть форму', 'Hide form'], search: ['Искать в ', 'Search in '], wait: ['Ждите', 'Wait'], noFile: ['Нет файла', 'No file'], clickToAdd: ['Выберите, либо перетащите файл', 'Select or drag and drop file'], removeFile: ['Удалить файл', 'Remove file'], helpAddFile: ['Встроить .ogg, .rar, .zip или .7z в картинку', 'Pack .ogg, .rar, .zip or .7z into image'], downloadFile: ['Скачать содержащийся в картинке файл', 'Download existing file from image'], fileCorrupt: ['Файл повреждён: ', 'File is corrupted: '], subjHasTrip: ['Поле "Тема" содержит трипкод', '"Subject" field contains a tripcode'], loadImage: ['Загружаются изображения: ', 'Loading images: '], loadFile: ['Загружаются файлы: ', 'Loading files: '], cantLoad: ['Не могу загрузить ', 'Can\'t load '], willSavePview: ['Будет сохранено превью', 'Thumbnail will be saved'], loadErrors: ['Во время загрузки произошли ошибки:', 'An error occurred during the loading:'], errCorruptData: ['Ошибка: сервер отправил повреждённые данные', 'Error: server sent corrupted data'], nextImg: ['Следующее изображение', 'Next image'], prevImg: ['Предыдущее изображение', 'Previous image'], togglePost: ['Скрыть/Раскрыть пост', 'Hide/Unhide post'], replyToPost: ['Ответить на пост', 'Reply to post'], expandThrd: ['Раскрыть весь тред', 'Expand all thread'], toggleFav: ['Добавить/Убрать Избранное', 'Add/Remove Favorites'], attachPview: ['Закрепить превью', 'Attach preview'], author: ['автор: ', 'author: '], views: ['просмотров: ', 'views: '], published: ['опубликовано: ', 'published: '], seSyntaxErr: ['синтаксическая ошибка в аргументе спелла: %s', 'syntax error in argument of spell: %s'], seUnknown: ['неизвестный спелл: %s', 'unknown spell: %s'], seMissOp: ['пропущен оператор', 'missing operator'], seMissArg: ['пропущен аргумент спелла: %s', 'missing argument of spell: %s'], seMissSpell: ['пропущен спелл', 'missing spell'], seErrRegex: ['синтаксическая ошибка в регулярном выражении: %s', 'syntax error in regular expression: %s'], seUnexpChar: ['неожиданный символ: %s', 'unexpected character: %s'], seMissClBkt: ['пропущена закрывающаяся скобка', 'missing ) in parenthetical'], seRow: [' (строка ', ' (row '], seCol: [', столбец ', ', column '] }, doc = window.document, aProto = Array.prototype, locStorage, sesStorage, Cfg, comCfg, hThr, pByNum, sVis, bUVis, needScroll, aib, nav, brd, TNum, pageNum, updater, keyNav, firstThr, lastThr, visPosts = 2, dTime, YouTube, WebmParser, Logger, pr, dForm, dummy, spells, Images_ = {preloading: false, afterpreload: null, progressId: null, canvas: null}, ajaxInterval, lang, quotetxt = '', liteMode, isExpImg, isPreImg, chromeCssUpd, $each = Function.prototype.call.bind(aProto.forEach), emptyFn = function() {}; //============================================================================================================ // UTILITIES //============================================================================================================ function $Q(path, root) { return root.querySelectorAll(path); } function $q(path, root) { return root.querySelector(path); } function $C(id, root) { return root.getElementsByClassName(id); } function $c(id, root) { return root.getElementsByClassName(id)[0]; } function $id(id) { return doc.getElementById(id); } function $T(id, root) { return root.getElementsByTagName(id); } function $t(id, root) { return root.getElementsByTagName(id)[0]; } function $append(el, nodes) { for(var i = 0, len = nodes.length; i < len; i++) { if(nodes[i]) { el.appendChild(nodes[i]); } } } function $before(el, node) { el.parentNode.insertBefore(node, el); } function $after(el, node) { el.parentNode.insertBefore(node, el.nextSibling); } function $add(html) { dummy.innerHTML = html; return dummy.firstChild; } function $new(tag, attr, events) { var el = doc.createElement(tag); if(attr) { for(var key in attr) { key === 'text' ? el.textContent = attr[key] : key === 'value' ? el.value = attr[key] : el.setAttribute(key, attr[key]); } } if(events) { for(var key in events) { el.addEventListener(key, events[key], false); } } return el; } function $New(tag, attr, nodes) { var el = $new(tag, attr, null); $append(el, nodes); return el; } function $txt(el) { return doc.createTextNode(el); } function $btn(val, ttl, Fn) { return $new('input', {'type': 'button', 'value': val, 'title': ttl}, {'click': Fn}); } function $script(text) { $del(doc.head.appendChild($new('script', {'type': 'text/javascript', 'text': text}, null))); } function $css(text) { return doc.head.appendChild($new('style', {'type': 'text/css', 'text': text}, null)); } function $if(cond, el) { return cond ? el : null; } function $disp(el) { el.style.display = el.style.display === 'none' ? '' : 'none'; } function $del(el) { if(el) { el.parentNode.removeChild(el); } } function $DOM(html) { var myDoc = doc.implementation.createHTMLDocument(''); myDoc.documentElement.innerHTML = html; return myDoc; } function $pd(e) { e.preventDefault(); } function $txtInsert(el, txt) { var scrtop = el.scrollTop, start = el.selectionStart; el.value = el.value.substr(0, start) + txt + el.value.substr(el.selectionEnd); el.setSelectionRange(start + txt.length, start + txt.length); el.focus(); el.scrollTop = scrtop; } function $txtSelect() { return (nav.Presto ? doc.getSelection() : window.getSelection()).toString(); } function $isEmpty(obj) { for(var i in obj) { if(obj.hasOwnProperty(i)) { return false; } } return true; } Logger = new function() { var instance, oldTime, initTime, timeLog; function LoggerSingleton() { if(instance) { return instance; } instance = this; } LoggerSingleton.prototype = { finish: function() { timeLog.push(Lng.total[lang] + (Date.now() - initTime) + 'ms'); }, get: function() { return timeLog; }, init: function() { oldTime = initTime = Date.now(); timeLog = []; }, log: function realLog(text) { var newTime = Date.now(), time = newTime - oldTime; if(time > 1) { timeLog.push(text + ': ' + time + 'ms'); oldTime = newTime; } } }; return LoggerSingleton; }; function $xhr(obj) { var h, xhr = new XMLHttpRequest(); if(obj['onreadystatechange']) { xhr.onreadystatechange = obj['onreadystatechange'].bind(window, xhr); } if(obj['onload']) { xhr.onload = obj['onload'].bind(window, xhr); } xhr.open(obj['method'], obj['url'], true); if(obj['responseType']) { xhr.responseType = obj['responseType']; } for(h in obj['headers']) { xhr.setRequestHeader(h, obj['headers'][h]); } xhr.send(obj['data'] || null); return xhr; } function $queue(maxNum, Fn, endFn) { this.array = []; this.length = this.index = this.running = 0; this.num = 1; this.fn = Fn; this.endFn = endFn; this.max = maxNum; this.freeSlots = []; while(maxNum--) { this.freeSlots.push(maxNum); } this.completed = this.paused = false; } $queue.prototype = { run: function(data) { if(this.paused || this.running === this.max) { this.array.push(data); this.length++; } else { this.fn(this.freeSlots.pop(), this.num++, data); this.running++; } }, end: function(qIdx) { if(!this.paused && this.index < this.length) { this.fn(qIdx, this.num++, this.array[this.index++]); return; } this.running--; this.freeSlots.push(qIdx); if(!this.paused && this.completed && this.running === 0) { this.endFn(); } }, complete: function() { if(this.index >= this.length && this.running === 0) { this.endFn(); } else { this.completed = true; } }, pause: function() { this.paused = true; }, 'continue': function() { this.paused = false; if(this.index >= this.length) { if(this.completed) { this.endFn(); } return; } while(this.index < this.length && this.running !== this.max) { this.fn(this.freeSlots.pop(), this.num++, this.array[this.index++]); this.running++; } } }; function $tar() { this._data = []; } $tar.prototype = { addFile: function(filepath, input) { var i, checksum, nameLen, fileSize = input.length, header = new Uint8Array(512); for(i = 0, nameLen = Math.min(filepath.length, 100); i < nameLen; ++i) { header[i] = filepath.charCodeAt(i) & 0xFF; } this._padSet(header, 100, '100777', 8); // fileMode this._padSet(header, 108, '0', 8); // uid this._padSet(header, 116, '0', 8); // gid this._padSet(header, 124, fileSize.toString(8), 13); // fileSize this._padSet(header, 136, Math.floor(Date.now() / 1000).toString(8), 12); // mtime this._padSet(header, 148, ' ', 8); // checksum header[156] = 0x30; // type ('0') for(i = checksum = 0; i < 157; i++) { checksum += header[i]; } this._padSet(header, 148, checksum.toString(8), 8); // checksum this._data.push(header); this._data.push(input); if((i = Math.ceil(fileSize / 512) * 512 - fileSize) !== 0) { this._data.push(new Uint8Array(i)); } }, addString: function(filepath, str) { var i, len, data, sDat = unescape(encodeURIComponent(str)); for(i = 0, len = sDat.length, data = new Uint8Array(len); i < len; ++i) { data[i] = sDat.charCodeAt(i) & 0xFF; } this.addFile(filepath, data); }, get: function() { this._data.push(new Uint8Array(1024)); return new Blob(this._data, {'type': 'application/x-tar'}); }, _padSet: function(data, offset, num, len) { var i = 0, nLen = num.length; len -= 2; while(nLen < len) { data[offset++] = 0x20; // ' ' len--; } while(i < nLen) { data[offset++] = num.charCodeAt(i++); } data[offset] = 0x20; // ' ' } }; function $workers(source, count) { var i, wrk, wUrl; if(nav.Firefox) { wUrl = 'data:text/javascript,' + source; wrk = unsafeWindow.Worker; } else { wUrl = window.URL.createObjectURL(new Blob([source], {'type': 'text/javascript'})); this.url = wUrl; wrk = Worker; } for(i = 0; i < count; ++i) { this[i] = new wrk(wUrl); } } $workers.prototype = { url: null, clear: function() { if(this.url !== null) { window.URL.revokeObjectURL(this.url); } } }; function regQuote(str) { return (str + '').replace(/([.?*+^$[\]\\(){}|\-])/g, '\\$1'); } function fixBrd(b) { return '/' + b + (b ? '/' : ''); } function getAbsLink(url) { return url[1] === '/' ? aib.prot + url : url[0] === '/' ? aib.prot + '//' + aib.host + url : url; } function getErrorMessage(eCode, eMsg) { return eCode === 0 ? eMsg || Lng.noConnect[lang] : 'HTTP [' + eCode + '] ' + eMsg; } function getAncestor(el, tagName) { do { el = el.parentElement; } while(el && el.tagName !== tagName); return el; } function getPrettyErrorMessage(e) { return e.stack ? (nav.WebKit ? e.stack : e.name + ': ' + e.message + '\n' + (nav.Firefox ? e.stack.replace(/^([^@]*).*\/(.+)$/gm, function(str, fName, line) { return ' at ' + (fName ? fName + ' (' + line + ')' : line); }) : e.stack) ) : e.name + ': ' + e.message; } function toRegExp(str, noG) { var l = str.lastIndexOf('/'), flags = str.substr(l + 1); return new RegExp(str.substr(1, l - 1), noG ? flags.replace('g', '') : flags); } //============================================================================================================ // STORAGE & CONFIG //============================================================================================================ function getStored(id, Fn) { if(nav.isGM) { Fn(GM_getValue(id)); } else if(nav.isChromeStorage) { chrome.storage.sync.get(id, function(obj) { Fn(obj[id]); }); } else if(nav.isScriptStorage) { Fn(scriptStorage.getItem(id)); } else { Fn(locStorage.getItem(id)); } } function setStored(id, value) { if(nav.isGM) { GM_setValue(id, value); } else if(nav.isChromeStorage) { var obj = {}; obj[id] = value; chrome.storage.sync.set(obj, function() {}); } else if(nav.isScriptStorage) { scriptStorage.setItem(id, value); } else { locStorage.setItem(id, value); } } function delStored(id) { if(nav.isGM) { GM_deleteValue(id); } else if(nav.isChromeStorage) { chrome.storage.sync.remove(id, function() {}); } else if(nav.isScriptStorage) { scriptStorage.removeItem(id); } else { locStorage.removeItem(id); } } function getStoredObj(id, Fn) { getStored(id, function(Fn, val) { try { var data = JSON.parse(val || '{}'); } finally { Fn(data || {}); } }.bind(null, Fn)); } function saveComCfg(dm, obj) { getStoredObj('DESU_Config', function(dm, obj, val) { comCfg = val; if(obj) { comCfg[dm] = obj; } else { delete comCfg[dm]; } setStored('DESU_Config', JSON.stringify(comCfg) || ''); }.bind(null, dm, obj)); } function saveCfg(id, val) { if(Cfg[id] !== val) { Cfg[id] = val; saveComCfg(aib.dm, Cfg); } } function Config(obj) { for(var i in obj) { this[i] = obj[i]; } } Config.prototype = defaultCfg; function readCfg(Fn) { getStoredObj('DESU_Config', function(Fn, val) { var obj; comCfg = val; if(!(aib.dm in comCfg) || $isEmpty(obj = comCfg[aib.dm])) { if(nav.isChromeStorage && (obj = locStorage.getItem('DESU_Config'))) { obj = JSON.parse(obj)[aib.dm]; locStorage.removeItem('DESU_Config'); } else { obj = nav.isGlobal ? comCfg['global'] || {} : {}; } obj['captchaLang'] = aib.ru ? 2 : 1; obj['correctTime'] = 0; } Cfg = new Config(obj); if(!Cfg['timeOffset']) { Cfg['timeOffset'] = '+0'; } if(!Cfg['timePattern']) { Cfg['timePattern'] = aib.timePattern; } if((nav.Opera11 || aib.fch || aib.tiny) && Cfg['ajaxReply'] === 2) { Cfg['ajaxReply'] = 1; } if(!('Notification' in window)) { Cfg['desktNotif'] = 0; } if(nav.Presto) { if(nav.Opera11) { if(!nav.isGM) { Cfg['YTubeTitles'] = 0; } Cfg['animation'] = 0; } if(Cfg['YTubeType'] === 2) { Cfg['YTubeType'] = 1; } Cfg['preLoadImgs'] = 0; Cfg['findImgFile'] = 0; if(!nav.isGM) { Cfg['updScript'] = 0; } Cfg['fileThumb'] = 0; } if(nav.isChromeStorage) { Cfg['updScript'] = 0; } if(Cfg['updThrDelay'] < 10) { Cfg['updThrDelay'] = 10; } if(!Cfg['saveSage']) { Cfg['sageReply'] = 0; } if(!Cfg['passwValue']) { Cfg['passwValue'] = Math.round(Math.random() * 1e15).toString(32); } if(!Cfg['stats']) { Cfg['stats'] = {'view': 0, 'op': 0, 'reply': 0}; } if(TNum) { Cfg['stats']['view']++; } if(aib.dobr) { Cfg['fileThumb'] = 0; aib.hDTFix = new dateTime( 'yyyy-nn-dd-hh-ii-ss', '_d _M _Y (_w) _h:_i ', Cfg['timeOffset'] || 0, Cfg['correctTime'] ? lang : 1, null ); } saveComCfg(aib.dm, Cfg); lang = Cfg['language']; if(Cfg['correctTime']) { dTime = new dateTime(Cfg['timePattern'], Cfg['timeRPattern'], Cfg['timeOffset'], lang, function(rp) { saveCfg('timeRPattern', rp); }); } Fn(); }.bind(null, Fn)); } function toggleCfg(id) { saveCfg(id, +!Cfg[id]); } function readPosts() { var data, str = TNum ? sesStorage['de-hidden-' + brd + TNum] : null; if(typeof str === 'string') { data = str.split(','); if(data.length === 4 && +data[0] === (Cfg['hideBySpell'] ? spells.hash : 0) && (data[1] in pByNum) && pByNum[data[1]].count === +data[2]) { sVis = data[3].split(''); return; } } sVis = []; } function readUserPosts() { getStoredObj('DESU_Posts_' + aib.dm, function(val) { bUVis = val; getStoredObj('DESU_Threads_' + aib.dm, function(val) { hThr = val; if(nav.isChromeStorage && (val = locStorage.getItem('DESU_Posts_' + aib.dm))) { bUVis = JSON.parse(val); val = locStorage.getItem('DESU_Threads_' + aib.dm); hThr = JSON.parse(val); locStorage.removeItem('DESU_Posts_' + aib.dm); locStorage.removeItem('DESU_Threads_' + aib.dm); } var uVis, vis, num, post, date = Date.now(), update = false; if(brd in bUVis) { uVis = bUVis[brd]; } else { uVis = bUVis[brd] = {}; } if(!(brd in hThr)) { hThr[brd] = {}; } if(!firstThr) { return; } for(post = firstThr.op; post; post = post.next) { num = post.num; if(num in uVis) { if(post.isOp) { uVis[num][0] = +!(num in hThr[brd]); } if(uVis[num][0] === 0) { post.setUserVisib(true, date, false); } else { uVis[num][1] = date; post.btns.firstChild.className = 'de-btn-hide-user'; post.userToggled = true; } } else { vis = sVis[post.count]; if(post.isOp) { if(num in hThr[brd]) { vis = '0'; } else if(vis === '0') { vis = null; } } if(vis === '0') { if(!post.hidden) { post.setVisib(true); post.hideRefs(); } post.spellHidden = true; } else if(vis !== '1') { spells.check(post); } } } spells.end(savePosts); if(update) { bUVis[brd] = uVis; saveUserPosts(false); } }); }); } function savePosts() { if(TNum) { var lPost = firstThr.lastNotDeleted; sesStorage['de-hidden-' + brd + TNum] = (Cfg['hideBySpell'] ? spells.hash : '0') + ',' + lPost.num + ',' + lPost.count + ',' + sVis.join(''); } saveHiddenThreads(false); toggleContent('hid', true); } function saveUserPosts(clear) { var minDate, b, vis, key, str = JSON.stringify(bUVis); if(clear && str.length > 1e6) { minDate = Date.now() - 5 * 24 * 3600 * 1000; for(b in bUVis) { if(bUVis.hasOwnProperty(b)) { vis = bUVis[b]; for(key in vis) { if(vis.hasOwnProperty(key) && vis[key][1] < minDate) { delete vis[key]; } } } } str = JSON.stringify(bUVis); } setStored('DESU_Posts_' + aib.dm, str); toggleContent('hid', true); } function saveHiddenThreads(updContent) { setStored('DESU_Threads_' + aib.dm, JSON.stringify(hThr)); if(updContent) { toggleContent('hid', true); } } function readFavoritesPosts() { getStoredObj('DESU_Favorites', function(fav) { var thr, temp, update = false; if(nav.isChromeStorage && (temp = locStorage.getItem('DESU_Favorites'))) { temp = JSON.parse(temp); locStorage.removeItem('DESU_Favorites'); if($isEmpty(temp)) { return; } temp = temp[aib.host]; fav[aib.host] = temp; temp = temp[brd]; } else { if(!(aib.host in fav)) { return; } temp = fav[aib.host]; if(!(brd in temp)) { return; } temp = temp[brd]; } for(thr = firstThr; thr; thr = thr.next) { if(thr.num in temp) { $c('de-btn-fav', thr.op.btns).className = 'de-btn-fav-sel'; if(TNum) { temp[thr.num]['cnt'] = thr.pcount; temp[thr.num]['new'] = 0; } else { temp[thr.num]['new'] = thr.pcount - temp[thr.num]['cnt']; } update = true; } } if(update) { saveFavorites(fav); } }); } function saveFavorites(fav) { setStored('DESU_Favorites', JSON.stringify(fav)); toggleContent('fav', true, fav); } function removeFavoriteEntry(fav, h, b, num, clearPage) { function _isEmpty(f) { for(var i in f) { if(i !== 'url' && f.hasOwnProperty(i)) { return false; } } return true; } if((h in fav) && (b in fav[h]) && (num in fav[h][b])) { delete fav[h][b][num]; if(_isEmpty(fav[h][b])) { delete fav[h][b]; if($isEmpty(fav[h])) { delete fav[h]; } } } if(clearPage && h === aib.host && b === brd && (num in pByNum)) { ($c('de-btn-fav-sel', pByNum[num].btns) || {}).className = 'de-btn-fav'; } } function readViewedPosts() { if(Cfg['markViewed']) { var data = sesStorage['de-viewed']; if(data) { data.split(',').forEach(function(pNum) { var post = pByNum[pNum]; if(post) { post.el.classList.add('de-viewed'); post.viewed = true; } }); } } } //============================================================================================================ // MAIN PANEL //============================================================================================================ function pButton(id, href, hasHotkey) { return '<li><a id="de-btn-' + id + '" class="de-abtn" ' + (hasHotkey ? 'de-' : '') + 'title="' + Lng.panelBtn[id][lang] +'" href="' + href + '"></a></li>'; } function addPanel() { var panel, evtObject, imgLen = $Q(aib.qThumbImages, dForm).length; (pr && pr.pArea[0] || dForm).insertAdjacentHTML('beforebegin', '<div id="de-main" lang="' + getThemeLang() + '">' + '<div class="de-content"></div>' + '<div id="de-panel">' + '<span id="de-btn-logo" title="' + Lng.panelBtn['attach'][lang] + '"></span>' + '<ul id="de-panel-btns"' + (Cfg['expandPanel'] ? '>' : ' style="display: none">') + (Cfg['disabled'] ? pButton('enable', '#', false) : pButton('settings', '#', true) + pButton('hidden', '#', true) + pButton('favor', '#', true) + (aib.arch ? '' : pButton('refresh', '#', false) + (!TNum && (pageNum === aib.firstPage) ? '' : pButton('goback', aib.getPageUrl(brd, pageNum - 1), true)) + (TNum || pageNum === aib.lastPage ? '' : pButton('gonext', aib.getPageUrl(brd, pageNum + 1), true)) ) + pButton('goup', '#', false) + pButton('godown', '#', false) + (imgLen === 0 ? '' : pButton('expimg', '#', false) + pButton('maskimg', '#', true) + (nav.Presto ? '' : (Cfg['preLoadImgs'] ? '' : pButton('preimg', '#', false)) + (!TNum && !aib.arch ? '' : pButton('imgload', '#', false)))) + (!TNum ? '' : pButton(Cfg['ajaxUpdThr'] ? 'upd-on' : 'upd-off', '#', false) + (nav.Safari ? '' : pButton('audio-off', '#', false))) + (!aib.abu && (!aib.fch || aib.arch) ? '' : pButton('catalog', '//' + aib.host + '/' + (aib.abu ? 'makaba/makaba.fcgi?task=catalog&board=' + brd : brd + '/catalog.html'), false)) + pButton('enable', '#', false) + (!TNum && !aib.arch ? '' : '<div id="de-panel-info"><span title="' + Lng.panelBtn['counter'][lang] + '">' + firstThr.pcount + '/' + imgLen + '</span></div>') ) + '</ul>' + '</div>' + (Cfg['disabled'] ? '' : '<div id="de-alert"></div>' + '<hr style="clear: both;">' ) + '</div>' ); panel = $id('de-panel'); evtObject = { attach: false, odelay: 0, panel: panel, handleEvent: function(e) { switch(e.type) { case 'click': switch(e.target.id) { case 'de-btn-logo': if(Cfg['expandPanel']) { this.panel.lastChild.style.display = 'none'; this.attach = false; } else { this.attach = true; } toggleCfg('expandPanel'); return; case 'de-btn-settings': this.attach = toggleContent('cfg', false); break; case 'de-btn-hidden': this.attach = toggleContent('hid', false); break; case 'de-btn-favor': this.attach = toggleContent('fav', false); break; case 'de-btn-refresh': window.location.reload(); break; case 'de-btn-goup': scrollTo(0, 0); break; case 'de-btn-godown': scrollTo(0, doc.body.scrollHeight || doc.body.offsetHeight); break; case 'de-btn-expimg': isExpImg = !isExpImg; $del($c('de-img-center', doc)); for(var post = firstThr.op; post; post = post.next) { post.toggleImages(isExpImg); } break; case 'de-btn-preimg': isPreImg = !isPreImg; if(!e.ctrlKey) { preloadImages(null); } break; case 'de-btn-maskimg': toggleCfg('maskImgs'); updateCSS(); break; case 'de-btn-upd-on': case 'de-btn-upd-off': case 'de-btn-upd-warn': if(updater.enabled) { updater.disable(); } else { updater.enable(); } break; case 'de-btn-audio-on': case 'de-btn-audio-off': if(updater.toggleAudio(0)) { updater.enable(); e.target.id = 'de-btn-audio-on'; } else { e.target.id = 'de-btn-audio-off'; } $del($c('de-menu', doc)); break; case 'de-btn-imgload': if($id('de-alert-imgload')) { break; } if(Images_.preloading) { $alert(Lng.loading[lang], 'imgload', true); Images_.afterpreload = loadDocFiles.bind(null, true); Images_.progressId = 'imgload'; } else { loadDocFiles(true); } break; case 'de-btn-enable': toggleCfg('disabled'); window.location.reload(); break; default: return; } $pd(e); return; case 'mouseover': if(!Cfg['expandPanel']) { clearTimeout(this.odelay); this.panel.lastChild.style.display = ''; } switch(e.target.id) { case 'de-btn-settings': KeyEditListener.setTitle(e.target, 10); break; case 'de-btn-hidden': KeyEditListener.setTitle(e.target, 7); break; case 'de-btn-favor': KeyEditListener.setTitle(e.target, 6); break; case 'de-btn-goback': KeyEditListener.setTitle(e.target, 4); break; case 'de-btn-gonext': KeyEditListener.setTitle(e.target, 17); break; case 'de-btn-maskimg': KeyEditListener.setTitle(e.target, 9); break; case 'de-btn-refresh': if(TNum) { return; } case 'de-btn-audio-off': addMenu(e); } return; default: // mouseout if(!Cfg['expandPanel'] && !this.attach) { this.odelay = setTimeout(function(obj) { obj.panel.lastChild.style.display = 'none'; obj.attach = false; }, 500, this); } switch(e.target.id) { case 'de-btn-refresh': case 'de-btn-audio-off': removeMenu(e); break; } } } }; panel.addEventListener('click', evtObject, true); panel.addEventListener('mouseover', evtObject, false); panel.addEventListener('mouseout', evtObject, false); } function toggleContent(name, isUpd, data) { if(liteMode) { return false; } var remove, el = $c('de-content', doc), id = 'de-content-' + name; if(!el) { return false; } if(isUpd && el.id !== id) { return true; } remove = !isUpd && el.id === id; if(el.hasChildNodes() && Cfg['animation']) { nav.animEvent(el, function(node) { showContent(node, id, name, remove, data); id = name = remove = data = null; }); el.className = 'de-content de-cfg-close'; return !remove; } else { showContent(el, id, name, remove, data); return !remove; } } function addContentBlock(parent, title) { return parent.appendChild($New('div', {'class': 'de-content-block'}, [ $new('input', {'type': 'checkbox'}, {'click': function() { var el, res = this.checked, i = 0, els = $Q('.de-entry > div > input', this.parentNode); for(; el = els[i++];) { el.checked = res; } }}), title ])); } function showContent(cont, id, name, remove, data) { var tNum, i, b, els, post, cln, block, temp, cfgTabId; if(name === 'cfg' && !remove && (temp = $q('.de-cfg-tab-back[selected="true"] > .de-cfg-tab', cont))) { cfgTabId = temp.getAttribute('info'); } cont.innerHTML = cont.style.backgroundColor = ''; if(remove) { cont.removeAttribute('id'); return; } cont.id = id; if(name === 'cfg') { addSettings(cont, cfgTabId); } else if(Cfg['attachPanel']) { cont.style.backgroundColor = getComputedStyle(doc.body).getPropertyValue('background-color'); } if(name === 'fav') { if(data) { showFavoriteTable(cont, data); } else { // TODO: show load message getStoredObj('DESU_Favorites', function(fav) { showFavoriteTable(this, fav); }.bind(cont)); } return; } if(name === 'hid') { for(i = 0, els = $C('de-post-hide', dForm); post = els[i++];) { if(post.isOp) { continue; } (cln = post.cloneNode(true)).removeAttribute('id'); cln.style.display = ''; if(cln.classList.contains(aib.cRPost)) { cln.classList.add('de-cloned-post'); } else { cln.className = aib.cReply + ' de-cloned-post'; } cln.post = Object.create(cln.clone = post.post); cln.post.el = cln; cln.btn = $q('.de-btn-hide, .de-btn-hide-user', cln); cln.btn.parentNode.className = 'de-ppanel'; cln.btn.onclick = function() { // doesn't work properly. TODO: Fix this.hideContent(this.hidden = !this.hidden); }.bind(cln); (block || (block = cont.appendChild( $add('<div class="de-content-block"><b>' + Lng.hiddenPosts[lang] + ':</b></div>') ))).appendChild($New('div', {'class': 'de-entry'}, [cln])); } if(block) { $append(cont, [ $btn(Lng.expandAll[lang], '', function() { $each($Q('.de-cloned-post', this.parentNode), function(el) { var post = el.post; post.hideContent(post.hidden = !post.hidden); }); this.value = this.value === Lng.undo[lang] ? Lng.expandAll[lang] : Lng.undo[lang]; }), $btn(Lng.save[lang], '', function() { $each($Q('.de-cloned-post', this.parentNode), function(date, el) { if(!el.post.hidden) { el.clone.setUserVisib(false, date, true); } }.bind(null, Date.now())); saveUserPosts(true); }) ]); } else { cont.appendChild($new('b', {'text': Lng.noHidPosts[lang]}, null)); } $append(cont, [ doc.createElement('hr'), $new('b', {'text': ($isEmpty(hThr) ? Lng.noHidThrds[lang] : Lng.hiddenThrds[lang] + ':')}, null) ]); for(b in hThr) { if(!$isEmpty(hThr[b])) { block = addContentBlock(cont, $new('b', {'text': '/' + b}, null)); for(tNum in hThr[b]) { block.insertAdjacentHTML('beforeend', '<div class="de-entry" info="' + b + ';' + tNum + '"><div class="' + aib.cReply + '"><input type="checkbox"><a href="' + aib.getThrdUrl(b, tNum) + '" target="_blank">№' + tNum + '</a> - ' + hThr[b][tNum] + '</div></div>'); } } } $append(cont, [ doc.createElement('hr'), addEditButton('hidden', function(Fn) { Fn(hThr, true, function(data) { hThr = data; if(!(brd in hThr)) { hThr[brd] = {}; } firstThr.updateHidden(hThr[brd]); saveHiddenThreads(true); locStorage['__de-threads'] = JSON.stringify(hThr); locStorage.removeItem('__de-threads'); }); }), $btn(Lng.clear[lang], Lng.clrDeleted[lang], function() { $each($Q('.de-entry[info]', this.parentNode), function(el) { var arr = el.getAttribute('info').split(';'); ajaxLoad(aib.getThrdUrl(arr[0], arr[1]), false, null, function(eCode, eMsg, xhr) { if(eCode === 404) { delete hThr[this[0]][this[1]]; saveHiddenThreads(true); } }.bind(arr)); }); }), $btn(Lng.remove[lang], Lng.clrSelected[lang], function() { $each($Q('.de-entry[info]', this.parentNode), function(date, el) { var post, arr = el.getAttribute('info').split(';'); if($t('input', el).checked) { if(arr[1] in pByNum) { pByNum[arr[1]].setUserVisib(false, date, true); } else { locStorage['__de-post'] = JSON.stringify({ 'brd': arr[0], 'date': date, 'isOp': true, 'num': arr[1], 'hide': false }); locStorage.removeItem('__de-post'); } delete hThr[arr[0]][arr[1]]; } }.bind(null, Date.now())); saveHiddenThreads(true); }) ]); } if(Cfg['animation']) { cont.className = 'de-content de-cfg-open'; } } function clearFavoriteTable() { var els = $Q('.de-entry[de-removed]', doc), len = els.length; if(len > 0) { getStoredObj('DESU_Favorites', function(fav) { for(var el, i = 0; i < len; ++i) { el = els[i]; removeFavoriteEntry(fav, el.getAttribute('de-host'), el.getAttribute('de-board'), el.getAttribute('de-num'), true); } saveFavorites(fav); }); } } function showFavoriteTable(cont, data) { var h, b, i, block, tNum; for(h in data) { for(b in data[h]) { i = data[h][b]; block = addContentBlock(cont, i['url'] ? $new('a', {'href': i['url'], 'text': h + '/' + b}, null) : $new('b', {'text': h + '/' + b}, null)); if(h === aib.host && b === brd) { block.classList.add('de-fav-current'); } for(tNum in data[h][b]) { if(tNum === 'url') { continue; } i = data[h][b][tNum]; if(!i['url'].startsWith('http')) { i['url'] = (h === aib.host ? aib.prot + '//' : 'http://') + h + i['url']; } block.appendChild($New('div', { 'class': 'de-entry', 'de-host': h, 'de-board': b, 'de-num': tNum, 'de-url': i['url'] }, [ $New('div', {'class': aib.cReply}, [ $add('<input type="checkbox">'), $new('span', {'class': 'de-btn-expthr'}, {'click': loadFavorThread}), $add('<a href="' + i['url'] + '">№' + tNum + '</a>'), $add('<span class="de-fav-title"> - ' + i['txt'] + '</span>'), $add('<span class="de-fav-inf-page"></span>'), $add('<span class="de-fav-inf-posts">[<span class="de-fav-inf-old">' + i['cnt'] + '</span>][<span class="de-fav-inf-new">' + i['new'] + '</span>]</span>') ]) ])); } } } cont.insertAdjacentHTML('afterbegin', '<b>' + (Lng[block ? 'favThrds' : 'noFavThrds'][lang]) + '</b>'); $append(cont, [ doc.createElement('hr'), addEditButton('favor', function(Fn) { getStoredObj('DESU_Favorites', function(Fn, val) { Fn(val, true, saveFavorites); }.bind(null, Fn)); }), $btn(Lng.info[lang], Lng.infoCount[lang], function() { getStoredObj('DESU_Favorites', function(fav) { var i, els, len, update = false; var queue = new $queue(4, function(qIdx, num, el) { var c, host = el.getAttribute('de-host'), b = el.getAttribute('de-board'), num = el.getAttribute('de-num'), f = fav[host][b][num]; if(host !== aib.host || TNum && num === TNum && b === brd) { queue.end(qIdx); return; } el = $c('de-fav-inf-new', el); el.classList.add('de-wait'); el.textContent = ''; ajaxLoad(aib.getThrdUrl(b, num), true, function(form, xhr) { var cnt = aib.getPosts(form).length + 1 - this.previousElementSibling.textContent; this.textContent = cnt; this.classList.remove('de-wait'); if(cnt > 0) { f['new'] = cnt; update = true; } queue.end(qIdx); f = qIdx = null; }.bind(el), function(eCode, eMsg, xhr) { this.textContent = getErrorMessage(eCode, eMsg); this.classList.remove('de-wait'); queue.end(qIdx); qIdx = null; }.bind(el)); }, function() { if(update) { setStored('DESU_Favorites', JSON.stringify(fav)); } fav = queue = update = null; }); for(i = 0, els = $C('de-entry', doc), len = els.length; i < len; ++i) { queue.run(els[i]); } queue.complete(); }); }), $btn(Lng.page[lang], Lng.infoPage[lang], function() { var els = $C('de-entry', doc), i = 6, loaded = 0; $alert(Lng.loading[lang], 'load-pages', true); while(i--) { ajaxLoad(aib.getPageUrl(brd, i), true, function(idx, form, xhr) { for(var inf, el, len = this.length, i = 0; i < len; ++i) { el = this[i]; if(el.getAttribute('de-host') === aib.host && el.getAttribute('de-board') === brd) { inf = $c('de-fav-inf-page', el); if((new RegExp('(?:№|No.|>)\\s*' + el.getAttribute('de-num') + '\\s*<')) .test(form.innerHTML)) { inf.innerHTML = '@' + idx; } else if(loaded === 5 && !inf.textContent.contains('@')) { inf.innerHTML = '@?'; } } } if(loaded === 5) { closeAlert($id('de-alert-load-pages')); } loaded++; }.bind(els, i), function(eCode, eMsg, xhr) { if(loaded === 5) { closeAlert($id('de-alert-load-pages')); } loaded++; }); } }), $btn(Lng.clear[lang], Lng.clrDeleted[lang], function() { var i, len, els, queue = new $queue(4, function(qIdx, num, el) { var node = $c('de-fav-inf-old', el); node.className = 'de-wait'; ajaxLoad(el.getAttribute('de-url'), false, function() { this.classList.remove('de-wait'); queue.end(qIdx); qIdx = null; }.bind(node), function(eCode, eMsg, xhr) { if(eCode === 404) { this.textContent = getErrorMessage(eCode, eMsg); this.classList.remove('de-wait'); el.setAttribute('de-removed', ''); } queue.end(qIdx); qIdx = el = null; }.bind(node)); }, function() { queue = null; clearFavoriteTable(); }); for(i = 0, els = $C('de-entry', doc), len = els.length; i < len; ++i) { queue.run(els[i]); } queue.complete(); }), $btn(Lng.remove[lang], Lng.clrSelected[lang], function() { $each($C('de-entry', doc), function(el) { if($t('input', el).checked) { el.setAttribute('de-removed', ''); } }); clearFavoriteTable(); }) ]); if(Cfg['animation']) { cont.className = 'de-content de-cfg-open'; } } //============================================================================================================ // SETTINGS WINDOW //============================================================================================================ function fixSettings() { function toggleBox(state, arr) { var i = arr.length, nState = !state; while(i--) { ($q(arr[i], doc) || {}).disabled = nState; } } toggleBox(Cfg['ajaxUpdThr'], [ 'input[info="noErrInTitle"]', 'input[info="favIcoBlink"]', 'input[info="markNewPosts"]', 'input[info="desktNotif"]' ]); toggleBox(Cfg['expandImgs'], [ 'input[info="resizeImgs"]', 'input[info="webmControl"]', 'input[info="webmVolume"]' ]); toggleBox(Cfg['preLoadImgs'], ['input[info="findImgFile"]']); toggleBox(Cfg['openImgs'], ['input[info="openGIFs"]']); toggleBox(Cfg['linksNavig'], [ 'input[info="linksOver"]', 'input[info="linksOut"]', 'input[info="markViewed"]', 'input[info="strikeHidd"]', 'input[info="noNavigHidd"]' ]); toggleBox(Cfg['addYouTube'] && Cfg['addYouTube'] !== 4, [ 'select[info="YTubeType"]', 'input[info="YTubeHD"]', 'input[info="addVimeo"]' ]); toggleBox(Cfg['addYouTube'], [ 'input[info="YTubeWidth"]', 'input[info="YTubeHeigh"]', 'input[info="YTubeTitles"]' ]); toggleBox(Cfg['ajaxReply'], ['input[info="sendErrNotif"]', 'input[info="scrAfterRep"]']); toggleBox(Cfg['ajaxReply'] === 2, [ 'input[info="postSameImg"]', 'input[info="removeEXIF"]', 'input[info="removeFName"]' ]); toggleBox(Cfg['addTextBtns'], ['input[info="txtBtnsLoc"]']); toggleBox(Cfg['updScript'], ['select[info="scrUpdIntrv"]']); toggleBox(Cfg['keybNavig'], ['input[info="loadPages"]']); } function lBox(id, isBlock, Fn) { var el = $new('input', {'info': id, 'type': 'checkbox'}, {'click': function() { toggleCfg(this.getAttribute('info')); fixSettings(); if(Fn) { Fn(this); } }}); el.checked = Cfg[id]; return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + Lng.cfg[id][lang])]); } function inpTxt(id, size, Fn) { return $new('input', {'info': id, 'type': 'text', 'size': size, 'value': Cfg[id]}, { 'keyup': Fn ? Fn : function() { saveCfg(this.getAttribute('info'), this.value); } }); } function optSel(id, isBlock, Fn) { for(var i = 0, x = Lng.cfg[id], len = x.sel[lang].length, el, opt = ''; i < len; i++) { opt += '<option value="' + i + '">' + x.sel[lang][i] + '</option>'; } el = $add('<select info="' + id + '">' + opt + '</select>'); el.addEventListener('change', Fn || function() { saveCfg(this.getAttribute('info'), this.selectedIndex); fixSettings(); }, false); el.selectedIndex = Cfg[id]; return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + x.txt[lang])]); } function cfgTab(name) { return $New('div', {'class': aib.cReply + ' de-cfg-tab-back', 'selected': false}, [$new('div', { 'class': 'de-cfg-tab', 'text': Lng.cfgTab[name][lang], 'info': name}, { 'click': function() { var el, id, pN = this.parentNode; if(pN.getAttribute('selected') === 'true') { return; } if(el = $c('de-cfg-body', doc)) { el.className = 'de-cfg-unvis'; $q('.de-cfg-tab-back[selected="true"]', doc).setAttribute('selected', false); } pN.setAttribute('selected', true); if(!(el = $id('de-cfg-' + (id = this.getAttribute('info'))))) { $after($id('de-cfg-bar'), el = id === 'filters' ? getCfgFilters() : id === 'posts' ? getCfgPosts() : id === 'images' ? getCfgImages() : id === 'links' ? getCfgLinks() : id === 'form' ? getCfgForm() : id === 'common' ? getCfgCommon() : getCfgInfo() ); if(id === 'filters') { updRowMeter.call($id('de-spell-edit')); } } el.className = 'de-cfg-body'; if(id === 'filters') { $id('de-spell-edit').value = spells.list; } fixSettings(); } })]); } function updRowMeter() { var str, top = this.scrollTop, el = this.parentNode.previousSibling.firstChild, num = el.numLines || 1, i = 15; if(num - i < ((top / 12) | 0 + 1)) { str = ''; while(i--) { str += num++ + '<br>'; } el.insertAdjacentHTML('beforeend', str); el.numLines = num; } el.scrollTop = top; } function getCfgFilters() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-filters'}, [ lBox('hideBySpell', false, toggleSpells), $New('div', {'id': 'de-spell-panel'}, [ $new('a', { 'id': 'de-btn-addspell', 'text': Lng.add[lang], 'href': '#', 'class': 'de-abtn'}, { 'click': $pd, 'mouseover': addMenu, 'mouseout': removeMenu }), $new('a', {'text': Lng.apply[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) { $pd(e); saveCfg('hideBySpell', 1); $q('input[info="hideBySpell"]', doc).checked = true; toggleSpells(); }}), $new('a', {'text': Lng.clear[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) { $pd(e); $id('de-spell-edit').value = ''; toggleSpells(); }}), $add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Spells-' + (lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>') ]), $New('div', {'id': 'de-spell-div'}, [ $add('<div><div id="de-spell-rowmeter"></div></div>'), $New('div', null, [$new('textarea', {'id': 'de-spell-edit', 'wrap': 'off'}, { 'keydown': updRowMeter, 'scroll': updRowMeter })]) ]), lBox('sortSpells', true, function() { if(Cfg['sortSpells']) { toggleSpells(); } }), lBox('menuHiddBtn', true, null), lBox('hideRefPsts', true, null), lBox('delHiddPost', true, function() { $each($C('de-post-hide', dForm), function(el) { var wrap = el.post.wrap, hide = !wrap.classList.contains('de-hidden'); if(hide) { wrap.insertAdjacentHTML('beforebegin', '<span style="counter-increment: de-cnt 1;"></span>'); } else { $del(wrap.previousSibling); } wrap.classList.toggle('de-hidden'); }); updateCSS(); }) ]); } function getCfgPosts() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-posts'}, [ lBox('ajaxUpdThr', false, TNum ? function() { if(Cfg['ajaxUpdThr']) { updater.enable(); } else { updater.disable(); } } : null), $New('label', null, [ inpTxt('updThrDelay', 4, null), $txt(Lng.cfg['updThrDelay'][lang]) ]), $New('div', {'class': 'de-cfg-depend'}, [ lBox('noErrInTitle', true, null), lBox('favIcoBlink', true, null), lBox('markNewPosts', true, function() { firstThr.clearPostsMarks(); }), $if('Notification' in window, lBox('desktNotif', true, function() { if(Cfg['desktNotif']) { Notification.requestPermission(); } })) ]), optSel('expandPosts', true, null), optSel('postBtnsCSS', true, null), lBox('noSpoilers', true, updateCSS), lBox('noPostNames', true, updateCSS), lBox('noPostScrl', true, updateCSS), $New('div', null, [ lBox('correctTime', false, dateTime.toggleSettings), $add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Settings-time-' + (lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>') ]), $New('div', {'class': 'de-cfg-depend'}, [ $New('div', null, [ inpTxt('timeOffset', 3, null), $txt(Lng.cfg['timeOffset'][lang]) ]), $New('div', null, [ inpTxt('timePattern', 30, null), $txt(Lng.cfg['timePattern'][lang]) ]), $New('div', null, [ inpTxt('timeRPattern', 30, null), $txt(Lng.cfg['timeRPattern'][lang]) ]) ]) ]); } function getCfgImages() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-images'}, [ optSel('expandImgs', true, null), $New('div', {'style': 'padding-left: 25px;'}, [ lBox('resizeImgs', true, null), lBox('webmControl', true, null), inpTxt('webmVolume', 6, function() { var val = +this.value; saveCfg('webmVolume', val < 100 ? val : 100); }), $txt(Lng.cfg['webmVolume'][lang]) ]), $if(!nav.Presto, lBox('preLoadImgs', true, null)), $if(!nav.Presto, $New('div', {'class': 'de-cfg-depend'}, [ lBox('findImgFile', true, null) ])), lBox('openImgs', true, null), $New('div', {'class': 'de-cfg-depend'}, [ lBox('openGIFs', false, null)]), lBox('imgSrcBtns', true, null) ]); } function getCfgLinks() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-links'}, [ optSel('linksNavig', true, null), $New('div', {'class': 'de-cfg-depend'}, [ $New('div', null, [ inpTxt('linksOver', 6, function() { saveCfg('linksOver', +this.value | 0); }), $txt(Lng.cfg['linksOver'][lang]) ]), $New('div', null, [ inpTxt('linksOut', 6, function() { saveCfg('linksOut', +this.value | 0); }), $txt(Lng.cfg['linksOut'][lang]) ]), lBox('markViewed', true, null), lBox('strikeHidd', true, null), lBox('noNavigHidd', true, null) ]), lBox('crossLinks', true, null), lBox('insertNum', true, null), lBox('addMP3', true, null), lBox('addImgs', true, null), optSel('addYouTube', true, null), $New('div', {'class': 'de-cfg-depend'}, [ $New('div', null, [ optSel('YTubeType', false, null), inpTxt('YTubeWidth', 6, null), $txt('×'), inpTxt('YTubeHeigh', 6, null), $txt(' '), lBox('YTubeHD', false, null) ]), $if(!nav.Opera11 || nav.isGM, lBox('YTubeTitles', false, null)), lBox('addVimeo', true, null) ]) ]); } function getCfgForm() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-form'}, [ optSel('ajaxReply', true, null), $if(pr.form, $New('div', {'class': 'de-cfg-depend'}, [ $if(!nav.Opera11, $New('div', null, [ lBox('postSameImg', true, null), lBox('removeEXIF', false, null), lBox('removeFName', false, null), lBox('sendErrNotif', true, null) ])), lBox('scrAfterRep', true, null) ])), $if(pr.form, optSel('addPostForm', true, null)), lBox('favOnReply', true, null), $if(pr.subj, lBox('warnSubjTrip', false, null)), $if(pr.file && !aib.dobr && !nav.Presto, lBox('fileThumb', true, function() { for(var i = 0, ins = pr.fileInputs, len = ins.length; i < len; ++i) { ins[i].updateUtils(); } })), $if(pr.mail, $New('div', null, [ lBox('addSageBtn', false, null), lBox('saveSage', false, null) ])), $if(pr.capTr, optSel('captchaLang', true, null)), $if(pr.txta, $New('div', null, [ optSel('addTextBtns', false, function() { saveCfg('addTextBtns', this.selectedIndex); pr.addTextPanel(); }), lBox('txtBtnsLoc', false, pr.addTextPanel.bind(pr)) ])), $if(pr.passw, $New('div', null, [ inpTxt('passwValue', 20, PostForm.setUserPassw), $txt(Lng.cfg['userPassw'][lang]), $btn(Lng.change[lang], '', function() { $q('input[info="passwValue"]', doc).value = Math.round(Math.random() * 1e15).toString(32); PostForm.setUserPassw(); }) ])), $if(pr.name, $New('div', null, [ inpTxt('nameValue', 20, PostForm.setUserName), lBox('userName', false, PostForm.setUserName) ])), $New('div', null, [ $txt(Lng.dontShow[lang]), lBox('noBoardRule', false, updateCSS), $if(pr.gothr, lBox('noGoto', false, function() { $disp(pr.gothr); })), $if(pr.passw, lBox('noPassword', false, function() { $disp(pr.passw.parentNode.parentNode); })) ]) ]); } function getCfgCommon() { return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-common'}, [ optSel('scriptStyle', true, function() { saveCfg('scriptStyle', this.selectedIndex); $id('de-main').lang = getThemeLang(); }), $New('div', null, [ lBox('userCSS', false, updateCSS), addEditButton('css', function(Fn) { Fn(Cfg['userCSSTxt'], false, function() { saveCfg('userCSSTxt', this.value); updateCSS(); toggleContent('cfg', true); }); }) ]), lBox('attachPanel', true, function() { toggleContent('cfg', false); updateCSS(); }), lBox('panelCounter', true, updateCSS), lBox('rePageTitle', true, null), $if(nav.Anim, lBox('animation', true, null)), lBox('closePopups', true, null), $New('div', null, [ lBox('keybNavig', false, function() { if(Cfg['keybNavig']) { if(keyNav) { keyNav.enable(); } else { keyNav = new KeyNavigation(); } } else if(keyNav) { keyNav.disable(); } }), $btn(Lng.edit[lang], '', function(e) { $pd(e); if($id('de-alert-edit-keybnavig')) { return; } KeyNavigation.readKeys(function(keys) { var aEl, evtListener, temp = KeyEditListener.getEditMarkup(keys); $alert(temp[1], 'edit-keybnavig', false); aEl = $id('de-alert-edit-keybnavig'); evtListener = new KeyEditListener(aEl, keys, temp[0]); aEl.addEventListener('focus', evtListener, true); aEl.addEventListener('blur', evtListener, true); aEl.addEventListener('click', evtListener, true); aEl.addEventListener('keydown', evtListener, true); aEl.addEventListener('keyup', evtListener, true); }); }) ]), $New('div', {'class': 'de-cfg-depend'}, [ inpTxt('loadPages', 4, null), $txt(Lng.cfg['loadPages'][lang]) ]), $if(!nav.isChromeStorage && !nav.Presto || nav.isGM, $New('div', null, [ lBox('updScript', true, null), $New('div', {'class': 'de-cfg-depend'}, [ optSel('scrUpdIntrv', false, null), $btn(Lng.checkNow[lang], '', function() { $alert(Lng.loading[lang], 'updavail', true); checkForUpdates(true, function(html) { $alert(html, 'updavail', false); }); }) ]) ])), lBox('turnOff', true, function() { for(var dm in comCfg) { if(dm !== aib.dm && dm !== 'global' && dm !== 'lastUpd') { comCfg[dm]['disabled'] = Cfg['turnOff']; } } setStored('DESU_Config', JSON.stringify(comCfg) || ''); }) ]); } function getCfgInfo() { function getHiddenThrCount() { var b, tNum, count = 0; for(b in hThr) { for(tNum in hThr[b]) { count++; } } return count; } return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-info'}, [ $add('<div style="padding-bottom: 10px;">' + '<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/versions" ' + 'target="_blank">v' + version + '</a>&nbsp;|&nbsp;' + '<a href="http://www.freedollchan.org/scripts/" target="_blank">Freedollchan</a>&nbsp;|&nbsp;' + '<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/' + (lang ? 'home-en/' : '') + '" target="_blank">Github</a></div>'), $add('<div><div style="display: inline-block; vertical-align: top; width: 186px; height: 235px;">' + Lng.thrViewed[lang] + Cfg['stats']['view'] + '<br>' + Lng.thrCreated[lang] + Cfg['stats']['op'] + '<br>' + Lng.thrHidden[lang] + getHiddenThrCount() + '<br>' + Lng.postsSent[lang] + Cfg['stats']['reply'] + '</div>' + '<div style="display: inline-block; padding-left: 7px; height: 235px; ' + 'border-left: 1px solid grey;">' + new Logger().get().join('<br>') + '</div></div>'), $btn(Lng.debug[lang], Lng.infoDebug[lang], function() { $alert(Lng.infoDebug[lang] + ':<textarea readonly id="de-debug-info" class="de-editor"></textarea>', 'help-debug', false); $id('de-debug-info').value = JSON.stringify({ 'version': version, 'location': String(window.location), 'nav': nav, 'cfg': Cfg, 'sSpells': spells.list.split('\n'), 'oSpells': sesStorage['de-spells-' + brd + TNum], 'perf': new Logger().get() }, function(key, value) { if(key in defaultCfg) { if(value === defaultCfg[key] || key === 'nameValue' || key === 'passwValue') { return void 0; } } return key === 'stats' ? void 0 : value; }, '\t'); }) ]); } function addEditButton(name, getDataFn) { return $btn(Lng.edit[lang], Lng.editInTxt[lang], function(getData) { getData(function(val, isJSON, saveFn) { var ta = $new('textarea', { 'class': 'de-editor', 'value': isJSON ? JSON.stringify(val, null, '\t') : val }, null); $alert('', 'edit-' + name, false); $append($c('de-alert-msg', $id('de-alert-edit-' + name)), [ $txt(Lng.editor[name][lang]), ta, $btn(Lng.save[lang], Lng.saveChanges[lang], isJSON ? function(fun) { var data; try { data = JSON.parse(this.value.trim().replace(/[\n\r\t]/g, '') || '{}'); } finally { if(data) { fun(data); closeAlert($id('de-alert-edit-' + name)); closeAlert($id('de-alert-err-invaliddata')); } else { $alert(Lng.invalidData[lang], 'err-invaliddata', false); } } }.bind(ta, saveFn) : saveFn.bind(ta)) ]); }); }.bind(null, getDataFn)); } function addSettings(Set, id) { Set.appendChild($New('div', {'class': aib.cReply}, [ $new('div', {'id': 'de-cfg-head', 'text': 'Dollchan Extension Tools'}, null), $New('div', {'id': 'de-cfg-bar'}, [ cfgTab('filters'), cfgTab('posts'), cfgTab('images'), cfgTab('links'), $if(pr.form || pr.oeForm, cfgTab('form')), cfgTab('common'), cfgTab('info') ]), $New('div', {'id': 'de-cfg-btns'}, [ optSel('language', false, function() { saveCfg('language', lang = this.selectedIndex); $del($id('de-main')); $del($id('de-css')); $del($id('de-css-dynamic')); scriptCSS(); addPanel(); toggleContent('cfg', false); }), $New('div', {'style': 'float: right;'}, [ addEditButton('cfg', function(Fn) { Fn(Cfg, true, function(data) { saveComCfg(aib.dm, data); window.location.reload(); }); }), $if(nav.isGlobal, $btn(Lng.load[lang], Lng.loadGlobal[lang], function() { if(('global' in comCfg) && !$isEmpty(comCfg['global'])) { saveComCfg(aib.dm, null); window.location.reload(); } else { $alert(Lng.noGlobalCfg[lang], 'err-noglobalcfg', false); } })), $if(nav.isGlobal, $btn(Lng.save[lang], Lng.saveGlobal[lang], function() { var i, obj = {}, com = comCfg[aib.dm]; for(i in com) { if(com[i] !== defaultCfg[i] && i !== 'stats') { obj[i] = com[i]; } } saveComCfg('global', obj); toggleContent('cfg', true); })), $btn(Lng.reset[lang], Lng.resetCfg[lang], function() { if(confirm(Lng.conReset[lang])) { delStored('DESU_Config'); delStored('DESU_Favorites'); delStored('DESU_Posts_' + aib.dm); delStored('DESU_Threads_' + aib.dm); delStored('DESU_keys'); window.location.reload(); } }) ]), $new('div', {'style': 'clear: both;'}, null) ]) ])); $q('.de-cfg-tab[info="' + (id || 'filters') + '"]', Set).click(); } //============================================================================================================ // MENUS & POPUPS //============================================================================================================ function closeAlert(el) { if(el) { el.closeTimeout = null; if(Cfg['animation']) { nav.animEvent(el, function(node) { var p = node && node.parentNode; if(p) { p.removeChild(node); } }); el.classList.add('de-close'); } else { $del(el); } } } function $alert(txt, id, wait) { var node, el = $id('de-alert-' + id), cBtn = 'de-alert-btn' + (wait ? ' de-wait' : ''), tBtn = wait ? '' : '\u2716 '; if(el) { $t('div', el).innerHTML = txt.trim(); node = $t('span', el); node.className = cBtn; node.textContent = tBtn; clearTimeout(el.closeTimeout); if(!wait && Cfg['animation']) { nav.animEvent(el, function(node) { node.classList.remove('de-blink'); }); el.classList.add('de-blink'); } } else { el = $id('de-alert').appendChild($New('div', {'class': aib.cReply, 'id': 'de-alert-' + id}, [ $new('span', {'class': cBtn, 'text': tBtn}, {'click': function() { closeAlert(this.parentNode); }}), $add('<div class="de-alert-msg">' + txt.trim() + '</div>') ])); if(Cfg['animation']) { nav.animEvent(el, function(node) { node.classList.remove('de-open'); }); el.classList.add('de-open'); } } if(Cfg['closePopups'] && !wait && !id.contains('help') && !id.contains('edit')) { el.closeTimeout = setTimeout(closeAlert, 4e3, el); } } function showMenu(el, html, inPanel, onclick) { var y, pos, menu, cr = el.getBoundingClientRect(); if(Cfg['attachPanel'] && inPanel) { pos = 'fixed'; y = 'bottom: 25'; } else { pos = 'absolute'; y = 'top: ' + (window.pageYOffset + cr.bottom); } doc.body.insertAdjacentHTML('beforeend', '<div class="' + aib.cReply + ' de-menu" style="position: ' + pos + '; right: ' + (doc.documentElement.clientWidth - cr.right - window.pageXOffset) + 'px; ' + y + 'px;">' + html + '</div>'); menu = doc.body.lastChild; menu.addEventListener('mouseover', function(e) { clearTimeout(e.currentTarget.odelay); }, true); menu.addEventListener('mouseout', removeMenu, true); menu.addEventListener('click', function(e) { var el = e.target; if(el.className === 'de-menu-item') { this(el); do { el = el.parentElement; } while (!el.classList.contains('de-menu')); $del(el); } }.bind(onclick), false); } function addMenu(e) { e.target.odelay = setTimeout(function(el) { switch(el.id) { case 'de-btn-addspell': addSpellMenu(el); return; case 'de-btn-refresh': addAjaxPagesMenu(el); return; case 'de-btn-audio-off': addAudioNotifMenu(el); return; } }, Cfg['linksOver'], e.target); } function removeMenu(e) { var el = $c('de-menu', doc), rt = e.relatedTarget; clearTimeout(e.target.odelay); if(el && (!rt || (rt !== el && !el.contains(rt)))) { el.odelay = setTimeout($del, 75, el); } } function addSpellMenu(el) { showMenu(el, '<div style="display: inline-block; border-right: 1px solid grey;">' + '<span class="de-menu-item">' + ('#words,#exp,#exph,#imgn,#ihash,#subj,#name,#trip,#img,<br>') .split(',').join('</span><span class="de-menu-item">') + '</span></div><div style="display: inline-block;"><span class="de-menu-item">' + ('#sage,#op,#tlen,#all,#video,#vauthor,#num,#wipe,#rep,#outrep') .split(',').join('</span><span class="de-menu-item">') + '</span></div>', false, function(el) { var exp = el.textContent, idx = Spells.names.indexOf(exp.substr(1)); $txtInsert($id('de-spell-edit'), exp + ( TNum && exp !== '#op' && exp !== '#rep' && exp !== '#outrep' ? '[' + brd + ',' + TNum + ']' : '' ) + (Spells.needArg[idx] ? '(' : '')); }); } function addAjaxPagesMenu(el) { showMenu(el, '<span class="de-menu-item">' + Lng.selAjaxPages[lang].join('</span><span class="de-menu-item">') + '</span>', true, function(el) { loadPages(aProto.indexOf.call(el.parentNode.children, el) + 1); }); } function addAudioNotifMenu(el) { showMenu(el, '<span class="de-menu-item">' + Lng.selAudioNotif[lang].join('</span><span class="de-menu-item">') + '</span>', true, function(el) { var i = aProto.indexOf.call(el.parentNode.children, el); updater.enable(); updater.toggleAudio(i === 0 ? 3e4 : i === 1 ? 6e4 : i === 2 ? 12e4 : 3e5); $id('de-btn-audio-off').id = 'de-btn-audio-on'; }); } //============================================================================================================ // KEYBOARD NAVIGATION //============================================================================================================ function KeyNavigation() { KeyNavigation.readKeys(this._init.bind(this)); } KeyNavigation.version = 4; KeyNavigation.readKeys = function(Fn) { getStored('DESU_keys', function(str) { var tKeys, keys; if(!str) { this(KeyNavigation.getDefaultKeys()); return; } try { keys = JSON.parse(str); } finally { if(!keys) { this(KeyNavigation.getDefaultKeys()); return; } if(keys[0] !== KeyNavigation.version) { tKeys = KeyNavigation.getDefaultKeys(); switch(keys[0]) { case 1: keys[2][11] = tKeys[2][11]; keys[4] = tKeys[4]; case 2: keys[2][12] = tKeys[2][12]; keys[2][13] = tKeys[2][13]; keys[2][14] = tKeys[2][14]; keys[2][15] = tKeys[2][15]; keys[2][16] = tKeys[2][16]; case 3: keys[2][17] = keys[3][3]; keys[3][3] = keys[3].splice(4, 1)[0]; } keys[0] = KeyNavigation.version; setStored('DESU_keys', JSON.stringify(keys)); } if(keys[1] ^ !!nav.Firefox) { var mapFunc = nav.Firefox ? function mapFuncFF(key) { switch(key) { case 189: return 173; case 187: return 61; case 186: return 59; default: return key; } } : function mapFuncNonFF(key) { switch(key) { case 173: return 189; case 61: return 187; case 59: return 186; default: return key; } }; keys[1] = !!nav.Firefox; keys[2] = keys[2].map(mapFunc); keys[3] = keys[3].map(mapFunc); setStored('DESU_keys', JSON.stringify(keys)); } this(keys); } }.bind(Fn)); }; KeyNavigation.getDefaultKeys = function() { var isFirefox = !!nav.Firefox; var globKeys = [ /* One post/thread above */ 0x004B /* = K */, /* One post/thread below */ 0x004A /* = J */, /* Reply or create thread */ 0x0052 /* = R */, /* Hide selected thread/post */ 0x0048 /* = H */, /* Open previous page/picture */ 0x1025 /* = Ctrl+Left */, /* Send post (txt) */ 0xC00D /* = Alt+Enter */, /* Open/close favorites posts */ 0x4046 /* = Alt+F */, /* Open/close hidden posts */ 0x4048 /* = Alt+H */, /* Open/close panel */ 0x0050 /* = P */, /* Mask/unmask images */ 0x0042 /* = B */, /* Open/close settings */ 0x4053 /* = Alt+S */, /* Expand current image */ 0x0049 /* = I */, /* Bold text */ 0xC042 /* = Alt+B */, /* Italic text */ 0xC049 /* = Alt+I */, /* Strike text */ 0xC054 /* = Alt+T */, /* Spoiler text */ 0xC050 /* = Alt+P */, /* Code text */ 0xC043 /* = Alt+C */, /* Open next page/picture */ 0x1027 /* = Ctrl+Right */ ]; var nonThrKeys = [ /* One post above */ 0x004D /* = M */, /* One post below */ 0x004E /* = N */, /* Open thread */ 0x0056 /* = V */, /* Expand thread */ 0x0045 /* = E */ ]; var thrKeys = [ /* Update thread */ 0x0055 /* = U */ ]; return [KeyNavigation.version, isFirefox, globKeys, nonThrKeys, thrKeys]; }; KeyNavigation.prototype = { cPost: null, enabled: false, gKeys: null, lastPage: 0, lastPageOffset: 0, ntKeys: null, paused: false, tKeys: null, clear: function(lastPage) { this.cPost = null; this.lastPage = lastPage; this.lastPageOffset = 0; }, disable: function() { if(this.enabled) { if(this.cPost) { this.cPost.unselect(); } doc.removeEventListener('keydown', this, true); this.enabled = false; } }, enable: function() { if(!this.enabled) { this.clear(pageNum); doc.addEventListener('keydown', this, true); this.enabled = true; } }, handleEvent: function(e) { if(this.paused) { return; } var temp, post, scrollToThread, globIdx, idx, curTh = e.target.tagName, kc = e.keyCode | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) | (e.altKey ? 0x4000 : 0) | (curTh === 'TEXTAREA' || (curTh === 'INPUT' && e.target.type === 'text') ? 0x8000 : 0); if(kc === 0x74 || kc === 0x8074) { // F5 if(TNum) { return; } if(Attachment.viewer) { Attachment.viewer.close(null); Attachment.viewer = null; } loadPages(+Cfg['loadPages']); } else if(kc === 0x1B) { // ESC if(Attachment.viewer) { Attachment.viewer.close(null); Attachment.viewer = null; return; } if(this.cPost) { this.cPost.unselect(); this.cPost = null; } if(TNum) { firstThr.clearPostsMarks(); } this.lastPageOffset = 0; } else if(kc === 0x801B) { // ESC (txt) e.target.blur(); } else { globIdx = this.gKeys.indexOf(kc); switch(globIdx) { case 2: // Reply or create thread if(pr.form) { if(!this.cPost && TNum && Cfg['addPostForm'] === 3) { this.cPost = firstThr.op; } if(this.cPost) { pr.showQuickReply(this.cPost, this.cPost.num, true); } else { pr.showMainReply(Cfg['addPostForm'] === 1, null); } } break; case 3: // Hide selected thread/post post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { post.toggleUserVisib(); this._scroll(post, false, post.isOp); } break; case 4: // Open previous page/picture if(Attachment.viewer) { Attachment.viewer.navigate(false); } else if(TNum || pageNum !== aib.firstPage) { window.location.pathname = aib.getPageUrl(brd, TNum ? 0 : pageNum - 1); } break; case 5: // Send post (txt) if(e.target !== pr.txta && e.target !== pr.cap) { return; } pr.subm.click(); break; case 6: // Open/close favorites posts toggleContent('fav', false); break; case 7: // Open/close hidden posts toggleContent('hid', false); break; case 8: // Open/close panel $disp($id('de-panel').lastChild); break; case 9: // Mask/unmask images toggleCfg('maskImgs'); updateCSS(); break; case 10: // Open/close settings toggleContent('cfg', false); break; case 11: // Expand current image post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { post.toggleImages(!post.imagesExpanded); } break; case 12: // Bold text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-bold').click(); break; case 13: // Italic text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-italic').click(); break; case 14: // Strike text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-strike').click(); break; case 15: // Spoiler text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-spoil').click(); break; case 16: // Code text (txt) if(e.target !== pr.txta) { return; } $id('de-btn-code').click(); break; case 17: // Open next page/picture if(Attachment.viewer) { Attachment.viewer.navigate(true); } else if(!TNum && this.lastPage !== aib.lastPage) { window.location.pathname = aib.getPageUrl(brd, this.lastPage + 1); } break; case -1: if(TNum) { idx = this.tKeys.indexOf(kc); if(idx === 0) { // Update thread Thread.loadNewPosts(null); break; } return; } idx = this.ntKeys.indexOf(kc); if(idx === -1) { return; } else if(idx === 2) { // Open thread post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { if(nav.Firefox) { GM_openInTab(aib.getThrdUrl(brd, post.tNum), false, true); } else { window.open(aib.getThrdUrl(brd, post.tNum), '_blank'); } } break; } else if(idx === 3) { // Expand/collapse thread post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false); if(post) { if(post.thr.loadedOnce && post.thr.op.next.count === 1) { temp = post.thr.nextNotHidden; post.thr.load(visPosts, !!temp, null); post = (temp || post.thr).op; } else { post.thr.load(1, false, null); post = post.thr.op; } scrollTo(0, pageYOffset + post.topCoord); if(this.cPost && this.cPost !== post) { this.cPost.unselect(); this.cPost = post; } } break; } default: scrollToThread = !TNum && (globIdx === 0 || globIdx === 1); this._scroll(this._getFirstVisPost(scrollToThread, false), globIdx === 0 || idx === 0, scrollToThread); } } e.stopPropagation(); $pd(e); }, pause: function() { this.paused = true; }, resume: function(keys) { this.gKeys = keys[2]; this.ntKeys = keys[3]; this.tKeys = keys[4]; this.paused = false; }, _getFirstVisPost: function(getThread, getFull) { var post, tPost; if(this.lastPageOffset !== pageYOffset) { post = getThread ? firstThr : firstThr.op; while(post.topCoord < 1) { tPost = post.next; if(!tPost) { break; } post = tPost; } if(this.cPost) { this.cPost.unselect(); } this.cPost = getThread ? getFull ? post.op : post.op.prev : getFull ? post : post.prev; this.lastPageOffset = pageYOffset; } return this.cPost; }, _getNextVisPost: function(cPost, isOp, toUp) { var thr; if(isOp) { thr = cPost ? toUp ? cPost.thr.prevNotHidden : cPost.thr.nextNotHidden : firstThr.hidden ? firstThr.nextNotHidden : firstThr; return thr ? thr.op : null; } return cPost ? cPost.getAdjacentVisPost(toUp) : firstThr.hidden || firstThr.op.hidden ? firstThr.op.getAdjacentVisPost(toUp) : firstThr.op; }, _init: function(keys) { this.enabled = true; this.lastPage = pageNum; this.gKeys = keys[2]; this.ntKeys = keys[3]; this.tKeys = keys[4]; doc.addEventListener('keydown', this, true); }, _scroll: function(post, toUp, toThread) { var next = this._getNextVisPost(post, toThread, toUp); if(!next) { if(!TNum && (toUp ? pageNum > aib.firstPage : this.lastPage < aib.lastPage)) { window.location.pathname = aib.getPageUrl(brd, toUp ? pageNum - 1 : this.lastPage + 1); } return; } if(post) { post.unselect(); } if(toThread) { next.el.scrollIntoView(); } else { scrollTo(0, pageYOffset + next.el.getBoundingClientRect().top - Post.sizing.wHeight / 2 + next.el.clientHeight / 2); } this.lastPageOffset = pageYOffset; next.select(); this.cPost = next; } } function KeyEditListener(alertEl, keys, allKeys) { var j, k, i, len, aInputs = aProto.slice.call($C('de-input-key', alertEl)); for(i = 0, len = allKeys.length; i < len; ++i) { k = allKeys[i]; if(k !== 0) { for(j = i + 1; j < len; ++j) { if(k === allKeys[j]) { aInputs[i].classList.add('de-error-key'); aInputs[j].classList.add('de-error-key'); break; } } } } this.aEl = alertEl; this.keys = keys; this.initKeys = JSON.parse(JSON.stringify(keys)); this.allKeys = allKeys; this.allInputs = aInputs; this.errCount = $C('de-error-key', alertEl).length; if(this.errCount !== 0) { this.saveButton.disabled = true; } } // Browsers have different codes for these keys (see KeyNavigation.readKeys): // Firefox - '-' - 173, '=' - 61, ';' - 59 // Chrome/Opera: '-' - 189, '=' - 187, ';' - 186 KeyEditListener.keyCodes = ['',,,,,,,,'Backspace',/* Tab */,,,,'Enter',,,'Shift','Ctrl','Alt', /* Pause/Break */,/* Caps Lock */,,,,,,,/* Escape */,,,,,'Space',/* Page Up */, /* Page Down */,/* End */,/* Home */,'←','↑','→','↓',,,,,/* Insert */,/* Delete */,,'0','1','2', '3','4','5','6','7','8','9',,';',,'=',,,,'A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',/* Left WIN Key */,/* Right WIN Key */, /* Select key */,,,'Numpad 0','Numpad 1','Numpad 2','Numpad 3','Numpad 4','Numpad 5','Numpad 6', 'Numpad 7','Numpad 8','Numpad 9','Numpad *','Numpad +',,'Numpad -','Numpad .','Numpad /', /* F1 */,/* F2 */,/* F3 */,/* F4 */,/* F5 */,/* F6 */,/* F7 */,/* F8 */,/* F9 */,/* F10 */, /* F11 */,/* F12 */,,,,,,,,,,,,,,,,,,,,,/* Num Lock */,/* Scroll Lock */,,,,,,,,,,,,,,,,,,,,,,,, ,,,,'-',,,,,,,,,,,,,';','=',',','-','.','/','`',,,,,,,,,,,,,,,,,,,,,,,,,,,'[','\\',']','\'' ]; KeyEditListener.getStrKey = function(key) { var str = ''; if(key & 0x1000) { str += 'Ctrl+'; } if(key & 0x2000) { str += 'Shift+'; } if(key & 0x4000) { str += 'Alt+'; } str += KeyEditListener.keyCodes[key & 0xFFF]; return str; }; KeyEditListener.getEditMarkup = function(keys) { var allKeys = []; var html = Lng.keyNavEdit[lang] .replace(/%l/g, '<label class="de-block">') .replace(/%\/l/g, '</label>') .replace(/%i([2-4])([0-9]+)(t)?/g, function(aKeys, all, id1, id2, isText) { var key = this[+id1][+id2]; aKeys.push(key); return '<input class="de-input-key" type="text" de-id1="' + id1 + '" de-id2="' + id2 + '" size="26" value="' + KeyEditListener.getStrKey(key) + (isText ? '" de-text' : '"' ) + ' readonly></input>'; }.bind(keys, allKeys)) + '<input type="button" id="de-keys-save" value="' + Lng.save[lang] + '"></input>' + '<input type="button" id="de-keys-reset" value="' + Lng.reset[lang] + '"></input>'; return [allKeys, html]; }; KeyEditListener.setTitle = function(el, idx) { var title = el.getAttribute('de-title'); if(keyNav && idx !== -1) { title += ' [' + KeyEditListener.getStrKey(keyNav.gKeys[idx]) + ']'; } el.title = title; }; KeyEditListener.prototype = { cEl: null, cKey: -1, errorInput: false, get saveButton() { var val = $id('de-keys-save'); Object.defineProperty(this, 'saveButton', { value: val, configurable: true }); return val; }, handleEvent: function(e) { var key, keyStr, keys, str, id, temp, el = e.target; switch(e.type) { case 'blur': if(keyNav && this.errCount === 0) { keyNav.resume(this.keys); } this.cEl = null; return; case 'focus': if(keyNav) { keyNav.pause(); } this.cEl = el; return; case 'click': if(el.id === 'de-keys-reset') { this.keys = KeyNavigation.getDefaultKeys(); this.initKeys = KeyNavigation.getDefaultKeys(); if(keyNav) { keyNav.resume(this.keys); } temp = KeyEditListener.getEditMarkup(this.keys); this.allKeys = temp[0]; $c('de-alert-msg', this.aEl).innerHTML = temp[1]; this.allInputs = aProto.slice.call($C('de-input-key', this.aEl)); this.errCount = 0; delete this.saveButton; break; } else if(el.id === 'de-keys-save') { keys = this.keys; setStored('DESU_keys', JSON.stringify(keys)); } else if(el.className === 'de-alert-btn') { keys = this.initKeys; } else { return; } if(keyNav) { keyNav.resume(keys); } closeAlert($id('de-alert-edit-keybnavig')); break; case 'keydown': if(!this.cEl) { return; } key = e.keyCode; if(key === 0x1B || key === 0x2E) { // ESC, DEL this.cEl.value = ''; this.cKey = 0; this.errorInput = false; break; } keyStr = KeyEditListener.keyCodes[key]; if(keyStr == null) { this.cKey = -1; return; } str = ''; if(e.ctrlKey) { str += 'Ctrl+'; } if(e.shiftKey) { str += 'Shift+'; } if(e.altKey) { str += 'Alt+'; } if(key === 16 || key === 17 || key === 18) { this.errorInput = true; } else { this.cKey = key | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) | (e.altKey ? 0x4000 : 0) | (this.cEl.hasAttribute('de-text') ? 0x8000 : 0); this.errorInput = false; str += keyStr; } this.cEl.value = str; break; case 'keyup': var idx, rIdx, oKey, rEl, isError, el = this.cEl, key = this.cKey; if(!el || key === -1) { return; } isError = el.classList.contains('de-error-key'); if(!this.errorInput && key !== -1) { idx = this.allInputs.indexOf(el); oKey = this.allKeys[idx]; if(oKey === key) { this.errorInput = false; break; } rIdx = key === 0 ? -1 : this.allKeys.indexOf(key); this.allKeys[idx] = key; if(isError) { idx = this.allKeys.indexOf(oKey); if(idx !== -1 && this.allKeys.indexOf(oKey, idx + 1) === -1) { rEl = this.allInputs[idx]; if(rEl.classList.contains('de-error-key')) { this.errCount--; rEl.classList.remove('de-error-key'); } } if(rIdx === -1) { this.errCount--; el.classList.remove('de-error-key'); } } if(rIdx === -1) { this.keys[+el.getAttribute('de-id1')][+el.getAttribute('de-id2')] = key; if(this.errCount === 0) { this.saveButton.disabled = false; } this.errorInput = false; break; } rEl = this.allInputs[rIdx]; if(!rEl.classList.contains('de-error-key')) { this.errCount++; rEl.classList.add('de-error-key'); } } if(!isError) { this.errCount++; el.classList.add('de-error-key'); } if(this.errCount !== 0) { this.saveButton.disabled = true; } } $pd(e); } }; //============================================================================================================ // FORM SUBMIT //============================================================================================================ function getSubmitError(dc) { var i, els, el, err = '', form = $q(aib.qDForm, dc); if(dc.body.hasChildNodes() && !form) { for(i = 0, els = $Q(aib.qError, dc); el = els[i++];) { err += el.innerHTML + '\n'; } if(!(err = err.replace(/<a [^>]+>Назад.+|<br.+/, ''))) { err = Lng.error[lang] + ':\n' + dc.body.innerHTML; } err = /:null|successful|uploaded|updating|обновл|удален[о\.]/i.test(err) ? '' : err.replace(/"/g, "'"); } return err; } function checkUpload(dc) { if(aib.krau) { pr.form.action = pr.form.action.split('?')[0]; $id('postform_row_progress').style.display = 'none'; aib.btnZeroLUTime.click(); } var el, err = getSubmitError(dc); if(err) { if(pr.isQuick) { pr.setReply(true, false); } if(/captch|капч|подтвер|verifizie/i.test(err)) { pr.refreshCapImg(true); } $alert(err, 'upload', false); updater.sendErrNotif(); return; } pr.txta.value = ''; if(pr.file) { pr.delFilesUtils(); } if(pr.video) { pr.video.value = ''; } Cfg['stats'][pr.tNum ? 'reply' : 'op']++; saveComCfg(aib.dm, Cfg); if(!pr.tNum) { window.location = aib.getThrdUrl(brd, aib.getTNum($q(aib.qDForm, dc))); return; } el = !aib._55ch && !aib.belch && (aib.qPostRedir === null || $q(aib.qPostRedir, dc)) ? $q(aib.qDForm, dc) : null; if(TNum) { firstThr.clearPostsMarks(); if(el) { firstThr.loadNewFromForm(el); closeAlert($id('de-alert-upload')); if(Cfg['scrAfterRep']) { scrollTo(0, pageYOffset + firstThr.last.el.getBoundingClientRect().top); } } else { firstThr.loadNew(function(eCode, eMsg, np, xhr) { infoLoadErrors(eCode, eMsg, 0); closeAlert($id('de-alert-upload')); if(Cfg['scrAfterRep']) { scrollTo(0, pageYOffset + firstThr.last.el.getBoundingClientRect().top); } }, true); } } else { if(el) { pByNum[pr.tNum].thr.loadFromForm(visPosts, false, el); closeAlert($id('de-alert-upload')); } else { pByNum[pr.tNum].thr.load(visPosts, false, closeAlert.bind(window, $id('de-alert-upload'))); } } pr.closeQReply(); pr.refreshCapImg(false); } function endDelete() { var el = $id('de-alert-deleting'); if(el) { closeAlert(el); $alert(Lng.succDeleted[lang], 'deleted', false); } } function checkDelete(dc) { var el, i, els, len, post, tNums, num, err = getSubmitError(dc); if(err) { $alert(Lng.errDelete[lang] + err, 'deleting', false); updater.sendErrNotif(); return; } tNums = []; num = (doc.location.hash.match(/\d+/) || [null])[0]; if(num && (post = pByNum[num])) { if(!post.isOp) { post.el.className = aib.cReply; } doc.location.hash = ''; } for(i = 0, els = $Q('.' + aib.cRPost + ' input:checked', dForm), len = els.length; i < len; ++i) { el = els[i]; el.checked = false; if(!TNum && tNums.indexOf(num = aib.getPostEl(el).post.tNum) === -1) { tNums.push(num); } } if(TNum) { firstThr.clearPostsMarks(); firstThr.loadNew(function(eCode, eMsg, np, xhr) { infoLoadErrors(eCode, eMsg, 0); endDelete(); }, false); } else { tNums.forEach(function(tNum) { pByNum[tNum].thr.load(visPosts, false, endDelete); }); } } function html5Submit(form, button, fn) { this.boundary = '---------------------------' + Math.round(Math.random() * 1e11); this.data = []; this.busy = 0; this.error = false; this.url = form.action; this.fn = fn; $each($Q('input:not([type="submit"]):not([type="button"]), textarea, select', form), this.append.bind(this)); this.append(button); this.submit(); } html5Submit.prototype = { append: function(el) { var file, fName, idx, fr, pre = '--' + this.boundary + '\r\nContent-Disposition: form-data; name="' + el.name + '"'; if(el.type === 'file' && el.files.length > 0) { file = el.files[0]; fName = file.name; this.data.push(pre + '; filename="' + ( !Cfg['removeFName'] ? fName : ' ' + fName.substring(fName.lastIndexOf('.')) ) + '"\r\nContent-type: ' + file.type + '\r\n\r\n', null, '\r\n'); idx = this.data.length - 2; if(!/^image\/(?:png|jpeg)$|^video\/webm$/.test(file.type)) { this.data[idx] = file; return; } fr = new FileReader(); fr.onload = function(name, e) { var dat = this.clearImage(e.target.result, el.obj.imgFile, Cfg['postSameImg'] && String(Math.round(Math.random() * 1e6))); if(dat) { this.data[idx] = new Blob(dat); this.busy--; this.submit(); } else { this.error = true; $alert(Lng.fileCorrupt[lang] + name, 'upload', false); } }.bind(this, fName); fr.readAsArrayBuffer(file); this.busy++; } else if((el.type !== 'checkbox' && el.type !== 'radio') || el.checked) { this.data.push(pre + '\r\n\r\n' + el.value + '\r\n'); } }, submit: function() { if(this.error || this.busy !== 0) { return; } this.data.push('--' + this.boundary + '--\r\n'); $xhr({ 'method': 'POST', 'headers': {'Content-type': 'multipart/form-data; boundary=' + this.boundary}, 'data': new Blob(this.data), 'url': nav.fixLink(this.url), 'onreadystatechange': function(xhr) { if(xhr.readyState === 4) { if(xhr.status === 200) { this($DOM(xhr.responseText)); } else { $alert(xhr.status === 0 ? Lng.noConnect[lang] : 'HTTP [' + xhr.status + '] ' + xhr.statusText, 'upload', false); } } }.bind(this.fn) }); }, readExif: function(data, off, len) { var i, j, dE, tag, tgLen, xRes = 0, yRes = 0, resT = 0, dv = new DataView(data, off), le = String.fromCharCode(dv.getUint8(0), dv.getUint8(1)) !== 'MM'; if(dv.getUint16(2, le) !== 0x2A) { return null; } i = dv.getUint32(4, le); if(i > len) { return null; } for(tgLen = dv.getUint16(i, le), j = 0; j < tgLen; j++) { tag = dv.getUint16(dE = i + 2 + 12 * j, le); if(tag === 0x0128) { resT = dv.getUint16(dE + 8, le) - 1; } else if(tag === 0x011A || tag === 0x011B) { dE = dv.getUint32(dE + 8, le); if(dE > len) { return null; } if(tag === 0x11A) { xRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le)); } else { yRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le)); } } } xRes = xRes || yRes; yRes = yRes || xRes; return new Uint8Array([resT & 0xFF, xRes >> 8, xRes & 0xFF, yRes >> 8, yRes & 0xFF]); }, clearImage: function(data, extraData, rand) { var tmp, i, len, deep, val, lIdx, jpgDat, img = new Uint8Array(data), rExif = !!Cfg['removeEXIF'], rv = extraData ? rand ? [img, extraData, rand] : [img, extraData] : rand ? [img, rand] : [img]; if(!Cfg['postSameImg'] && !rExif && !extraData) { return rv; } // JPG if(img[0] === 0xFF && img[1] === 0xD8) { for(i = 2, deep = 1, len = img.length - 1, val = [null, null], lIdx = 2, jpgDat = null; i < len; ) { if(img[i] === 0xFF) { if(rExif) { if(!jpgDat && deep === 1) { if(img[i + 1] === 0xE1 && img[i + 4] === 0x45) { jpgDat = this.readExif(data, i + 10, (img[i + 2] << 8) + img[i + 3]); } else if(img[i + 1] === 0xE0 && img[i + 7] === 0x46 && (img[i + 2] !== 0 || img[i + 3] >= 0x0E || img[i + 15] !== 0xFF)) { jpgDat = img.subarray(i + 11, i + 16); } } if((img[i + 1] >> 4) === 0xE || img[i + 1] === 0xFE) { if(lIdx !== i) { val.push(img.subarray(lIdx, i)); } i += 2 + (img[i + 2] << 8) + img[i + 3]; lIdx = i; continue; } } else if(img[i + 1] === 0xD8) { deep++; i++; continue; } if(img[i + 1] === 0xD9 && --deep === 0) { break; } } i++; } i += 2; if(!extraData && len - i > 75) { i = len; } if(lIdx === 2) { if(i !== len) { rv[0] = new Uint8Array(data, 0, i); } return rv; } val[0] = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0, 0, 0x0E, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1]); val[1] = jpgDat || new Uint8Array([0, 0, 1, 0, 1]); val.push(img.subarray(lIdx, i)); if(extraData) { val.push(extraData); } if(rand) { val.push(rand); } return val; } // PNG if(img[0] === 0x89 && img[1] === 0x50) { for(i = 0, len = img.length - 7; i < len && (img[i] !== 0x49 || img[i + 1] !== 0x45 || img[i + 2] !== 0x4E || img[i + 3] !== 0x44); i++) {} i += 8; if(i !== len && (extraData || len - i <= 75)) { rv[0] = new Uint8Array(data, 0, i); } return rv; } // WEBM if(img[0] === 0x1a && img[1] === 0x45 && img[2] === 0xDF && img[3] === 0xA3) { return new WebmParser(data).addData(rand).getData(); } return null; } }; WebmParser = function(data) { var EBMLId = 0x1A45DFA3, segmentId = 0x18538067, voidId = 0xEC; function WebmElement(data, dataLength, offset) { var num, clz, id, size, headSize = 0; if(offset + 4 >= dataLength) { return; } num = data.getUint32(offset); clz = Math.clz32(num); if(clz > 3) { this.error = true; return; } id = num >>> (8 * (3 - clz)); headSize += clz + 1; offset += clz + 1; if(offset + 4 >= dataLength) { this.error = true; return; } num = data.getUint32(offset); clz = Math.clz32(num); if(clz > 3) { if((num & (0xFFFFFFFF >>> (clz + 1))) !== 0) { this.error = true; return; // We cannot handle webm-files with size greater than 4Gb :( } if(offset + 8 >= dataLength) { this.error = true; return; } headSize += 4; offset += 4; num = data.getUint32(offset); clz -= 4; } size = num >>> (8 * (3 - clz)); headSize += clz + 1; offset += clz + 1; if(offset + size > dataLength) { this.error = true; return; } this.data = data; this.offset = offset; this.endOffset = offset + size; this.id = id; this.headSize = headSize; this.size = size; } WebmElement.prototype = { error: false, id: 0 }; function Parser(data) { var dv = new DataView(data), len = data.byteLength, el = new WebmElement(dv, len, 0), offset = 0, voids = []; error: do { if(el.error || el.id !== EBMLId) { break; } this.EBML = el; offset += el.headSize + el.size; while(true) { el = new WebmElement(dv, len, offset); if(el.error) { break error; } if(el.id === segmentId) { this.segment = el; break; // Ignore everything after first segment } else if(el.id === voidId) { voids.push(el); } else { break error; } offset += el.headSize + el.size; } this.voids = voids; this.data = data; this.length = len; this.rv = [null]; this.error = false; return; } while(false); this.error = true; } Parser.prototype = { addData: function(data) { if(this.error || !data) { return this; } var size = typeof data === 'string' ? data.length : data.byteLength; if(size > 127) { this.error = true; return; } this.rv.push(new Uint8Array([voidId, 0x80 | size]), data); return this; }, getData: function() { if(this.error) { return null; } var len = this.segment.endOffset; this.rv[0] = len === this.length ? this.data : new Uint8Array(this.data, 0, len); return this.rv; } }; WebmParser = Parser; return new Parser(data); } //============================================================================================================ // CONTENT FEATURES //============================================================================================================ function initMessageFunctions() { window.addEventListener('message', function(e) { var temp, data = e.data.substring(1); switch(e.data[0]) { case 'A': if(data.substr(10, 5) === 'pform') { checkUpload($DOM(data.substr(15))); $q('iframe[name="de-iframe-pform"]', doc).src = 'about:blank'; } else { checkDelete($DOM(data.substr(15))); $q('iframe[name="de-iframe-dform"]', doc).src = 'about:blank'; } return; case 'B': $del($id('de-fav-wait')); $id('de-iframe-fav').style.height = data + 'px'; return; } }, false); } function detectImgFile(ab) { var i, j, dat = new Uint8Array(ab), len = dat.length; /* JPG [ff d8 ff e0] = [яШяа] */ if(dat[0] === 0xFF && dat[1] === 0xD8) { for(i = 0, j = 0; i < len - 1; i++) { if(dat[i] === 0xFF) { /* Built-in JPG */ if(dat[i + 1] === 0xD8) { j++; /* JPG end [ff d9] */ } else if(dat[i + 1] === 0xD9 && --j === 0) { i += 2; break; } } } /* PNG [89 50 4e 47] = [‰PNG] */ } else if(dat[0] === 0x89 && dat[1] === 0x50) { for(i = 0; i < len - 7; i++) { /* PNG end [49 45 4e 44 ae 42 60 82] */ if(dat[i] === 0x49 && dat[i + 1] === 0x45 && dat[i + 2] === 0x4E && dat[i + 3] === 0x44) { i += 8; break; } } } else { return {}; } /* Ignore small files */ if(i !== len && len - i > 60) { for(len = i + 90; i < len; i++) { /* 7Z [37 7a bc af] = [7zјЇ] */ if(dat[i] === 0x37 && dat[i + 1] === 0x7A && dat[i + 2] === 0xBC) { return {'type': 0, 'idx': i, 'data': ab}; /* ZIP [50 4b 03 04] = [PK..] */ } else if(dat[i] === 0x50 && dat[i + 1] === 0x4B && dat[i + 2] === 0x03) { return {'type': 1, 'idx': i, 'data': ab}; /* RAR [52 61 72 21] = [Rar!] */ } else if(dat[i] === 0x52 && dat[i + 1] === 0x61 && dat[i + 2] === 0x72) { return {'type': 2, 'idx': i, 'data': ab}; /* OGG [4f 67 67 53] = [OggS] */ } else if(dat[i] === 0x4F && dat[i + 1] === 0x67 && dat[i + 2] === 0x67) { return {'type': 3, 'idx': i, 'data': ab}; /* MP3 [0x49 0x44 0x33] = [ID3] */ } else if(dat[i] === 0x49 && dat[i + 1] === 0x44 && dat[i + 2] === 0x33) { return {'type': 4, 'idx': i, 'data': ab}; } } } return {}; } function workerQueue(mReqs, wrkFn, errFn) { if(!nav.hasWorker) { this.run = this._runSync.bind(wrkFn); return; } this.queue = new $queue(mReqs, this._createWrk.bind(this), null); this.run = this._runWrk; this.wrks = new $workers('self.onmessage = function(e) {\ var info = (' + String(wrkFn) + ')(e.data[1]);\ if(info.data) {\ self.postMessage([e.data[0], info], [info.data]);\ } else {\ self.postMessage([e.data[0], info]);\ }\ }', mReqs); this.errFn = errFn; } workerQueue.prototype = { _runSync: function(data, transferObjs, Fn) { Fn(this(data)); }, onMess: function(Fn, e) { this.queue.end(e.data[0]); Fn(e.data[1]); }, onErr: function(qIdx, e) { this.queue.end(qIdx); this.errFn(e); }, _runWrk: function(data, transObjs, Fn) { this.queue.run([data, transObjs, this.onMess.bind(this, Fn)]); }, _createWrk: function(qIdx, num, data) { var w = this.wrks[qIdx]; w.onmessage = data[2]; w.onerror = this.onErr.bind(this, qIdx); w.postMessage([qIdx, data[0]], data[1]); }, clear: function() { this.wrks && this.wrks.clear(); this.wrks = null; } }; function addImgFileIcon(fName, info) { var app, ext, type = info['type']; if(typeof type !== 'undefined') { if(type === 2) { app = 'application/x-rar-compressed'; ext = 'rar'; } else if(type === 1) { app = 'application/zip'; ext = 'zip'; } else if(type === 0) { app = 'application/x-7z-compressed'; ext = '7z'; } else if(type === 3) { app = 'audio/ogg'; ext = 'ogg'; } else { app = 'audio/mpeg'; ext = 'mp3'; } this.insertAdjacentHTML('afterend', '<a href="' + window.URL.createObjectURL( new Blob([new Uint8Array(info['data']).subarray(info['idx'])], {'type': app}) ) + '" class="de-img-' + (type > 2 ? 'audio' : 'arch') + '" title="' + Lng.downloadFile[lang] + '" download="' + fName.substring(0, fName.lastIndexOf('.')) + '.' + ext + '">.' + ext + '</a>' ); } } function downloadImgData(url, Fn) { downloadObjInfo(Fn, { 'method': 'GET', 'url': url, 'onreadystatechange': function onDownloaded(url, e) { if(e.readyState !== 4) { return; } var isAb = e.responseType === 'arraybuffer'; if(e.status === 0 && isAb) { Fn(new Uint8Array(e.response)); } else if(e.status !== 200) { if(e.status === 404 || !url) { Fn(null); } else { downloadObjInfo(Fn, { 'method': 'GET', 'url': url, 'onreadystatechange': onDownloaded.bind(null, null) }); } } else if(isAb) { Fn(new Uint8Array(e.response)); } else { for(var len, i = 0, txt = e.responseText, rv = new Uint8Array(len = txt.length); i < len; ++i) { rv[i] = txt.charCodeAt(i) & 0xFF; } Fn(rv); } }.bind(null, url) }); } function downloadObjInfo(Fn, obj) { if(aib.fch && nav.Firefox && !obj.url.startsWith('blob')) { obj['overrideMimeType'] = 'text/plain; charset=x-user-defined'; GM_xmlhttpRequest(obj); } else { obj['responseType'] = 'arraybuffer'; try { $xhr(obj); } catch(e) { Fn(null); } } } function preloadImages(post) { if(!Cfg['preLoadImgs'] && !Cfg['openImgs'] && !isPreImg) { return; } var lnk, url, iType, nExp, el, i, len, els, queue, mReqs = post ? 1 : 4, cImg = 1, rjf = (isPreImg || Cfg['findImgFile']) && new workerQueue(mReqs, detectImgFile, function(e) { console.error("FILE DETECTOR ERROR, line: " + e.lineno + " - " + e.message); }); if(isPreImg || Cfg['preLoadImgs']) { queue = new $queue(mReqs, function(qIdx, num, dat) { downloadImgData(dat[0], function(idx, data) { if(data) { var a = this[1], fName = this[0].substring(this[0].lastIndexOf("/") + 1), aEl = $q(aib.qImgLink, aib.getImgWrap(a)); aEl.setAttribute('download', fName); a.href = window.URL.createObjectURL(new Blob([data], {'type': this[2]})); a.setAttribute('de-name', fName); if(this[2] === 'video/webm') { this[4].setAttribute('de-video', ''); } if(this[3]) { this[4].src = a.href; } if(rjf) { rjf.run(data.buffer, [data.buffer], addImgFileIcon.bind(aEl, fName)); } } queue.end(idx); if(Images_.progressId) { $alert(Lng.loadImage[lang] + cImg + '/' + len, Images_.progressId, true); } cImg++; }.bind(dat, qIdx)); }, function() { Images_.preloading = false; if(Images_.afterpreload) { Images_.afterpreload(); Images_.afterpreload = Images_.progressId = null; } rjf && rjf.clear(); rjf = queue = cImg = len = null; }); Images_.preloading = true; } for(i = 0, els = $Q(aib.qThumbImages, post || dForm), len = els.length; i < len; i++) { if(lnk = getAncestor(el = els[i], 'A')) { url = lnk.href; nExp = !!Cfg['openImgs']; if(/\.gif$/i.test(url)) { iType = 'image/gif'; } else { if(/\.jpe?g$/i.test(url)) { iType = 'image/jpeg'; } else if(/\.png$/i.test(url)) { iType = 'image/png'; } else if(/\.webm$/i.test(url)) { iType = 'video/webm'; nExp = false; } else { continue; } nExp &= !Cfg['openGIFs']; } if(queue) { queue.run([url, lnk, iType, nExp, el]); } else if(nExp) { el.src = url; // ! } } } queue && queue.complete(); } function getDataFromImg(img) { var cnv = Images_.canvas || (Images_.canvas = doc.createElement('canvas')); cnv.width = img.width; cnv.height = img.height; cnv.getContext('2d').drawImage(img, 0, 0); return new Uint8Array(atob(cnv.toDataURL("image/png").split(',')[1]).split('').map(function(a) { return a.charCodeAt(); })); } function loadDocFiles(imgOnly) { var els, files, progress, counter, count = 0, current = 1, warnings = '', tar = new $tar(), dc = imgOnly ? doc : doc.documentElement.cloneNode(true); Images_.queue = new $queue(4, function(qIdx, num, dat) { downloadImgData(dat[0], function(idx, data) { var name = this[1].replace(/[\\\/:*?"<>|]/g, '_'), el = this[2]; progress.value = current; counter.innerHTML = current; current++; if(this[3]) { if(!data) { warnings += '<br>' + Lng.cantLoad[lang] + '<a href="' + this[0] + '">' + this[0] + '</a><br>' + Lng.willSavePview[lang]; $alert(Lng.loadErrors[lang] + warnings, 'floadwarn', false); name = 'thumb-' + name.replace(/\.[a-z]+$/, '.png'); data = getDataFromImg(this[2]); } if(!imgOnly) { el.classList.add('de-thumb'); el.src = this[3].href = $q(aib.qImgLink, aib.getImgWrap(this[3])).href = name = 'images/' + name; } tar.addFile(name, data); } else if(data && data.length > 0) { tar.addFile(el.href = el.src = 'data/' + name, data); } else { $del(el); } Images_.queue.end(idx); }.bind(dat, qIdx)); }, function() { var u, a, dt; if(!imgOnly) { dt = doc.doctype; $t('head', dc).insertAdjacentHTML('beforeend', '<script type="text/javascript" src="data/dollscript.js"></script>'); tar.addString('data/dollscript.js', '(' + String(de_main_func) + ')(null, true);'); tar.addString( TNum + '.html', '<!DOCTYPE ' + dt.name + (dt.publicId ? ' PUBLIC "' + dt.publicId + '"' : dt.systemId ? ' SYSTEM' : '') + (dt.systemId ? ' "' + dt.systemId + '"' : '') + '>' + dc.outerHTML ); } u = window.URL.createObjectURL(tar.get()); a = $new('a', {'href': u, 'download': aib.dm + '-' + brd.replace(/[\\\/:*?"<>|]/g, '') + '-t' + TNum + (imgOnly ? '-images.tar' : '.tar')}, null); doc.body.appendChild(a); a.click(); setTimeout(function(el, url) { window.URL.revokeObjectURL(url); $del(el); }, 0, a, u); $del($id('de-alert-filesload')); Images_.queue = tar = warnings = count = current = imgOnly = progress = counter = null; }); els = aProto.slice.call($Q(aib.qThumbImages, $q('[de-form]', dc))); count += els.length; els.forEach(function(el) { var lnk, url; if(lnk = getAncestor(el, 'A')) { url = lnk.href; Images_.queue.run([url, lnk.getAttribute('de-name') || url.substring(url.lastIndexOf("/") + 1), el, lnk]); } }); if(!imgOnly) { files = []; $each($Q('script, link[rel="alternate stylesheet"], span[class^="de-btn-"],' + ' #de-main > div, .de-parea, #de-qarea, ' + aib.qPostForm, dc), $del); $each($T('a', dc), function(el) { var num, tc = el.textContent; if(tc[0] === '>' && tc[1] === '>' && (num = +tc.substr(2)) && (num in pByNum)) { el.href = aib.anchor + num; } else { el.href = getAbsLink(el.href); } if(!el.classList.contains('de-preflink')) { el.className = 'de-preflink ' + el.className; } }); $each($Q('.' + aib.cRPost, dc), function(post, i) { post.setAttribute('de-num', i === 0 ? TNum : aib.getPNum(post)); }); $each($Q('link, *[src]', dc), function(el) { if(els.indexOf(el) !== -1) { return; } var temp, i, ext, name, url = el.tagName === 'LINK' ? el.href : el.src; if(!this.test(url)) { $del(el); return; } name = url.substring(url.lastIndexOf("/") + 1).replace(/[\\\/:*?"<>|]/g, '_') .toLowerCase(); if(files.indexOf(name) !== -1) { temp = url.lastIndexOf('.'); ext = url.substring(temp); url = url.substring(0, temp); name = name.substring(0, name.lastIndexOf('.')); for(i = 0; ; ++i) { temp = name + '(' + i + ')' + ext; if(files.indexOf(temp) === -1) { break; } } name = temp; } files.push(name); Images_.queue.run([url, name, el, null]); count++; }.bind(new RegExp('^\\/\\/?|^https?:\\/\\/([^\\/]*\.)?' + regQuote(aib.dm) + '\\/', 'i'))); } $alert((imgOnly ? Lng.loadImage[lang] : Lng.loadFile[lang]) + '<br><progress id="de-loadprogress" value="0" max="' + count + '"></progress> <span>1</span>/' + count, 'filesload', true); progress = $id('de-loadprogress'); counter = progress.nextElementSibling; Images_.queue.complete(); els = null; } //============================================================================================================ // TIME CORRECTION //============================================================================================================ function dateTime(pattern, rPattern, diff, dtLang, onRPat) { if(dateTime.checkPattern(pattern)) { this.disabled = true; return; } this.regex = pattern .replace(/(?:[sihdny]\?){2,}/g, function() { return '(?:' + arguments[0].replace(/\?/g, '') + ')?'; }) .replace(/\-/g, '[^<]') .replace(/\+/g, '[^0-9]') .replace(/([sihdny]+)/g, '($1)') .replace(/[sihdny]/g, '\\d') .replace(/m|w/g, '([a-zA-Zа-яА-Я]+)'); this.pattern = pattern.replace(/[\?\-\+]+/g, '').replace(/([a-z])\1+/g, '$1'); this.diff = parseInt(diff, 10); this.sDiff = (this.diff < 0 ? '' : '+') + this.diff; this.arrW = Lng.week[dtLang]; this.arrM = Lng.month[dtLang]; this.arrFM = Lng.fullMonth[dtLang]; this.rPattern = rPattern; this.onRPat = onRPat; } dateTime.toggleSettings = function(el) { if(el.checked && (!/^[+-]\d{1,2}$/.test(Cfg['timeOffset']) || dateTime.checkPattern(Cfg['timePattern']))) { $alert(Lng.cTimeError[lang], 'err-correcttime', false); saveCfg('correctTime', 0); el.checked = false; } }; dateTime.checkPattern = function(val) { return !val.contains('i') || !val.contains('h') || !val.contains('d') || !val.contains('y') || !(val.contains('n') || val.contains('m')) || /[^\?\-\+sihdmwny]|mm|ww|\?\?|([ihdny]\?)\1+/.test(val); }; dateTime.prototype = { getRPattern: function(txt) { var k, p, a, str, i = 1, j = 0, m = txt.match(new RegExp(this.regex)); if(!m) { this.disabled = true; return false; } this.rPattern = ''; str = m[0]; while(a = m[i++]) { p = this.pattern[i - 2]; if((p === 'm' || p === 'y') && a.length > 3) { p = p.toUpperCase(); } k = str.indexOf(a, j); this.rPattern += str.substring(j, k) + '_' + p; j = k + a.length; } this.onRPat && this.onRPat(this.rPattern); return true; }, pad2: function(num) { return num < 10 ? '0' + num : num; }, fix: function(txt) { if(this.disabled || (!this.rPattern && !this.getRPattern(txt))) { return txt; } return txt.replace(new RegExp(this.regex, 'g'), function() { var i, a, t, second, minute, hour, day, month, year, dtime; for(i = 1; i < 8; i++) { a = arguments[i]; t = this.pattern[i - 1]; t === 's' ? second = a : t === 'i' ? minute = a : t === 'h' ? hour = a : t === 'd' ? day = a : t === 'n' ? month = a - 1 : t === 'y' ? year = a : t === 'm' && ( month = /^янв|^jan/i.test(a) ? 0 : /^фев|^feb/i.test(a) ? 1 : /^мар|^mar/i.test(a) ? 2 : /^апр|^apr/i.test(a) ? 3 : /^май|^may/i.test(a) ? 4 : /^июн|^jun/i.test(a) ? 5 : /^июл|^jul/i.test(a) ? 6 : /^авг|^aug/i.test(a) ? 7 : /^сен|^sep/i.test(a) ? 8 : /^окт|^oct/i.test(a) ? 9 : /^ноя|^nov/i.test(a) ? 10 : /^дек|^dec/i.test(a) && 11 ); } dtime = new Date(year.length === 2 ? '20' + year : year, month, day, hour, minute, second || 0); dtime.setHours(dtime.getHours() + this.diff); return this.rPattern .replace('_o', this.sDiff) .replace('_s', this.pad2(dtime.getSeconds())) .replace('_i', this.pad2(dtime.getMinutes())) .replace('_h', this.pad2(dtime.getHours())) .replace('_d', this.pad2(dtime.getDate())) .replace('_w', this.arrW[dtime.getDay()]) .replace('_n', this.pad2(dtime.getMonth() + 1)) .replace('_m', this.arrM[dtime.getMonth()]) .replace('_M', this.arrFM[dtime.getMonth()]) .replace('_y', ('' + dtime.getFullYear()).substring(2)) .replace('_Y', dtime.getFullYear()); }.bind(this)); } }; //============================================================================================================ // PLAYERS //============================================================================================================ YouTube = new function() { var instance, vData, embedType, videoType, width, height, isHD, loadTitles, vimReg = /^https?:\/\/(?:www\.)?vimeo\.com\/(?:[^\?]+\?clip_id=)?(\d+).*?$/; function addThumb(el, m, isYtube) { var wh = ' width="' + width + '" height="' + height + '"></a>'; if(isYtube) { el.innerHTML = '<a href="https://www.youtube.com/watch?v=' + m[1] + '" target="_blank">' + '<img class="de-video-thumb de-ytube" src="https://i.ytimg.com/vi/' + m[1] + '/0.jpg"' + wh; } else { el.innerHTML = '<a href="https://vimeo.com/' + m[1] + '" target="_blank">' + '<img class="de-video-thumb de-vimeo" src=""' + wh; GM_xmlhttpRequest({ 'method': 'GET', 'url': 'http://vimeo.com/api/v2/video/' + m[1] + '.json', 'onload': function(xhr){ this.setAttribute('src', JSON.parse(xhr.responseText)[0]['thumbnail_large']); }.bind(el.firstChild.firstChild) }); } } function addPlayer(el, m, isYtube) { var time, id = m[1], wh = ' width="' + width + '" height="' + height + '">'; if(isYtube) { time = (m[2] ? m[2] * 3600 : 0) + (m[3] ? m[3] * 60 : 0) + (m[4] ? +m[4] : 0); el.innerHTML = videoType === 1 ? '<iframe type="text/html" src="//www.youtube.com/embed/' + id + (isHD ? '?hd=1&' : '?') + 'start=' + time + '&html5=1&rel=0" frameborder="0"' + wh : '<embed type="application/x-shockwave-flash" src="https://www.youtube.com/v/' + id + (isHD ? '?hd=1&' : '?') + 'start=' + time + '" allowfullscreen="true" wmode="transparent"' + wh; } else { el.innerHTML = videoType === 1 ? '<iframe src="//player.vimeo.com/video/' + id + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen' + wh : '<embed type="application/x-shockwave-flash" src="http://vimeo.com/moogaloop.swf?clip_id=' + id + '&server=vimeo.com&color=00adef&fullscreen=1" ' + 'allowscriptaccess="always" allowfullscreen="true"' + wh; } } function addLink(post, m, loader, link, isYtube) { var msg, src, time, dataObj; post.hasYTube = true; if(post.ytInfo === null) { if(embedType === 2) { addPlayer(post.ytObj, post.ytInfo = m, isYtube); } else if(embedType > 2) { addThumb(post.ytObj, post.ytInfo = m, isYtube); } } else if(!link && $q('.de-video-link[href*="' + m[1] + '"]', post.msg)) { return; } if(loader && (dataObj = vData[m[1]])) { post.ytData.push(dataObj); } if(m[4] || m[3] || m[2]) { if(m[4] >= 60) { m[3] = (m[3] || 0) + Math.floor(m[4] / 60); m[4] %= 60; } if(m[3] >= 60) { m[2] = (m[2] || 0) + Math.floor(m[3] / 60); m[3] %= 60; } time = (m[2] ? m[2] + 'h' : '') + (m[3] ? m[3] + 'm' : '') + (m[4] ? m[4] + 's' : ''); } if(link) { link.href = link.href.replace(/^http:/, 'https:'); if(time) { link.setAttribute('de-time', time); } if(dataObj) { link.textContent = dataObj[0]; link.className = 'de-video-link de-ytube de-video-title'; link.setAttribute('de-author', dataObj[1]); link.title = Lng.author[lang] + dataObj[1] + ', ' + Lng.views[lang] + dataObj[2] + ', ' + Lng.published[lang] + dataObj[3]; } else { link.className = 'de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo'); } } else { src = isYtube ? 'https://www.youtube.com/watch?v=' + m[1] + (time ? '#t=' + time : '') : 'https://vimeo.com/' + m[1]; post.msg.insertAdjacentHTML('beforeend', '<p class="de-video-ext"><a class="de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo') + (dataObj ? ' de-video-title" title="' + Lng.author[lang] + dataObj[1] + ', ' + Lng.views[lang] + dataObj[2] + ', ' + Lng.published[lang] + dataObj[3] + '" de-author="' + dataObj[1] : '') + (time ? '" de-time="' + time : '') + '" href="' + src + '">' + (dataObj ? dataObj[0] : src) + '</a></p>'); link = post.msg.lastChild.firstChild; } if(!post.ytInfo || post.ytInfo === m) { post.ytLink = link; } link.ytInfo = m; if(loader && !dataObj) { post.ytLinksLoading++; loader.run([post, link, m[1]]); } } function getYtubeTitleLoader() { var queueEnd, queue = new $queue(4, function(qIdx, num, data) { if(num % 30 === 0) { queue.pause(); setTimeout(queue.continue.bind(queue), 3e3); } GM_xmlhttpRequest({ 'method': 'GET', 'url': 'https://gdata.youtube.com/feeds/api/videos/' + data[2] + '?alt=json&fields=title/text(),author/name,yt:statistics/@viewCount,published', 'onreadystatechange': function(idx, xhr) { if(xhr.readyState !== 4) { return; } var entry, title, author, views, publ, data, post = this[0], link = this[1]; try { if(xhr.status === 200) { entry = JSON.parse(xhr.responseText)['entry']; title = entry['title']['$t']; author = entry['author'][0]['name']['$t']; views = entry['yt$statistics']['viewCount']; publ = entry['published']['$t'].substr(0, 10); } } finally { if(title) { link.textContent = title; link.setAttribute('de-author', author); link.classList.add('de-video-title'); link.title = Lng.author[lang] + author + ', ' + Lng.views[lang] + views + ', ' + Lng.published[lang] + publ; vData[this[2]] = data = [title, author, views, publ]; post.ytData.push(data); post.ytLinksLoading--; if(post.ytHideFun !== null) { post.ytHideFun(data); } } setTimeout(queueEnd, 250, idx); } }.bind(data, qIdx) }); }, function() { sesStorage['de-ytube-data'] = JSON.stringify(vData); queue = queueEnd = null; }); queueEnd = queue.end.bind(queue); return queue; } function YouTubeSingleton() { if(instance) { return instance; } instance = this; embedType = Cfg['addYouTube']; if(embedType === 0) { this.parseLinks = emptyFn; this.updatePost = emptyFn; } loadTitles = Cfg['YTubeTitles']; if(loadTitles) { vData = JSON.parse(sesStorage['de-ytube-data'] || '{}'); } videoType = Cfg['YTubeType']; width = Cfg['YTubeWidth']; height = Cfg['YTubeHeigh']; isHD = Cfg['YTubeHD']; } YouTubeSingleton.prototype = { embedType: embedType, ytReg: /^https?:\/\/(?:www\.|m\.)?youtu(?:be\.com\/(?:watch\?.*?v=|v\/|embed\/)|\.be\/)([^&#?]+).*?(?:t(?:ime)?=(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?)?$/, vData: vData, addPlayer: addPlayer, addThumb: addThumb, parseLinks: function(post) { var i, len, els, el, src, m, embedTube = [], loader = loadTitles && getYtubeTitleLoader(); for(i = 0, els = $Q('embed, object, iframe', post ? post.el : dForm), len = els.length; i < len; ++i) { el = els[i]; src = el.src || el.data; if(m = src.match(this.ytReg)) { embedTube.push(post || aib.getPostEl(el).post, m, true); $del(el); } if(Cfg['addVimeo'] && (m = src.match(vimReg))) { embedTube.push(post || aib.getPostEl(el).post, m, false); $del(el); } } for(i = 0, els = $Q('a[href*="youtu"]', post ? post.el : dForm), len = els.length; i < len; ++i) { el = els[i]; if(m = el.href.match(this.ytReg)) { addLink(post || aib.getPostEl(el).post, m, loader, el, true); } } if(Cfg['addVimeo']) { for(i = 0, els = $Q('a[href*="vimeo.com"]', post ? post.el : dForm), len = els.length; i < len; ++i) { el = els[i]; if(m = el.href.match(vimReg)) { addLink(post || aib.getPostEl(el).post, m, null, el, false); } } } for(i = 0, len = embedTube.length; i < len; i += 3) { addLink(embedTube[i], embedTube[i + 1], loader, null, embedTube[i + 2]); } loader && loader.complete(); }, updatePost: function(post, oldLinks, newLinks, cloned) { var i, j, el, link, m, loader = !cloned && loadTitles && getYtubeTitleLoader(), len = newLinks.length; for(i = 0, j = 0; i < len; i++) { el = newLinks[i]; link = oldLinks[j]; if(link && link.classList.contains('de-current')) { post.ytLink = el; } if(cloned) { el.ytInfo = link.ytInfo; j++; } else if(m = el.href.match(this.ytReg)) { addLink(post, m, loader, el, true); j++; } } post.ytLink = post.ytLink || newLinks[0]; loader && loader.complete(); } }; return YouTubeSingleton; }; function embedMP3Links(post) { var el, link, src, i, els, len; if(!Cfg['addMP3']) { return; } for(i = 0, els = $Q('a[href*=".mp3"]', post ? post.el : dForm), len = els.length; i < len; ++i) { link = els[i]; if(link.target !== '_blank' && link.rel !== 'nofollow') { continue; } src = link.href; el = (post || aib.getPostEl(link).post).mp3Obj; if(nav.canPlayMP3) { if(!$q('audio[src="' + src + '"]', el)) { el.insertAdjacentHTML('beforeend', '<p><audio src="' + src + '" preload="none" controls></audio></p>'); link = el.lastChild.firstChild; link.addEventListener('play', updater.addPlayingTag, false); link.addEventListener('pause', updater.removePlayingTag, false); } } else if(!$q('object[FlashVars*="' + src + '"]', el)) { el.insertAdjacentHTML('beforeend', '<object data="http://junglebook2007.narod.ru/audio/player.swf" type="application/x-shockwave-flash" wmode="transparent" width="220" height="16" FlashVars="playerID=1&amp;bg=0x808080&amp;leftbg=0xB3B3B3&amp;lefticon=0x000000&amp;rightbg=0x808080&amp;rightbghover=0x999999&amp;rightcon=0x000000&amp;righticonhover=0xffffff&amp;text=0xffffff&amp;slider=0x222222&amp;track=0xf5f5dc&amp;border=0x666666&amp;loader=0x7fc7ff&amp;loop=yes&amp;autostart=no&amp;soundFile=' + src + '"><br>'); } } } //============================================================================================================ // AJAX //============================================================================================================ function ajaxLoad(url, loadForm, Fn, errFn) { return GM_xmlhttpRequest({ 'method': 'GET', 'url': nav.fixLink(url), 'onreadystatechange': function(xhr) { if(xhr.readyState !== 4) { return; } if(xhr.status !== 200) { if(errFn) { errFn(xhr.status, xhr.statusText, this); } } else if(Fn) { do { var el, text = xhr.responseText; if((aib.futa ? /<!--gz-->$/ : /<\/html?>[\s\n\r]*$/).test(text)) { el = $DOM(text); if(!loadForm || (el = $q(aib.qDForm, el))) { Fn(el, this); break; } } if(errFn) { errFn(0, Lng.errCorruptData[lang], this); } } while(false); } loadForm = Fn = errFn = null; } });; } function getJsonPosts(url, Fn) { GM_xmlhttpRequest({ 'method': 'GET', 'url': nav.fixLink(url), 'onreadystatechange': function(xhr) { if(xhr.readyState !== 4) { return; } if(xhr.status === 304) { closeAlert($id('de-alert-newposts')); } else { try { var json = JSON.parse(xhr.responseText); } catch(e) { Fn(1, e.toString(), null, this); } finally { if(json) { Fn(xhr.status, xhr.statusText, json, this); } Fn = null; } } } }); } function loadFavorThread() { var post, el = this.parentNode.parentNode, ifrm = $t('iframe', el), cont = $c('de-content', doc); if(ifrm) { $del(ifrm); cont.style.overflowY = 'auto'; return; } if((post = pByNum[el.getAttribute('de-num')]) && !post.hidden) { scrollTo(0, pageYOffset + post.el.getBoundingClientRect().top); return; } $del($id('de-iframe-fav')); $c('de-content', doc).style.overflowY = 'scroll'; el.insertAdjacentHTML('beforeend', '<iframe name="de-iframe-fav" id="de-iframe-fav" src="' + $t('a', el).href + '" scrolling="no" style="border: none; width: ' + (doc.documentElement.clientWidth - 55) + 'px; height: 1px;"><div id="de-fav-wait" ' + 'class="de-wait" style="font-size: 1.1em; text-align: center">' + Lng.loading[lang] + '</div>'); } function loadPages(count) { var fun, i = pageNum, len = Math.min(aib.lastPage + 1, i + count), pages = [], loaded = 1; count = len - i; function onLoadOrError(idx, eCodeOrForm, eMsgOrXhr, maybeXhr) { if(typeof eCodeOrForm === 'number') { pages[idx] = $add('<div><center style="font-size: 2em">' + getErrorMessage(eCodeOrForm, eMsgOrXhr) + '</center><hr></div>'); } else { pages[idx] = replacePost(eCodeOrForm); } if(loaded === count) { var el, df, j, parseThrs = Thread.parsed, threads = parseThrs ? [] : null; for(j in pages) { if(!pages.hasOwnProperty(j)) { continue; } if(j != pageNum) { dForm.insertAdjacentHTML('beforeend', '<center style="font-size: 2em">' + Lng.page[lang] + ' ' + j + '</center><hr>'); } df = pages[j]; if(parseThrs) { threads = parseThreadNodes(df, threads); } while(el = df.firstChild) { dForm.appendChild(el); } } if(!parseThrs) { threads = $Q(aib.qThread, dForm); } do { if(threads.length !== 0) { try { parseDelform(dForm, threads); } catch(e) { $alert(getPrettyErrorMessage(e), 'load-pages', true); break; } initDelformAjax(); addDelformStuff(false); readUserPosts(); readFavoritesPosts(); $each($Q('input[type="password"]', dForm), function(pEl) { pr.dpass = pEl; pEl.value = Cfg['passwValue']; }); if(keyNav) { keyNav.clear(pageNum + count - 1); } } closeAlert($id('de-alert-load-pages')); } while(false); dForm.style.display = ''; loaded = pages = count = null; } else { loaded++; } } $alert(Lng.loading[lang], 'load-pages', true); $each($Q('a[href^="blob:"]', dForm), function(a) { window.URL.revokeObjectURL(a.href); }); Pview.clearCache(); isExpImg = false; pByNum = Object.create(null); Thread.tNums = []; Post.hiddenNums = []; if(Attachment.viewer) { Attachment.viewer.close(null); Attachment.viewer = null; } dForm.style.display = 'none'; dForm.innerHTML = ''; if(pr.isQuick) { if(pr.file) { pr.delFilesUtils(); } pr.txta.value = ''; } while(i < len) { fun = onLoadOrError.bind(null, i); ajaxLoad(aib.getPageUrl(brd, i++), true, fun, fun); } } function infoLoadErrors(eCode, eMsg, newPosts) { if(eCode === 200 || eCode === 304) { closeAlert($id('de-alert-newposts')); } else if(eCode === 0) { $alert(eMsg || Lng.noConnect[lang], 'newposts', false); } else { $alert(Lng.thrNotFound[lang] + TNum + '): \n' + getErrorMessage(eCode, eMsg), 'newposts', false); if(newPosts !== -1) { doc.title = '{' + eCode + '} ' + doc.title; } } } //============================================================================================================ // SPELLS //============================================================================================================ function Spells(read) { if(read) { this._read(true); } else { this.disable(false); } } Spells.names = [ 'words', 'exp', 'exph', 'imgn', 'ihash', 'subj', 'name', 'trip', 'img', 'sage', 'op', 'tlen', 'all', 'video', 'wipe', 'num', 'vauthor' ]; Spells.needArg = [ /* words */ true, /* exp */ true, /* exph */ true, /* imgn */ true, /* ihash */ true, /* subj */ false, /* name */ true, /* trip */ false, /* img */ false, /* sage */ false, /* op */ false, /* tlen */ false, /* all */ false, /* video */ false, /* wipe */ false, /* num */ true, /* vauthor */ true ]; Spells.decompileSpell = function(type, neg, val, scope) { var temp, temp_, spell = (neg ? '!#' : '#') + Spells.names[type] + (scope ? '[' + scope[0] + (scope[1] ? ',' + (scope[1] === -1 ? '' : scope[1]) : '') + ']' : ''); if(!val) { return spell; } // #img if(type === 8) { return spell + '(' + (val[0] === 2 ? '>' : val[0] === 1 ? '<' : '=') + (val[1] ? val[1][0] + (val[1][1] === val[1][0] ? '' : '-' + val[1][1]) : '') + (val[2] ? '@' + val[2][0] + (val[2][0] === val[2][1] ? '' : '-' + val[2][1]) + 'x' + val[2][2] + (val[2][2] === val[2][3] ? '' : '-' + val[2][3]) : '') + ')'; } // #wipe else if(type === 14) { if(val === 0x3F) { return spell; } temp = []; (val & 1) && temp.push('samelines'); (val & 2) && temp.push('samewords'); (val & 4) && temp.push('longwords'); (val & 8) && temp.push('symbols'); (val & 16) && temp.push('capslock'); (val & 32) && temp.push('numbers'); (val & 64) && temp.push('whitespace'); return spell + '(' + temp.join(',') + ')'; } // #num, #tlen else if(type === 15 || type === 11) { if((temp = val[1].length - 1) !== -1) { for(temp_ = []; temp >= 0; temp--) { temp_.push(val[1][temp][0] + '-' + val[1][temp][1]); } temp_.reverse(); } spell += '('; if(val[0].length !== 0) { spell += val[0].join(',') + (temp_ ? ',' : ''); } if(temp_) { spell += temp_.join(','); } return spell + ')'; } // #words, #name, #trip, #vauthor else if(type === 0 || type === 6 || type === 7 || type === 16) { return spell + '(' + val.replace(/\)/g, '\\)') + ')'; } else { return spell + '(' + String(val) + ')'; } }; Spells.prototype = { _optimizeSpells: function(spells) { var i, j, len, flags, type, spell, scope, neg, parensSpells, lastSpell = -1, newSpells = []; for(i = 0, len = spells.length; i < len; ++i) { spell = spells[i]; flags = spell[0]; type = flags & 0xFF; neg = (flags & 0x100) !== 0; if(type === 0xFF) { parensSpells = this._optimizeSpells(spell[1]); if(parensSpells) { if(parensSpells.length !== 1) { newSpells.push([flags, parensSpells]); lastSpell++; continue; } else if((parensSpells[0][0] & 0xFF) !== 12) { newSpells.push([(parensSpells[0][0] | (flags & 0x200)) ^ (flags & 0x100), parensSpells[0][1]]); lastSpell++; continue; } flags = parensSpells[0][0]; neg = !(neg ^ ((flags & 0x100) !== 0)); } } else { scope = spell[2]; if(!scope || (scope[0] === brd && (scope[1] === -1 ? !TNum : (!scope[1] || scope[1] === TNum)))) { if(type === 12) { neg = !neg; } else { newSpells.push([flags, spell[1]]); lastSpell++; continue; } } } for(j = lastSpell; j >= 0 && (((newSpells[j][0] & 0x200) !== 0) ^ neg); --j) {} if(j !== lastSpell) { newSpells = newSpells.slice(0, j + 1); lastSpell = j; } if(neg && j !== -1) { newSpells[j][0] &= 0x1FF; } if(((flags & 0x200) !== 0) ^ neg) { break; } } return lastSpell === -1 ? neg ? [[12, '']] : null : newSpells; }, _initSpells: function(data) { if(data) { data.forEach(function initExps(item) { var val = item[1]; if(val) { switch(item[0] & 0xFF) { case 1: case 2: case 3: case 5: case 13: item[1] = toRegExp(val, true); break; case 0xFF: val.forEach(initExps); } } }); } return data; }, _decompileScope: function(scope, indent) { var spell, type, temp, str, dScope = [], hScope = false, i = 0, j = 0, len = scope.length; for(; i < len; i++, j++) { spell = scope[i]; type = spell[0] & 0xFF; if(type === 0xFF) { hScope = true; temp = this._decompileScope(spell[1], indent + ' '); if(temp[1]) { str = ((spell[0] & 0x100) ? '!(\n' : '(\n') + indent + ' ' + temp[0].join('\n' + indent + ' ') + '\n' + indent + ')'; if(j === 0) { dScope[0] = str; } else { dScope[--j] += ' ' + str; } } else { dScope[j] = ((spell[0] & 0x100) ? '!(' : '(') + temp[0].join(' ') + ')'; } } else { dScope[j] = Spells.decompileSpell(type, spell[0] & 0x100, spell[1], spell[2]); } if(i !== len - 1) { dScope[j] += (spell[0] & 0x200) ? ' &' : ' |'; } } return [dScope, dScope.length > 2 || hScope]; }, _decompileSpells: function() { var str, reps, oreps, data = this._data; if(!data) { this._read(false); if(!(data = this._data)) { return this._list = ''; } } str = data[1] ? this._decompileScope(data[1], '')[0].join('\n') : ''; reps = data[2]; oreps = data[3]; if(reps || oreps) { if(str) { str += '\n\n'; } reps && reps.forEach(function(rep) { str += this._decompileRep(rep, false) + '\n'; }.bind(this)); oreps && oreps.forEach(function(orep) { str += this._decompileRep(orep, true) + '\n'; }.bind(this)); str = str.substr(0, str.length - 1); } this._data = null; return this._list = str; }, _decompileRep: function(rep, isOrep) { return (isOrep ? '#outrep' : '#rep') + (rep[0] ? '[' + rep[0] + (rep[1] ? ',' + (rep[1] === -1 ? '' : rep[1]) : '') + ']' : '') + '(' + rep[2] + ',' + rep[3].replace(/\)/g, '\\)') + ')'; }, _optimizeReps: function(data) { if(data) { var nData = []; data.forEach(function(temp) { if(!temp[0] || (temp[0] === brd && (temp[1] === -1 ? !TNum : !temp[1] || temp[1] === TNum))) { nData.push([temp[2], temp[3]]); } }); return nData.length === 0 ? false : nData; } return false; }, _initReps: function(data) { if(data) { for(var i = data.length - 1; i >= 0; i--) { data[i][0] = toRegExp(data[i][0], false); } } return data; }, _init: function(spells, reps, outreps) { this._spells = this._initSpells(spells); this._sLength = spells && spells.length; this._reps = this._initReps(reps); this._outreps = this._initReps(outreps); this.enable = !!this._spells; this.haveReps = !!reps; this.haveOutreps = !!outreps; }, _read: function(init) { var spells, data; try { spells = JSON.parse(Cfg['spells']); data = JSON.parse(sesStorage['de-spells-' + brd + TNum]); } catch(e) {} if(data && spells && data[0] === spells[0]) { this._data = spells; if(init) { this.hash = data[0]; this._init(data[1], data[2], data[3]); } return; } if(!spells) { spells = this.parseText('#wipe(samelines,samewords,longwords,numbers,whitespace)'); } if(init) { this.update(spells, false, false); } else { this._data = spells; } }, _asyncSpellComplete: function(interp) { this.hasNumSpell |= interp.hasNumSpell; this._asyncJobs--; this.end(null); }, _asyncJobs: 0, _completeFns: [], _hasComplFns: false, _data: null, _list: '', hash: 0, hasNumSpell: false, enable: false, get list() { return this._list || this._decompileSpells(); }, addCompleteFunc: function(Fn) { this._completeFns.push(Fn); this._hasComplFns = true; }, parseText: function(str) { var codeGen, spells, reps = [], outreps = [], regexError = false, checkRegex = function(exp, reg) { if(!regexError) { try { toRegExp(reg, false); } catch(e) { var line = str.substr(0, str.indexOf(exp)).match(/\n/g).length + 1; $alert(Lng.error[lang] + ': ' + Lng.seErrRegex[lang].replace('%s', reg) + Lng.seRow[lang] + line + ')', 'help-err-spell', false); regexError = true; } } }; str = String(str).replace(/[\s\n]+$/, '').replace( /([^\\]\)|^)?[\n\s]*(#rep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g, function(exp, preOp, fullExp, b, nt, t, reg, txt) { checkRegex(fullExp, reg); reps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]); return preOp || ''; } ).replace( /([^\\]\)|^)?[\n\s]*(#outrep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g, function(exp, preOp, fullExp, b, nt, t, reg, txt) { checkRegex(fullExp, reg); outreps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]); return preOp || ''; } ); checkRegex = null; if(regexError) { return null; } if(reps.length === 0) { reps = false; } if(outreps.length === 0) { outreps = false; } codeGen = new SpellsCodegen(str); spells = codeGen.generate(); if(codeGen.hasError) { $alert(Lng.error[lang] + ': ' + codeGen.error, 'help-err-spell', false); } else if(spells || reps || outreps) { if(spells && Cfg['sortSpells']) { this.sort(spells); } return [Date.now(), spells, reps, outreps]; } return null; }, sort: function(sp) { // Wraps AND-spells with brackets for proper sorting for(var i = 0, len = sp.length-1; i < len; i++) { if(sp[i][0] > 0x200) { var temp = [0xFF, []]; do { temp[1].push(sp.splice(i, 1)[0]); len--; } while (sp[i][0] > 0x200); temp[1].push(sp.splice(i, 1)[0]); sp.splice(i, 0, temp); } } sp = sp.sort(); for(var i = 0, len = sp.length-1; i < len; i++) { // Removes duplicates and weaker spells if(sp[i][0] === sp[i+1][0] && sp[i][1] <= sp[i+1][1] && sp[i][1] >= sp[i+1][1] && (sp[i][2] === null || // Stronger spell with 3 parameters sp[i][2] === undefined || // Equal spells with 2 parameters (sp[i][2] <= sp[i+1][2] && sp[i][2] >= sp[i+1][2]))) { // Equal spells with 3 parameters sp.splice(i+1, 1); i--; len--; // Moves brackets to the end of the list } else if(sp[i][0] === 0xFF) { sp.push(sp.splice(i, 1)[0]); i--; len--; } } }, update: function(data, sync, isHide) { var spells = data[1] ? this._optimizeSpells(data[1]) : false, reps = this._optimizeReps(data[2]), outreps = this._optimizeReps(data[3]); saveCfg('spells', JSON.stringify(data)); sesStorage['de-spells-' + brd + TNum] = JSON.stringify([data[0], spells, reps, outreps]); this._data = data; this._list = ''; this.hash = data[0]; if(sync) { locStorage['__de-spells'] = JSON.stringify({ 'hide': (!!this.list && !!isHide), 'data': data }); locStorage.removeItem('__de-spells'); } this._init(spells, reps, outreps); }, setSpells: function(spells, sync) { this.update(spells, sync, Cfg['hideBySpell']); if(Cfg['hideBySpell']) { for(var post = firstThr.op; post; post = post.next) { this.check(post); } this.end(savePosts); } else { this.enable = false; } }, disable: function(sync) { this.enable = false; this._list = ''; this._data = null; this.haveReps = this.haveOutreps = false; saveCfg('hideBySpell', false); }, end: function(Fn) { if(this._asyncJobs === 0) { Fn && Fn(); if(this._hasComplFns) { for(var i = 0, len = this._completeFns.length; i < len; ++i) { this._completeFns[i](); } this._completeFns = []; this._hasComplFns = false; } } else if(Fn) { this.addCompleteFunc(Fn); } }, check: function(post) { if(!this.enable) { return 0; } var interp = new SpellsInterpreter(post, this._spells, this._sLength); if(interp.run()) { this.hasNumSpell |= interp.hasNumSpell; return interp.postHidden ? 1 : 0; } interp.setEndFn(this._asyncSpellComplete.bind(this)); this._asyncJobs++; return 0; }, replace: function(txt) { for(var i = 0, len = this._reps.length; i < len; i++) { txt = txt.replace(this._reps[i][0], this._reps[i][1]); } return txt; }, outReplace: function(txt) { for(var i = 0, len = this._outreps.length; i < len; i++) { txt = txt.replace(this._outreps[i][0], this._outreps[i][1]); } return txt; }, addSpell: function(type, arg, scope, isNeg, spells) { if(!spells) { if(!this._data) { this._read(false); } spells = this._data || [Date.now(), [], false, false]; } var idx, sScope = String(scope), sArg = String(arg); if(spells[1]) { spells[1].some(scope && isNeg ? function(spell, i) { var data; if(spell[0] === 0xFF && ((data = spell[1]) instanceof Array) && data.length === 2 && data[0][0] === 0x20C && data[1][0] === type && data[1][2] == null && String(data[1][1]) === sArg && String(data[0][2]) === sScope) { idx = i; return true; } return (spell[0] & 0x200) !== 0; } : function(spell, i) { if(spell[0] === type && String(spell[1]) === sArg && String(spell[2]) === sScope) { idx = i; return true; } return (spell[0] & 0x200) !== 0; }); } else { spells[1] = []; } if(typeof idx !== 'undefined') { spells[1].splice(idx, 1); } else if(scope && isNeg) { spells[1].splice(0, 0, [0xFF, [[0x20C, '', scope], [type, arg, void 0]], void 0]); } else { spells[1].splice(0, 0, [type, arg, scope]); } this.update(spells, true, true); idx = null; } }; function SpellsCodegen(sList) { this._line = 1; this._col = 1; this._sList = sList; this.hasError = false; } SpellsCodegen.prototype = { TYPE_UNKNOWN: 0, TYPE_ANDOR: 1, TYPE_NOT: 2, TYPE_SPELL: 3, TYPE_PARENTHESES: 4, generate: function() { return this._sList ? this._generate(this._sList, false) : null; }, get error() { if(!this.hasError) { return ''; } return (this._errMsgArg ? this._errMsg.replace('%s', this._errMsgArg) : this._errMsg) + Lng.seRow[lang] + this._line + Lng.seCol[lang] + this._col + ')'; }, _errMsg: '', _errMsgArg: null, _generate: function(sList, inParens) { var res, name, i = 0, len = sList.length, data = [], lastType = this.TYPE_UNKNOWN; for(; i < len; i++, this._col++) { switch(sList[i]) { case '\n': this._line++; this._col = 0; case '\r': case ' ': continue; case '#': if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) { this._setError(Lng.seMissOp[lang], null); return null; } name = ''; i++; this._col++; while((sList[i] >= 'a' && sList[i] <= 'z') || (sList[i] >= 'A' && sList[i] <= 'Z')) { name += sList[i].toLowerCase(); i++; this._col++; } res = this._doSpell(name, sList.substr(i), lastType === this.TYPE_NOT) if(!res) { return null; } i += res[0] - 1; this._col += res[0] - 1; data.push(res[1]); lastType = this.TYPE_SPELL; break; case '(': if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) { this._setError(Lng.seMissOp[lang], null); return null; } res = this._generate(sList.substr(i + 1), true); if(!res) { return null; } i += res[0] + 1; data.push([lastType === this.TYPE_NOT ? 0x1FF : 0xFF, res[1]]); lastType = this.TYPE_PARENTHESES; break; case '|': case '&': if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) { this._setError(Lng.seMissSpell[lang], null); return null; } if(sList[i] === '&') { data[data.length - 1][0] |= 0x200; } lastType = this.TYPE_ANDOR; break; case '!': if(lastType !== this.TYPE_ANDOR && lastType !== this.TYPE_UNKNOWN) { this._setError(Lng.seMissOp[lang], null); return null; } lastType = this.TYPE_NOT; break; case ')': if(lastType === this.TYPE_ANDOR || lastType === this.TYPE_NOT) { this._setError(Lng.seMissSpell[lang], null); return null; } if(inParens) { return [i, data]; } default: this._setError(Lng.seUnexpChar[lang], sList[i]); return null; } } if(inParens) { this._setError(Lng.seMissClBkt[lang], null); return null; } if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) { this._setError(Lng.seMissSpell[lang], null); return null; } return data; }, _doSpell: function(name, str, isNeg) { var scope, m, spellType, val, i = 0, spellIdx = Spells.names.indexOf(name); if(spellIdx === -1) { this._setError(Lng.seUnknown[lang], name); return null; } spellType = isNeg ? spellIdx | 0x100 : spellIdx; m = str.match(/^\[([a-z0-9\/]+)(?:(,)|,(\s*[0-9]+))?\]/); if(m) { i = m[0].length; str = str.substring(i); scope = [m[1], m[3] ? m[3] : m[2] ? -1 : false]; } else { scope = null; } if(str[0] !== '(' || str[1] === ')') { if(Spells.needArg[spellIdx]) { this._setError(Lng.seMissArg[lang], name); return null; } return [str[0] === '(' ? i + 2 : i, [spellType, spellIdx === 14 ? 0x3F : '', scope]]; } switch(spellIdx) { // #ihash case 4: m = str.match(/^\((\d+)\)/); if(+m[1] === +m[1]) { return [i + m[0].length, [spellType, +m[1], scope]]; } break; // #img case 8: m = str.match(/^\(([><=])(?:(\d+(?:\.\d+)?)(?:-(\d+(?:\.\d+)?))?)?(?:@(\d+)(?:-(\d+))?x(\d+)(?:-(\d+))?)?\)/); if(m && (m[2] || m[4])) { return [i + m[0].length, [spellType, [ m[1] === '=' ? 0 : m[1] === '<' ? 1 : 2, m[2] && [+m[2], m[3] ? +m[3] : +m[2]], m[4] && [+m[4], m[5] ? +m[5] : +m[4], +m[6], m[7] ? +m[7] : +m[6]] ], scope]]; } break; // #wipe case 14: m = str.match(/^\(([a-z, ]+)\)/); if(m) { val = m[1].split(/, */).reduce(function(val, str) { switch(str) { case 'samelines': return val |= 1; case 'samewords': return val |= 2; case 'longwords': return val |= 4; case 'symbols': return val |= 8; case 'capslock': return val |= 16; case 'numbers': return val |= 32; case 'whitespace': return val |= 64; default: return -1; } }, 0); if(val !== -1) { return [i + m[0].length, [spellType, val, scope]]; } } break; // #tlen, #num case 11: case 15: m = str.match(/^\(([\d-, ]+)\)/); if(m) { m[1].split(/, */).forEach(function(v) { if(v.contains('-')) { var nums = v.split('-'); nums[0] = +nums[0]; nums[1] = +nums[1]; this[1].push(nums); } else { this[0].push(+v); } }, val = [[], []]); return [i + m[0].length, [spellType, val, scope]]; } break; // #exp, #exph, #imgn, #subj, #video case 1: case 2: case 3: case 5: case 13: m = str.match(/^\((\/.*?[^\\]\/[igm]*)\)/); if(m) { val = m[1]; try { toRegExp(val, true); } catch(e) { this._setError(Lng.seErrRegex[lang], val); return null; } return [i + m[0].length, [spellType, val, scope]]; } break; // #sage, #op, #all, #trip, #name, #words, #vauthor default: m = str.match(/^\((.*?[^\\])\)/); if(m) { val = m[1].replace(/\\\)/g, ')'); return [i + m[0].length, [spellType, spellIdx === 0 ? val.toLowerCase() : val, scope]]; } } this._setError(Lng.seSyntaxErr[lang], name); return null; }, _setError: function(msg, arg) { this.hasError = true; this._errMsg = msg; this._errMsgArg = arg; } }; function SpellsInterpreter(post, spells, length) { this._post = post; this._ctx = [length, spells, 0]; this._deep = 0; } SpellsInterpreter.prototype = { hasNumSpell: false, postHidden: false, run: function() { var rv, type, val, i = this._ctx.pop(), scope = this._ctx.pop(), len = this._ctx.pop(); while(true) { if(i < len) { type = scope[i][0] & 0xFF; if(type === 0xFF) { this._deep++; this._ctx.push(len, scope, i); scope = scope[i][1]; len = scope.length; i = 0; continue; } val = this._runSpell(type, scope[i][1]); if(this._asyncWait) { this._ctx.push(len, scope, i, scope[i][0]); return false; } rv = this._checkRes(scope[i][0], val); if(rv === null) { i++; continue; } this._lastSpellIdx = i; } else { this._lastSpellIdx = i -= 1; rv = false; } if(this._deep !== 0) { this._deep--; i = this._ctx.pop(); scope = this._ctx.pop(); len = this._ctx.pop(); rv = this._checkRes(scope[i][0], rv); if(rv === null) { i++; continue; } } if(rv) { this._post.spellHide(this._getMsg(scope[i])); this.postHidden = true; } else if(!this._post.deleted) { sVis[this._post.count] = 1; } return true; } }, setEndFn: function(Fn) { this._endFn = Fn; }, _asyncWait: false, _endFn: null, _lastSpellIdx: 0, _wipeMsg: '', _asyncContinue: function(val) { this._asyncWait = false; var temp, rv = this._checkRes(this._ctx.pop(), val); if(rv === null) { if(!this.run()) { return; } } else if(rv) { temp = this._ctx.pop(); this._post.spellHide(this._getMsg(this._ctx.pop()[temp - 1])); this.postHidden = true; } else if(!this._post.deleted) { sVis[this._post.count] = 1; } if(this._endFn) { this._endFn(this); } }, _checkRes: function(flags, val) { if((flags & 0x100) !== 0) { val = !val; } if((flags & 0x200) !== 0) { if(!val) { return false; } } else if(val) { return true; } return null; }, _getMsg: function(spell) { var neg = spell[0] & 0x100, type = spell[0] & 0xFF, val = spell[1]; if(type === 0xFF) { return this._getMsg(val[this._lastSpellIdx]); } if(type === 14) { return (neg ? '!#wipe' : '#wipe') + (Spells._lastWipeMsg ? ': ' + Spells._lastWipeMsg : ''); } else { return Spells.decompileSpell(type, neg, val, spell[2]); } }, _runSpell: function(spellId, val) { switch(spellId) { case 0: return this._words(val); case 1: return this._exp(val); case 2: return this._exph(val); case 3: return this._imgn(val); case 4: return this._ihash(val); case 5: return this._subj(val); case 6: return this._name(val); case 7: return this._trip(val); case 8: return this._img(val); case 9: return this._sage(val); case 10: return this._op(val); case 11: return this._tlen(val); case 12: return this._all(val); case 13: return this._video(val); case 14: return this._wipe(val); case 15: this.hasNumSpell = true; return this._num(val); case 16: return this._vauthor(val); } }, _words: function(val) { return this._post.text.toLowerCase().contains(val) || this._post.subj.toLowerCase().contains(val); }, _exp: function(val) { return val.test(this._post.text); }, _exph: function(val) { return val.test(this._post.html); }, _imgn: function(val) { for(var i = 0, imgs = this._post.images, len = imgs.length; i < len; ++i) { if(val.test(imgs[i].info)) { return true; } } return false; }, _ihash: function(val) { for(var i = 0, imgs = this._post.images, len = imgs.length; i < len; ++i) { if(imgs[i].hash === val) { return true; } } if(this._post.hashImgsBusy === 0) { return false; } this._post.hashHideFun = this._ihash_helper.bind(this, val); this._asyncWait = true; return false; }, _ihash_helper: function(val, hash) { if(val === hash) { this._post.hashHideFun = null; this._asyncContinue(true); } else if(this._post.hashImgsBusy === 0) { this.hashHideFun = null; this._asyncContinue(false); } }, _subj: function(val) { var pSubj = this._post.subj; return pSubj ? !val || val.test(pSubj) : false; }, _name: function(val) { var pName = this._post.posterName; return pName ? !val || pName.contains(val) : false; }, _trip: function(val) { var pTrip = this._post.posterTrip; return pTrip ? !val || pTrip.contains(val) : false; }, _img: function(val) { var temp, w, h, hide, img, i, imgs = this._post.images, len = imgs.length; if(!val) { return len !== 0; } for(i = 0; i < len; ++i) { img = imgs[i]; if(temp = val[1]) { w = img.weight; switch(val[0]) { case 0: hide = w >= temp[0] && w <= temp[1]; break; case 1: hide = w < temp[0]; break; case 2: hide = w > temp[0]; } if(!hide) { continue; } else if(!val[2]) { return true; } } if(temp = val[2]) { w = img.width; h = img.height; switch(val[0]) { case 0: if(w >= temp[0] && w <= temp[1] && h >= temp[2] && h <= temp[3]) { return true } break; case 1: if(w < temp[0] && h < temp[3]) { return true } break; case 2: if(w > temp[0] && h > temp[3]) { return true } } } } return false; }, _sage: function(val) { return this._post.sage; }, _op: function(val) { return this._post.isOp; }, _tlen: function(val) { var text = this._post.text; return !val ? !!text : this._tlenNum_helper(val, text.replace(/\n/g, '').length); }, _all: function(val) { return true; }, _video: function(val) { return this._videoVauthor(val, false); }, _wipe: function(val) { var arr, len, i, j, n, x, keys, pop, capsw, casew, _txt, txt = this._post.text; // (1 << 0): samelines if(val & 1) { arr = txt.replace(/>/g, '').split(/\s*\n\s*/); if((len = arr.length) > 5) { arr.sort(); for(i = 0, n = len / 4; i < len;) { x = arr[i]; j = 0; while(arr[i++] === x) { j++; } if(j > 4 && j > n && x) { this._wipeMsg = 'same lines: "' + x.substr(0, 20) + '" x' + (j + 1); return true; } } } } // (1 << 1): samewords if(val & 2) { arr = txt.replace(/[\s\.\?\!,>]+/g, ' ').toUpperCase().split(' '); if((len = arr.length) > 3) { arr.sort(); for(i = 0, n = len / 4, keys = 0, pop = 0; i < len; keys++) { x = arr[i]; j = 0; while(arr[i++] === x) { j++; } if(len > 25) { if(j > pop && x.length > 2) { pop = j; } if(pop >= n) { this._wipeMsg = 'same words: "' + x.substr(0, 20) + '" x' + (pop + 1); return true; } } } x = keys / len; if(x < 0.25) { this._wipeMsg = 'uniq words: ' + (x * 100).toFixed(0) + '%'; return true; } } } // (1 << 2): longwords if(val & 4) { arr = txt.replace(/https*:\/\/.*?(\s|$)/g, '').replace(/[\s\.\?!,>:;-]+/g, ' ').split(' '); if(arr[0].length > 50 || ((len = arr.length) > 1 && arr.join('').length / len > 10)) { this._wipeMsg = 'long words'; return true; } } // (1 << 3): symbols if(val & 8) { _txt = txt.replace(/\s+/g, ''); if((len = _txt.length) > 30 && (x = _txt.replace(/[0-9a-zа-я\.\?!,]/ig, '').length / len) > 0.4) { this._wipeMsg = 'specsymbols: ' + (x * 100).toFixed(0) + '%'; return true; } } // (1 << 4): capslock if(val & 16) { arr = txt.replace(/[\s\.\?!;,-]+/g, ' ').trim().split(' '); if((len = arr.length) > 4) { for(i = 0, n = 0, capsw = 0, casew = 0; i < len; i++) { x = arr[i]; if((x.match(/[a-zа-я]/ig) || []).length < 5) { continue; } if((x.match(/[A-ZА-Я]/g) || []).length > 2) { casew++; } if(x === x.toUpperCase()) { capsw++; } n++; } if(capsw / n >= 0.3 && n > 4) { this._wipeMsg = 'CAPSLOCK: ' + capsw / arr.length * 100 + '%'; return true; } else if(casew / n >= 0.3 && n > 8) { this._wipeMsg = 'cAsE words: ' + casew / arr.length * 100 + '%'; return true; } } } // (1 << 5): numbers if(val & 32) { _txt = txt.replace(/\s+/g, ' ').replace(/>>\d+|https*:\/\/.*?(?: |$)/g, ''); if((len = _txt.length) > 30 && (x = (len - _txt.replace(/\d/g, '').length) / len) > 0.4) { this._wipeMsg = 'numbers: ' + Math.round(x * 100) + '%'; return true; } } // (1 << 5): whitespace if(val & 64) { if(/(?:\n\s*){5}/i.test(txt)) { this._wipeMsg = 'whitespace'; return true; } } return false; }, _num: function(val) { return this._tlenNum_helper(val, this._post.count + 1); }, _tlenNum_helper: function(val, num) { var i, arr; for(arr = val[0], i = arr.length - 1; i >= 0; --i) { if(arr[i] === num) { return true; } } for(arr = val[1], i = arr.length - 1; i >= 0; --i) { if(num >= arr[i][0] && num <= arr[i][1]) { return true; } } return false; }, _vauthor: function(val) { return this._videoVauthor(val, true); }, _videoVauthor: function(val, isAuthorSpell) { if(!val) { return !!this._post.hasYTube; } if(!this._post.hasYTube || !Cfg['YTubeTitles']) { return false; } var i, data, len; for(i = 0, data = this._post.ytData, len = data.length; i < len; ++i) { if(isAuthorSpell ? val === data[i][1] : val.test(data[i][0])) { return true; } } if(this._post.ytLinksLoading === 0) { return false; } this._post.ytHideFun = this._videoVauthor_helper.bind(this, isAuthorSpell, val); this._asyncWait = true; return false; }, _videoVauthor_helper: function(isAuthorSpell, val, data) { if(isAuthorSpell ? val === data[1] : val.test(data[0])) { this._post.ytHideFun = null; this._asyncContinue(true); } else if(this._post.ytLinksLoading === 0) { this._post.ytHideFun = null; this._asyncContinue(false); } } } function disableSpells() { closeAlert($id('de-alert-help-err-spell')); if(spells.enable) { sVis = TNum ? '1'.repeat(firstThr.pcount).split('') : []; for(var post = firstThr.op; post; post = post.next) { if(post.spellHidden && !post.userToggled) { post.spellUnhide(); } } } } function toggleSpells() { var temp, fld = $id('de-spell-edit'), val = fld.value; if(val && (temp = spells.parseText(val))) { disableSpells(); spells.setSpells(temp, true); fld.value = spells.list; } else { if(val) { locStorage['__de-spells'] = '{"hide": false, "data": null}'; } else { disableSpells(); spells.disable(); saveCfg('spells', ''); locStorage['__de-spells'] = '{"hide": false, "data": ""}'; } locStorage.removeItem('__de-spells'); $q('input[info="hideBySpell"]', doc).checked = spells.enable = false; } } function addSpell(type, arg, isNeg) { var temp, fld = $id('de-spell-edit'), val = fld && fld.value, chk = $q('input[info="hideBySpell"]', doc); if(!val || (temp = spells.parseText(val))) { disableSpells(); spells.addSpell(type, arg, TNum ? [brd, TNum] : null, isNeg, temp); val = spells.list; saveCfg('hideBySpell', !!val); if(val) { for(var post = firstThr.op; post; post = post.next) { spells.check(post); } spells.end(savePosts); } else { saveCfg('spells', ''); spells.enable = false; } if(fld) { chk.checked = !!(fld.value = val); } return; } spells.enable = false; if(chk) { chk.checked = false; } } //============================================================================================================ // STYLES //============================================================================================================ function getThemeLang() { return !Cfg['scriptStyle'] ? 'fr' : Cfg['scriptStyle'] === 1 ? 'en' : 'de'; } function scriptCSS() { var p, x = ''; function cont(id, src) { return id + ':before { content: ""; padding: 0 16px 0 0; margin: 0 4px; background: url(' + src + ') no-repeat center; }'; } function gif(id, src) { return id + ' { background: url(data:image/gif;base64,' + src + ') no-repeat center !important; }'; } // Settings window x += '.de-block { display: block; }\ #de-content-cfg > div { border-radius: 10px 10px 0 0; width: auto; min-width: 0; padding: 0; margin: 5px 20px; overflow: hidden; }\ #de-cfg-head { padding: 4px; border-radius: 10px 10px 0 0; color: #fff; text-align: center; font: bold 14px arial; cursor: default; }\ #de-cfg-head:lang(en), #de-panel:lang(en) { background: linear-gradient(to bottom, #4b90df, #3d77be 5px, #376cb0 7px, #295591 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #183d77 13px, #1f4485 18px, #264c90 20px, #325f9e 25px); }\ #de-cfg-head:lang(fr), #de-panel:lang(fr) { background: linear-gradient(to bottom, #7b849b, #616b86 2px, #3a414f 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #121212 13px, #1f2740 25px); }\ #de-cfg-head:lang(de), #de-panel:lang(de) { background: #777; }\ .de-cfg-body { min-height: 289px; min-width: 371px; padding: 11px 7px 7px; margin-top: -1px; font: 13px sans-serif; }\ .de-cfg-body input[type="text"], .de-cfg-body select { width: auto; padding: 0 !important; margin: 0 !important; }\ .de-cfg-body, #de-cfg-btns { border: 1px solid #183d77; border-top: none; }\ .de-cfg-body:lang(de), #de-cfg-btns:lang(de) { border-color: #444; }\ #de-cfg-btns { padding: 7px 2px 2px; }\ #de-cfg-bar { width: 100%; display: table; background-color: #1f2740; margin: 0; padding: 0; }\ #de-cfg-bar:lang(en) { background-color: #325f9e; }\ #de-cfg-bar:lang(de) { background-color: #777; }\ .de-cfg-depend { padding-left: 25px; }\ .de-cfg-tab { padding: 4px 5px; border-radius: 4px 4px 0 0; font: bold 12px arial; text-align: center; cursor: default; }\ .de-cfg-tab-back { display: table-cell !important; float: none !important; width:auto; min-width: 0 !important; padding: 0 !important; box-shadow: none !important; border: 1px solid #183d77 !important; border-radius: 4px 4px 0 0; opacity: 1; }\ .de-cfg-tab-back:lang(de) { border-color: #444 !important; }\ .de-cfg-tab-back:lang(fr) { border-color: #121421 !important; }\ .de-cfg-tab-back[selected="true"] { border-bottom: none !important; }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab { background-color: rgba(0,0,0,.2); }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(fr) { background: linear-gradient(to bottom, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover { background-color: rgba(99,99,99,.2); }\ .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(fr) { background: linear-gradient(to top, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\ .de-cfg-tab::' + (nav.Firefox ? '-moz-' : '') + 'selection { background: transparent; }\ .de-cfg-unvis { display: none; }\ #de-spell-panel { float: right; }\ #de-spell-panel > a { padding: 0 4px; }\ #de-spell-div { display: table; }\ #de-spell-div > div { display: table-cell; vertical-align: top; }\ #de-spell-edit { padding: 2px !important; width: 340px; height: 180px; border: none !important; outline: none !important; }\ #de-spell-rowmeter { padding: 2px 3px 0 0; margin: 2px 0; overflow: hidden; width: 2em; height: 182px; text-align: right; color: #fff; font: 12px courier new; }\ #de-spell-rowmeter:lang(en), #de-spell-rowmeter:lang(fr) { background-color: #616b86; }\ #de-spell-rowmeter:lang(de) { background-color: #777; }'; // Main panel x += '#de-btn-logo { margin-right: 3px; cursor: pointer; }\ #de-panel { height: 25px; z-index: 9999; border-radius: 15px 0 0 0; cursor: default;}\ #de-panel-btns { display: inline-block; padding: 0 0 0 2px; margin: 0; height: 25px; border-left: 1px solid #8fbbed; }\ #de-panel-btns:lang(de), #de-panel-info:lang(de) { border-color: #ccc; }\ #de-panel-btns:lang(fr), #de-panel-info:lang(fr) { border-color: #616b86; }\ #de-panel-btns > li { margin: 0 1px; padding: 0; }\ #de-panel-btns > li, #de-panel-btns > li > a, #de-btn-logo { display: inline-block; width: 25px; height: 25px; }\ #de-panel-btns:lang(en) > li, #de-panel-btns:lang(fr) > li { transition: all 0.3s ease; }\ #de-panel-btns:lang(en) > li:hover, #de-panel-btns:lang(fr) > li:hover { background-color: rgba(255,255,255,.15); box-shadow: 0 0 3px rgba(143,187,237,.5); }\ #de-panel-btns:lang(de) > li > a { border-radius: 5px; }\ #de-panel-btns:lang(de) > li > a:hover { width: 21px; height: 21px; border: 2px solid #444; }\ #de-panel-info { display: inline-block; vertical-align: 6px; padding: 0 6px; margin: 0 0 0 2px; height: 25px; border-left: 1px solid #8fbbed; color: #fff; font: 18px serif; }'; p = 'R0lGODlhGQAZAIAAAPDw8P///yH5BAEAAAEALAAAAAAZABkA'; x += gif('#de-btn-logo', p + 'QAI5jI+pywEPWoIIRomz3tN6K30ixZXM+HCgtjpk1rbmTNc0erHvLOt4vvj1KqnD8FQ0HIPCpbIJtB0KADs='); x += gif('#de-btn-settings', p + 'QAJAjI+pa+API0Mv1Ymz3hYuiQHHFYjcOZmlM3Jkw4aeAn7R/aL6zuu5VpH8aMJaKtZR2ZBEZnMJLM5kIqnP2csUAAA7'); x += gif('#de-btn-hidden', p + 'QAI5jI+pa+CeHmRHgmCp3rxvO3WhMnomUqIXl2UmuLJSNJ/2jed4Tad96JLBbsEXLPbhFRc8lU8HTRQAADs='); x += gif('#de-btn-favor', p + 'QAIzjI+py+AMjZs02ovzobzb1wDaeIkkwp3dpLEoeMbynJmzG6fYysNh3+IFWbqPb3OkKRUFADs='); x += gif('#de-btn-refresh', p + 'QAJAjI+pe+AfHmRGLkuz3rzN+1HS2JWbhWlpVIXJ+roxSpr2jedOBIu0rKjxhEFgawcCqJBFZlPJIA6d0ZH01MtRCgA7'); x += gif('#de-btn-goback', p + 'QAIrjI+pmwAMm4u02gud3lzjD4biJgbd6VVPybbua61lGqIoY98ZPcvwD4QUAAA7'); x += gif('#de-btn-gonext', p + 'QAIrjI+pywjQonuy2iuf3lzjD4Zis0Xd6YnQyLbua61tSqJnbXcqHVLwD0QUAAA7'); x += gif('#de-btn-goup', p + 'QAIsjI+pm+DvmDRw2ouzrbq9DmKcBpVfN4ZpyLYuCbgmaK7iydpw1OqZf+O9LgUAOw=='); x += gif('#de-btn-godown', p + 'QAItjI+pu+DA4ps02osznrq9DnZceIxkYILUd7bue6WhrLInLdokHq96tnI5YJoCADs='); x += gif('#de-btn-expimg', p + 'QAI9jI+pGwDn4GPL2Wep3rxXFEFel42mBE6kcYXqFqYnVc72jTPtS/KNr5OJOJMdq4diAXWvS065NNVwseehAAA7'); x += gif('#de-btn-preimg', p + 'QAJFjI+pGwCcHJPGWdoe3Lz7qh1WFJLXiX4qgrbXVEIYadLLnMX4yve+7ErBYorRjXiEeXagGguZAbWaSdHLOow4j8Hrj1EAADs='); x += gif('#de-btn-maskimg', p + 'QAJQjI+pGwD3TGxtJgezrKz7DzLYRlKj4qTqmoYuysbtgk02ZCG1Rkk53gvafq+i8QiSxTozIY7IcZJOl9PNBx1de1Sdldeslq7dJ9gsUq6QnwIAOw=='); x += gif('#de-btn-imgload', p + 'QAJFjI+pG+CQnHlwSYYu3rz7RoVipWib+aVUVD3YysAledKZHePpzvecPGnpDkBQEEV03Y7DkRMZ9ECNnemUlZMOQc+iT1EAADs=') x += gif('#de-btn-catalog', p + 'QAI2jI+pa+DhAHyRNYpltbz7j1Rixo0aCaaJOZ2SxbIwKTMxqub6zuu32wP9WsHPcFMs0XDJ5qEAADs='); x += gif('#de-btn-audio-off', p + 'QAI7jI+pq+DO1psvQHOj3rxTik1dCIzmSZqfmGXIWlkiB6L2jedhPqOfCitVYolgKcUwyoQuSe3WwzV1kQIAOw=='); x += gif('#de-btn-audio-on', p + 'QAJHjI+pq+AewJHs2WdoZLz7X11WRkEgNoHqimadOG7uAqOm+Y6atvb+D0TgfjHS6RIp8YQ1pbHRfA4n0eSTI7JqP8Wtahr0FAAAOw=='); x += gif('#de-btn-enable', p + 'AAJAjI+py+0Po5wUWKoswOF27z2aMX6bo51lioal2bzwISPyHSZ1lts9fwKKfjQiyXgkslq95TAFnUCdUirnis0eCgA7'); p = 'Dw8P///wAAACH5BAEAAAIALAAAAAAZABkAQAJElI+pe2EBoxOTNYmr3bz7OwHiCDzQh6bq06QSCUhcZMCmNrfrzvf+XsF1MpjhCSainBg0AbKkFCJko6g0MSGyftwuowAAOw=='; x += gif('#de-btn-upd-on', 'R0lGODlhGQAZAJEAADL/Mv' + p); x += gif('#de-btn-upd-off', 'R0lGODlhGQAZAJEAAP8yMv' + p); x += gif('#de-btn-upd-warn', 'R0lGODlhGQAZAJEAAP/0Qf' + p); if(Cfg['disabled']) { applyCSS(x); return; } // Post panel x += '.de-ppanel { margin-left: 4px; }\ .de-post-note { color: inherit; margin: 0 4px; vertical-align: 1px; font: italic bold 12px serif; }\ .de-thread-note { font-style: italic; }\ .de-btn-expthr, .de-btn-fav, .de-btn-fav-sel, .de-btn-hide, .de-btn-hide-user, .de-btn-rep, .de-btn-sage, .de-btn-src, .de-btn-stick, .de-btn-stick-on { display: inline-block; margin: 0 4px -2px 0 !important; cursor: pointer; '; if(Cfg['postBtnsCSS'] === 0) { x += 'color: #4F7942; font-size: 14px; }\ .de-post-hide .de-btn-hide:after { content: "\u271A"; }\ .de-post-hide .de-btn-hide-user:after { content: "\u271A"; }\ .de-btn-expthr:after { content: "\u21D5"; }\ .de-btn-fav:after { content: "\u2605"; }\ .de-btn-fav-sel:after { content: "[\u2605]"; }\ .de-btn-hide:after { content: "\u2716"; }\ .de-btn-hide-user:after { content: "\u2716"; color: red !important; }\ .de-btn-rep:after { content: "\u25B6"; }\ .de-btn-sage:after { content: "\u274E"; }\ .de-btn-src:after { content: "[S]"; }\ .de-btn-stick:after { content: "\u25FB"; }\ .de-btn-stick-on:after { content: "\u25FC"; }'; } else if(Cfg['postBtnsCSS'] === 1) { p = 'R0lGODlhDgAOAKIAAPDw8KCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM'; x += 'padding: 0 14px 14px 0; }'; x += gif('.de-post-hide .de-btn-hide', p + '4SLLcqyHKGRe1E1cARPaSwIGVI3bOIAxc26oD7LqwusZcbMcNC9gLHsMHvFFixwFlGRgQdNAoIQEAOw=='); x += gif('.de-post-hide .de-btn-hide-user', 'R0lGODlhDgAOAKIAAP+/v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM4SLLcqyHKGRe1E1cARPaSwIGVI3bOIAxc26oD7LqwusZcbMcNC9gLHsMHvFFixwFlGRgQdNAoIQEAOw=='); x += gif('.de-btn-expthr', p + '5SLLcqyHGJaeoAoAr6dQaF3gZGFpO6AzNoLHMAC8uMAty+7ZwbfYzny02qNSKElkloDQSZNAolJAAADs='); x += gif('.de-btn-fav', p + '4SLLcqyHGJaeoAoAradec1Wigk5FoOQhDSq7DyrpyvLRpDb84AO++m+YXiVWMAWRlmSTEntAnIQEAOw=='); x += gif('.de-btn-fav-sel', 'R0lGODlhDgAOAKIAAP/hAKCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM4SLLcqyHGJaeoAoAradec1Wigk5FoOQhDSq7DyrpyvLRpDb84AO++m+YXiVWMAWRlmSTEntAnIQEAOw=='); x += gif('.de-btn-hide', p + '7SLLcqyHKGZcUE1ctAPdb0AHeCDpkWi4DM6gtGwtvOg9xDcu0rbc4FiA3lEkGE2QER2kGBgScdColJAAAOw=='); x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAKIAAL//v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAM7SLLcqyHKGZcUE1ctAPdb0AHeCDpkWi4DM6gtGwtvOg9xDcu0rbc4FiA3lEkGE2QER2kGBgScdColJAAAOw=='); x += gif('.de-btn-rep', p + '2SLLcqyHKGZe0NGABAL5C1XWfM47NsAznqA6qwLbAG8/nfeexvNe91UACywSKxsmAAGs6m4QEADs='); x += gif('.de-btn-sage', 'R0lGODlhDgAOAJEAAPDw8EtLS////wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu0AgZs0SoqTzdnu5l1P1ImcwmBCAQA7'); x += gif('.de-btn-src', p + '/SLLcqyEuKWKYF4Cl6/VCF26UJHaUIzaDMGjA8Gqt7MJ47Naw3O832kxnay1sx11g6KMtBxEZ9DkdEKTYLCEBADs='); x += gif('.de-btn-stick', p + 'xSLLcqyHKGRe9wVYntQBgKGxMKDJDaQJouqzsMrgDTNO27Apzv88YCjAoGRB8yB4hAQA7'); x += gif('.de-btn-stick-on', 'R0lGODlhDgAOAKIAAL//v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AAAMxSLLcqyHKGRe9wVYntQBgKGxMKDJDaQJouqzsMrgDTNO27Apzv88YCjAoGRB8yB4hAQA7'); } else { p = 'R0lGODlhDgAOAJEAAPDw8IyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAI'; x += 'padding: 0 14px 14px 0; }'; x += gif('.de-post-hide .de-btn-hide', p + 'ZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7'); x += gif('.de-post-hide .de-btn-hide-user', 'R0lGODlhDgAOAJEAAP+/v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7 '); x += gif('.de-btn-expthr', p + 'bVI55pu0BwEMxzlonlHp331kXxjlYWH4KowkFADs='); x += gif('.de-btn-fav', p + 'dVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw=='); x += gif('.de-btn-fav-sel', 'R0lGODlhDgAOAJEAAP/hAIyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw=='); x += gif('.de-btn-hide', p + 'dVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw=='); x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAJEAAL//v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw=='); x += gif('.de-btn-rep', p + 'aVI55pu2vAIBISmrty7rx63FbN1LmiTCUUAAAOw=='); x += gif('.de-btn-sage', 'R0lGODlhDgAOAJEAAPDw8FBQUP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu0AgZs0SoqTzdnu5l1P1ImcwmBCAQA7'); x += gif('.de-btn-src', p + 'fVI55pt0ADnRh1uispfvpLkEieGGiZ5IUGmJrw7xCAQA7'); x += gif('.de-btn-stick', p + 'XVI55pu0PI5j00erutJpfj0XiKDKRUAAAOw=='); x += gif('.de-btn-stick-on', 'R0lGODlhDgAOAJEAAL//v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIXVI55pu0PI5j00erutJpfj0XiKDKRUAAAOw=='); } if(!pr.form && !pr.oeForm) { x += '.de-btn-rep { display: none; }'; } // Search images buttons x += cont('.de-src-google', 'http://google.com/favicon.ico'); x += cont('.de-src-tineye', 'http://tineye.com/favicon.ico'); x += cont('.de-src-iqdb', 'http://iqdb.org/favicon.ico'); x += cont('.de-src-saucenao', 'http://saucenao.com/favicon.ico'); // Posts counter x += '.de-ppanel-cnt:after { counter-increment: de-cnt 1; content: counter(de-cnt); margin-right: 4px; vertical-align: 1px; color: #4f7942; font: bold 11px tahoma; cursor: default; }\ .de-ppanel-del:after { content: "' + Lng.deleted[lang] + '"; margin-right: 4px; vertical-align: 1px; color: #727579; font: bold 11px tahoma; cursor: default; }'; // Text format buttons x += '#de-txt-panel { display: block; height: 23px; font-weight: bold; cursor: pointer; }\ #de-txt-panel > span:empty { display: inline-block; width: 27px; height: 23px; }'; p = 'R0lGODlhFwAWAJEAAPDw8GRkZAAAAP///yH5BAEAAAMALAAAAAAXABYAQAJ'; x += gif('#de-btn-bold:empty', p + 'T3IKpq4YAoZgR0KqqnfzipIUikFWc6ZHBwbQtG4zyonW2Vkb2iYOo8Ps8ZLOV69gYEkU5yQ7YUzqhzmgsOLXWnlRIc9PleX06rnbJ/KITDqTLUAAAOw=='); x += gif('#de-btn-italic:empty', p + 'K3IKpq4YAYxRCSmUhzTfx3z3c9iEHg6JnAJYYSFpvRlXcLNUg3srBmgr+RL0MzxILsYpGzyepfEIjR43t5kResUQmtdpKOIQpQwEAOw=='); x += gif('#de-btn-under:empty', p + 'V3IKpq4YAoRARzAoV3hzoDnoJNlGSWSEHw7JrEHILiVp1NlZXtKe5XiptPrFh4NVKHh9FI5NX60WIJ6ATZoVeaVnf8xSU4r7NMRYcFk6pzYRD2TIUAAA7'); x += gif('#de-btn-strike:empty', p + 'S3IKpq4YAoRBR0qqqnVeD7IUaKHIecjCqmgbiu3jcfCbAjOfTZ0fmVnu8YIHW6lgUDkOkCo7Z8+2AmCiVqHTSgi6pZlrN3nJQ8TISO4cdyJWhAAA7'); x += gif('#de-btn-spoil:empty', 'R0lGODlhFwAWAJEAAPDw8GRkZP///wAAACH5BAEAAAIALAAAAAAXABYAQAJBlIKpq4YAmHwxwYtzVrprXk0LhBziGZiBx44hur4kTIGsZ99fSk+mjrMAd7XerEg7xnpLIVM5JMaiFxc14WBiBQUAOw=='); x += gif('#de-btn-code:empty', p + 'O3IKpq4YAoZgR0KpqnFxokH2iFm7eGCEHw7JrgI6L2F1YotloKek6iIvJAq+WkfgQinjKVLBS45CePSXzt6RaTjHmNjpNNm9aq6p4XBgKADs='); x += gif('#de-btn-sup:empty', p + 'Q3IKpq4YAgZiSQhGByrzn7YURGFGWhxzMuqqBGC7wRUNkeU7nnWNoMosFXKzi8BHs3EQnDRAHLY2e0BxnWfEJkRdT80NNTrliG3aWcBhZhgIAOw=='); x += gif('#de-btn-sub:empty', p + 'R3IKpq4YAgZiSxquujtOCvIUayAkVZEoRcjCu2wbivMw2WaYi7vVYYqMFYq/i8BEM4ZIrYOmpdD49m2VFd2oiUZTORWcNYT9SpnZrTjiML0MBADs='); x += gif('#de-btn-quote:empty', p + 'L3IKpq4YAYxRUSKguvRzkDkZfWFlicDCqmgYhuGjVO74zlnQlnL98uwqiHr5ODbDxHSE7Y490wxF90eUkepoysRxrMVaUJBzClaEAADs='); // Show/close animation if(nav.Anim) { x += '@keyframes de-open {\ 0% { transform: translateY(-1500px); }\ 40% { transform: translateY(30px); }\ 70% { transform: translateY(-10px); }\ 100% { transform: translateY(0); }\ }\ @keyframes de-close {\ 0% { transform: translateY(0); }\ 20% { transform: translateY(20px); }\ 100% { transform: translateY(-4000px); }\ }\ @keyframes de-blink {\ 0%, 100% { transform: translateX(0); }\ 10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }\ 20%, 40%, 60%, 80% { transform: translateX(10px); }\ }\ @keyframes de-cfg-open { from { transform: translate(0,50%) scaleY(0); opacity: 0; } }\ @keyframes de-cfg-close { to { transform: translate(0,50%) scaleY(0); opacity: 0; } }\ @keyframes de-post-open-tl { from { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-open-bl { from { transform: translate(-50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-open-tr { from { transform: translate(50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-open-br { from { transform: translate(50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-tl { to { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-bl { to { transform: translate(-50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-tr { to { transform: translate(50%,-50%) scale(0); opacity: 0; } }\ @keyframes de-post-close-br { to { transform: translate(50%,50%) scale(0); opacity: 0; } }\ @keyframes de-post-new { from { transform: translate(0,-50%) scaleY(0); opacity: 0; } }\ .de-pview-anim { animation-duration: .2s; animation-timing-function: ease-in-out; animation-fill-mode: both; }\ .de-open { animation: de-open .7s ease-out both; }\ .de-close { animation: de-close .7s ease-in both; }\ .de-blink { animation: de-blink .7s ease-in-out both; }\ .de-cfg-open { animation: de-cfg-open .2s ease-out backwards; }\ .de-cfg-close { animation: de-cfg-close .2s ease-in both; }\ .de-post-new { animation: de-post-new .2s ease-out both; }'; } // Embedders x += cont('.de-video-link.de-ytube', 'https://youtube.com/favicon.ico'); x += cont('.de-video-link.de-vimeo', 'https://vimeo.com/favicon.ico'); x += cont('.de-img-arch', 'data:image/gif;base64,R0lGODlhEAAQALMAAF82SsxdwQMEP6+zzRA872NmZQesBylPHYBBHP///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAAAQABAAQARTMMlJaxqjiL2L51sGjCOCkGiBGWyLtC0KmPIoqUOg78i+ZwOCUOgpDIW3g3KJWC4t0ElBRqtdMr6AKRsA1qYy3JGgMR4xGpAAoRYkVDDWKx6NRgAAOw=='); x += cont('.de-img-audio', 'data:image/gif;base64,R0lGODlhEAAQAKIAAGya4wFLukKG4oq3802i7Bqy9P///wAAACH5BAEAAAYALAAAAAAQABAAQANBaLrcHsMN4QQYhE01OoCcQIyOYQGooKpV1GwNuAwAa9RkqTPpWqGj0YTSELg0RIYM+TjOkgba0sOaAEbGBW7HTQAAOw=='); x += '.de-current:after { content: "\u25C4"; }\ .de-img-arch, .de-img-audio { color: inherit; text-decoration: none; font-weight: bold; }\ .de-img-pre, .de-img-full { display: block; border: none; outline: none; cursor: pointer; }\ .de-img-pre { max-width: 200px; max-height: 200px; }\ .de-img-full { float: left; }\ .de-img-center { position: fixed; margin: 0 !important; z-index: 9999; background-color: #ccc; border: 1px solid black !important; }\ #de-img-btn-next > div, #de-img-btn-prev > div { height: 36px; width: 36px; }' + gif('#de-img-btn-next > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJPjI8JkO1vlpzS0YvzhUdX/nigR2ZgSJ6IqY5Uy5UwJK/l/eI6A9etP1N8grQhUbg5RlLKAJD4DAJ3uCX1isU4s6xZ9PR1iY7j5nZibixgBQA7') + gif('#de-img-btn-prev > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJOjI8JkO24ooxPzYvzfJrWf3Rg2JUYVI4qea1g6zZmPLvmDeM6Y4mxU/v1eEKOpziUIA1BW+rXXEVVu6o1dQ1mNcnTckp7In3LAKyMchUAADs=') + '#de-img-btn-next, #de-img-btn-prev { position: fixed; top: 50%; z-index: 10000; margin-top: -8px; background-color: black; cursor: pointer; }\ #de-img-btn-next { right: 0; border-radius: 10px 0 0 10px; }\ #de-img-btn-prev { left: 0; border-radius: 0 10px 10px 0; }\ .de-mp3, .de-video-obj { margin: 5px 20px; }\ .de-video-title[de-time]:after { content: " [" attr(de-time) "]"; color: red; }\ td > a + .de-video-obj, td > img + .de-video-obj { display: inline-block; }\ video { background: black; }'; // Other x += cont('.de-wait', 'data:image/gif;base64,R0lGODlhEAAQALMMAKqooJGOhp2bk7e1rZ2bkre1rJCPhqqon8PBudDOxXd1bISCef///wAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAMACwAAAAAEAAQAAAET5DJyYyhmAZ7sxQEs1nMsmACGJKmSaVEOLXnK1PuBADepCiMg/DQ+/2GRI8RKOxJfpTCIJNIYArS6aRajWYZCASDa41Ow+Fx2YMWOyfpTAQAIfkEBQAADAAsAAAAABAAEAAABE6QyckEoZgKe7MEQMUxhoEd6FFdQWlOqTq15SlT9VQM3rQsjMKO5/n9hANixgjc9SQ/CgKRUSgw0ynFapVmGYkEg3v1gsPibg8tfk7CnggAIfkEBQAADAAsAAAAABAAEAAABE2QycnOoZjaA/IsRWV1goCBoMiUJTW8A0XMBPZmM4Ug3hQEjN2uZygahDyP0RBMEpmTRCKzWGCkUkq1SsFOFQrG1tr9gsPc3jnco4A9EQAh+QQFAAAMACwAAAAAEAAQAAAETpDJyUqhmFqbJ0LMIA7McWDfF5LmAVApOLUvLFMmlSTdJAiM3a73+wl5HYKSEET2lBSFIhMIYKRSimFriGIZiwWD2/WCw+Jt7xxeU9qZCAAh+QQFAAAMACwAAAAAEAAQAAAETZDJyRCimFqbZ0rVxgwF9n3hSJbeSQ2rCWIkpSjddBzMfee7nQ/XCfJ+OQYAQFksMgQBxumkEKLSCfVpMDCugqyW2w18xZmuwZycdDsRACH5BAUAAAwALAAAAAAQABAAAARNkMnJUqKYWpunUtXGIAj2feFIlt5JrWybkdSydNNQMLaND7pC79YBFnY+HENHMRgyhwPGaQhQotGm00oQMLBSLYPQ9QIASrLAq5x0OxEAIfkEBQAADAAsAAAAABAAEAAABE2QycmUopham+da1cYkCfZ94UiW3kmtbJuRlGF0E4Iwto3rut6tA9wFAjiJjkIgZAYDTLNJgUIpgqyAcTgwCuACJssAdL3gpLmbpLAzEQA7'); x += '.de-abtn { text-decoration: none !important; outline: none; }\ .de-after-fimg { clear: left; }\ #de-alert { position: fixed; right: 0; top: 0; z-index: 9999; font: 14px arial; cursor: default; }\ #de-alert > div { overflow: visible !important; float: right; clear: both; width: auto; min-width: 0pt; padding: 10px; margin: 1px; border: 1px solid grey; white-space: pre-wrap; }\ .de-alert-btn { display: inline-block; vertical-align: top; color: green; cursor: pointer; }\ .de-alert-btn:not(.de-wait) + div { margin-top: .15em; }\ .de-alert-msg { display: inline-block; }\ .de-content textarea { display: block; margin: 2px 0; font: 12px courier new; ' + (nav.Presto ? '' : 'resize: none !important; ') + '}\ .de-content-block > a { color: inherit; font-weight: bold; font-size: 14px; }\ #de-content-fav, #de-content-hid { font-size: 16px; padding: 10px; border: 1px solid gray; }\ .de-editor { display: block; font: 12px courier new; width: 619px; height: 337px; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; }\ .de-entry { margin: 2px 0; font-size: 14px; ' + (nav.Presto ? 'white-space: nowrap; ' : '') + '}\ .de-entry > :first-child { float: none !important; }\ .de-entry > div > a { text-decoration: none; }\ .de-fav-inf-posts, .de-fav-inf-page { float: right; margin-right: 5px; font: bold 16px serif; }\ .de-fav-inf-new { color: #424f79; }\ .de-fav-inf-old { color: #4f7942; }\ .de-fav-title { margin-right: 15px; }\ .de-file { display: inline-block; margin: 1px; height: 130px; width: 130px; text-align: center; border: 1px dashed grey; }\ .de-file > .de-file-del { float: right; }\ .de-file > .de-file-rar { float: left; }\ .de-file > .de-file-rarmsg { float: left; padding: 0 4px 2px; color: #fff; background-color: rgba(55, 55, 55, 0.5); }\ .de-file > .de-file-utils { display: none; }\ .de-file > div { display: table; width: 100%; height: 100%; cursor: pointer; }\ .de-file > div > div { display: table-cell; vertical-align: middle; }\ .de-file + [type="file"] { opacity: 0; margin: 1px 0 0 -132px !important; vertical-align: top; width: 132px !important; height: 132px; border: none !important; cursor: pointer; }\ .de-file-drag { background: rgba(88, 88, 88, 0.4); border: 1px solid grey; }\ .de-file-hover > .de-file-utils { display: block; position: relative; margin: -18px 2px; }\ .de-file-img > img, .de-file-img > video { max-width: 126px; max-height: 126px; }\ .de-file-off > div > div:after { content: "' + Lng.noFile[lang] + '" }\ .de-file-off + .de-file-off { display: none; }\ .de-file-rarmsg { margin: 0 5px; font: bold 11px tahoma; cursor: default; }\ .de-file-del, .de-file-rar { display: inline-block; margin: 0 4px -3px; width: 16px; height: 16px; cursor: pointer; }'; x += gif('.de-file-del', 'R0lGODlhEAAQALMOAP8zAMopAJMAAP/M//+DIP8pAP86Av9MDP9sFP9zHv9aC/9gFf9+HJsAAP///wAAACH5BAEAAA4ALAAAAAAQABAAAARU0MlJKw3B4hrGyFP3hQNBjE5nooLJMF/3msIkJAmCeDpeU4LFQkFUCH8VwWHJRHIM0CiIMwBYryhS4XotZDuFLUAg6LLC1l/5imykgW+gU0K22C0RADs='); x += gif('.de-file-rar', 'R0lGODlhEAAQALMAAF82SsxdwQMEP6+zzRA872NmZQesBylPHYBBHP///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAAAQABAAQARTMMlJaxqjiL2L51sGjCOCkGiBGWyLtC0KmPIoqUOg78i+ZwOCUOgpDIW3g3KJWC4t0ElBRqtdMr6AKRsA1qYy3JGgMR4xGpAAoRYkVDDWKx6NRgAAOw=='); x += '.de-menu { padding: 0 !important; margin: 0 !important; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important;}\ .de-menu-item { display: block; padding: 3px 10px; color: inherit; text-decoration: none; font: 13px arial; white-space: nowrap; cursor: pointer; }\ .de-menu-item:hover { background-color: #222; color: #fff; }\ .de-new-post { ' + (nav.Presto ? 'border-left: 4px solid blue; border-right: 4px solid blue; }' : 'box-shadow: 6px 0 2px -2px blue, -6px 0 2px -2px blue; }') + '\ .de-omitted { color: grey; font-style: italic; }\ .de-omitted:before { content: "' + Lng.postsOmitted[lang] + '"; }\ .de-opref::after { content: " [OP]"; }\ .de-parea { text-align: center; }\ .de-parea-btn-close:after { content: "' + Lng.hideForm[lang] + '" }\ .de-parea-btn-thrd:after { content: "' + Lng.makeThrd[lang] + '" }\ .de-parea-btn-reply:after { content: "' + Lng.makeReply[lang] + '" }\ .de-pview { position: absolute; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important; margin: 0 !important; display: block !important; }\ .de-pview-info { padding: 3px 6px !important; }\ .de-pview-link { font-weight: bold; }\ .de-ref-hid { text-decoration: line-through !important; }\ .de-refmap { margin: 10px 4px 4px 4px; font-size: 75%; font-style: italic; }\ .de-refmap:before { content: "' + Lng.replies[lang] + ' "; }\ .de-reflink { text-decoration: none; }\ .de-refcomma:last-child { display: none; }\ #de-sagebtn { margin-right: 7px; cursor: pointer; }\ .de-selected, .de-error-key { ' + (nav.Presto ? 'border-left: 4px solid red; border-right: 4px solid red; }' : 'box-shadow: 6px 0 2px -2px red, -6px 0 2px -2px red; }') + '\ #de-txt-resizer { display: inline-block !important; float: none !important; padding: 6px; margin: -2px -12px; vertical-align: bottom; border-bottom: 2px solid #555; border-right: 2px solid #444; cursor: se-resize; }\ #de-updater-btn:after { content: "' + Lng.getNewPosts[lang] + '" }\ #de-updater-div { clear: left; margin-top: 10px; }\ .de-viewed { color: #888 !important; }\ .de-hidden, small[id^="rfmap"], body > hr, .theader, .postarea, .thumbnailmsg { display: none !important; }\ form > hr { clear: both }\ ' + aib.css + aib.cssEn + '.de-post-hide > ' + aib.qHide + ' { display: none !important; }'; if(!nav.Firefox) { x = x.replace(/(transition|keyframes|transform|animation|linear-gradient)/g, nav.cssFix + '$1'); if(!nav.Presto) { x = x.replace(/\(to bottom/g, '(top').replace(/\(to top/g, '(bottom'); } } applyCSS(x); } function applyCSS(x) { $css(x).id = 'de-css'; $css('').id = 'de-css-dynamic'; $css('').id = 'de-css-user'; updateCSS(); } function updateCSS() { var x; if(Cfg['attachPanel']) { x = '.de-content { position: fixed; right: 0; bottom: 25px; z-index: 9999; max-height: 95%; overflow-x: visible; overflow-y: auto; }\ #de-panel { position: fixed; right: 0; bottom: 0; }' } else { x = '.de-content { clear: both; float: right; }\ #de-panel { float: right; clear: both; }' } if(Cfg['addPostForm'] === 3) { x += '#de-qarea { position: fixed; right: 0; bottom: 25px; z-index: 9990; padding: 3px; border: 1px solid gray; }\ #de-qarea-target { font-weight: bold; }\ #de-qarea-close { float: right; color: green; font: bold 20px arial; cursor: pointer; }'; } else { x += '#de-qarea { float: none; clear: left; width: 100%; padding: 3px 0 3px 3px; margin: 2px 0; }'; } if(!Cfg['panelCounter']) { x += '#de-panel-info { display: none; }'; } if(Cfg['maskImgs']) { x += '.de-img-pre, .de-video-obj, .thumb, .ca_thumb, .fileThumb, img[src*="spoiler"], img[src*="thumb"], img[src^="blob"] { opacity: 0.07 !important; }\ .de-img-pre:hover, .de-video-obj:hover, .thumb:hover, .ca_thumb:hover, .fileThumb:hover, img[src*="spoiler"]:hover, img[src*="thumb"]:hover, img[src^="blob"]:hover { opacity: 1 !important; }'; } if(!(aib.dobr || aib.krau)) { x += '.de-img-full { margin: 2px 10px; }'; } if(Cfg['delHiddPost']) { x += '.de-thr-hid, .de-thr-hid + div + br, .de-thr-hid + div + br + hr { display: none; }'; } if(Cfg['noPostNames']) { x += aib.qName + ', .' + aib.cTrip + ' { display: none; }'; } if(Cfg['noSpoilers']) { x += '.spoiler' + (aib.fch ? ', s' : '') + ' { background: #888 !important; color: #ccc !important; }'; } if(Cfg['noPostScrl']) { x += 'blockquote, blockquote > p, .code_part { max-height: 100% !important; overflow: visible !important; }'; } if(Cfg['noBoardRule']) { x += (aib.futa ? '.chui' : '.rules, #rules, #rules_row') + ' { display: none; }'; } if(aib.abu || aib.toho) { if(Cfg['addYouTube']) { x += 'div[id^="post_video"] { display: none !important; }'; } } $id('de-css-dynamic').textContent = x; $id('de-css-user').textContent = Cfg['userCSS'] ? Cfg['userCSSTxt'] : ''; } //============================================================================================================ // SCRIPT UPDATING //============================================================================================================ function checkForUpdates(isForce, Fn) { var day, temp = Cfg['scrUpdIntrv']; if(!isForce) { day = 2 * 1000 * 60 * 60 * 24; switch(temp) { case 0: temp = day; break; case 1: temp = day * 2; break; case 2: temp = day * 7; break; case 3: temp = day * 14; break; default: temp = day * 30; } if(Date.now() - +comCfg['lastUpd'] < temp) { return; } } GM_xmlhttpRequest({ 'method': 'GET', 'url': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js', 'headers': {'Content-Type': 'text/plain'}, 'onreadystatechange': function(xhr) { if(xhr.readyState !== 4) { return; } if(xhr.status === 200) { var dVer = xhr.responseText.match(/@version\s+([0-9.]+)/)[1].split('.'), cVer = version.split('.'), len = cVer.length > dVer.length ? cVer.length : dVer.length, i = 0, isUpd = false; if(!dVer) { if(isForce) { Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>'); } return; } saveComCfg('lastUpd', Date.now()); while(i < len) { if((+dVer[i] || 0) > (+cVer[i] || 0)) { isUpd = true; break; } else if((+dVer[i] || 0) < (+cVer[i] || 0)) { break; } i++; } if(isUpd) { Fn('<a style="color: blue; font-weight: bold;" href="https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.user.js">' + Lng.updAvail[lang] + '</a>'); } else if(isForce) { Fn(Lng.haveLatest[lang]); } } else if(isForce) { Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>'); } } }); } //============================================================================================================ // POSTFORM //============================================================================================================ function PostForm(form, ignoreForm, init, dc) { this.oeForm = $q('form[name="oeform"], form[action*="paint"]', dc); if(aib.abu && ($c('locked', form) || this.oeForm)) { this.form = null; if(this.oeForm) { this._init(); } return; } if(!ignoreForm && !form) { if(this.oeForm) { ajaxLoad(aib.getThrdUrl(brd, aib.getTNum(dForm)), false, function(dc, xhr) { pr = new PostForm($q(aib.qPostForm, dc), true, init, dc); }, function(eCode, eMsg, xhr) { pr = new PostForm(null, true, init, dc); }); } else { this.form = null; } return; } function $x(path, root) { return dc.evaluate(path, root, null, 8, null).singleNodeValue; } var p = './/tr[not(contains(@style,"none"))]//input[not(@type="hidden") and '; this.tNum = TNum; this.form = form; this.cap = $q('input[type="text"][name*="aptcha"], div[id*="captcha"]', form); this.txta = $q('tr:not([style*="none"]) textarea:not([style*="display:none"])', form); this.subm = $q('tr input[type="submit"]', form); this.file = $q('tr input[type="file"]', form); if(this.file) { this.fileTd = getAncestor(this.file, 'TD'); this.fileImgTd = getAncestor(this.txta, 'TD').previousElementSibling; this.fileInputs = []; } this.passw = $q('tr input[type="password"]', form); this.dpass = $q('input[type="password"], input[name="password"]', dForm); this.name = $x(p + '(@name="field1" or @name="name" or @name="internal_n" or @name="nya1" or @name="akane")]', form); this.mail = $x(p + ( aib._410 ? '@name="sage"]' : '(@name="field2" or @name="em" or @name="sage" or @name="email" or @name="nabiki" or @name="dont_bump")]' ), form); this.subj = $x(p + '(@name="field3" or @name="sub" or @name="subject" or @name="internal_s" or @name="nya3" or @name="kasumi")]', form); this.video = $q('tr input[name="video"], tr input[name="embed"]', form); this.gothr = aib.qPostRedir && (p = $q(aib.qPostRedir, form)) && getAncestor(p, 'TR'); if(init) { this._init(); } } PostForm.setUserName = function() { var el = $q('input[info="nameValue"]', doc); if(el) { saveCfg('nameValue', el.value); } pr.name.value = Cfg['userName'] ? Cfg['nameValue'] : ''; }; PostForm.setUserPassw = function() { var el = $q('input[info="passwValue"]', doc); if(el) { saveCfg('passwValue', el.value); } (pr.dpass || {}).value = pr.passw.value = Cfg['passwValue']; }; PostForm.prototype = { isHidden: false, isQuick: false, isTopForm: false, lastQuickPNum: -1, pForm: null, pArea: [], qArea: null, get fileImageTD() { var val = $t(aib.tiny ? 'th' : 'td', getAncestor(this.txta, 'TR')); val.innerHTML = ''; Object.defineProperty(this, 'fileImageTD', { value: val }); return val; }, get rarInput() { var val = doc.body.appendChild($new('input', {'type': 'file', 'style': 'display: none;'}, null)) Object.defineProperty(this, 'rarInput', { value: val }); return val; }, addTextPanel: function() { var i, len, tag, html, btns, tPanel = $id('de-txt-panel'); if(!Cfg['addTextBtns']) { $del(tPanel); return; } if(!tPanel) { tPanel = $new('span', {'id': 'de-txt-panel'}, { 'click': this, 'mouseover': this }); } tPanel.style.cssFloat = Cfg['txtBtnsLoc'] ? 'none' : 'right'; $after(Cfg['txtBtnsLoc'] ? $id('de-txt-resizer') || this.txta : aib._420 ? $c('popup', this.form) : this.subm, tPanel); for(html = '', i = 0, btns = aib.formButtons, len = btns['id'].length; i < len; ++i) { tag = btns['tag'][i]; if(tag === '') { continue; } html += '<span id="de-btn-' + btns['id'][i] + '" de-title="' + Lng.txtBtn[i][lang] + '" de-tag="' + tag + '"' + (btns['bb'][i] ? 'de-bb' : '') + '>' + ( Cfg['addTextBtns'] === 2 ? (i === 0 ? '[ ' : '') + '<a class="de-abtn" href="#">' + btns['val'][i] + '</a>' + (i === len - 1 ? ' ]' : ' / ') : Cfg['addTextBtns'] === 3 ? '<input type="button" value="' + btns['val'][i] + '" style="font-weight: bold;">' : '' ) + '</span>'; } tPanel.innerHTML = html; }, delFilesUtils: function() { for(var i = 0, ins = this.fileInputs, len = ins.length; i < len; ++i) { ins[i].delUtils(); } }, eventFiles: function(parent) { this.fileInputs = []; $each($Q('input[type="file"]', parent || this.fileTd), function(el) { if(!el.obj) { el.obj = new FileInput(this, el); el.obj.init(false); } this.fileInputs.push(el.obj); }.bind(this)); }, handleEvent: function(e) { var x, start, end, scrtop, title, id, txt, len, el = e.target; if(el.tagName !== 'SPAN') { el = el.parentNode; } id = el.id; if(id.startsWith('de-btn')) { if(e.type === 'mouseover') { if(id === 'de-btn-quote') { quotetxt = $txtSelect(); } x = -1; if(keyNav) { switch(id.substr(7)) { case 'bold': x = 12; break; case 'italic': x = 13; break; case 'strike': x = 14; break; case 'spoil': x = 15; break; case 'code': x = 16; break; } } KeyEditListener.setTitle(el, x); return; } x = pr.txta; start = x.selectionStart; end = x.selectionEnd; if(id === 'de-btn-quote') { $txtInsert(x, '> ' + (start === end ? quotetxt : x.value.substring(start, end)) .replace(/\n/gm, '\n> ')); } else { scrtop = x.scrollTop; txt = this._wrapText(el.hasAttribute('de-bb'), el.getAttribute('de-tag'), x.value.substring(start, end)); len = start + txt.length; x.value = x.value.substr(0, start) + txt + x.value.substr(end); x.setSelectionRange(len, len); x.focus(); x.scrollTop = scrtop; } $pd(e); e.stopPropagation(); } }, get isVisible() { if(!this.isHidden && this.isTopForm && $q(':focus', this.pForm)) { var cr = this.pForm.getBoundingClientRect(); return cr.bottom > 0 && cr.top < window.innerHeight; } return false; }, get topCoord() { return this.pForm.getBoundingClientRect().top; }, showQuickReply: function(post, pNum, closeReply) { var el, tNum = post.tNum; if(!this.isQuick) { this.isQuick = true; this.setReply(true, false); $t('a', this._pBtn[+this.isTopForm]).className = 'de-abtn de-parea-btn-' + (TNum ? 'reply' : 'thrd'); if(!TNum && !aib.kus && !aib.dobr) { if(this.oeForm) { $del($q('input[name="oek_parent"]', this.oeForm)); this.oeForm.insertAdjacentHTML('afterbegin', '<input type="hidden" value="' + tNum + '" name="oek_parent">'); } if(this.form) { $del($q('#thr_id, input[name="parent"]', this.form)); this.form.insertAdjacentHTML('afterbegin', '<input type="hidden" id="thr_id" value="' + tNum + '" name="' + ( aib.fch || aib.futa ? 'resto' : aib.tiny ? 'thread' : 'parent' ) + '">' ); } } } else if(closeReply && !quotetxt && post.wrap.nextElementSibling === this.qArea) { this.closeQReply(); return; } $after(post.wrap, this.qArea); if(!TNum) { this._toggleQuickReply(tNum); } if(!this.form) { return; } if(this._lastCapUpdate && ((!TNum && this.tNum !== tNum) || (Date.now() - this._lastCapUpdate > 3e5))) { this.tNum = tNum; this.refreshCapImg(false); } this.tNum = tNum; if(aib._420 && this.txta.value === 'Comment') { this.txta.value = ''; } $txtInsert(this.txta, (this.txta.value === '' || this.txta.value.slice(-1) === '\n' ? '' : '\n') + (this.lastQuickPNum === pNum && this.txta.value.contains('>>' + pNum) ? '' : '>>' + pNum + '\n') + (quotetxt ? quotetxt.replace(/^\n|\n$/g, '').replace(/(^|\n)(.)/gm, '$1> $2') + '\n': '')); if(Cfg['addPostForm'] === 3) { el = $t('a', this.qArea.firstChild); el.href = aib.getThrdUrl(brd, tNum); el.textContent = '#' + tNum; } this.lastQuickPNum = pNum; }, showMainReply: function(isTop, evt) { this.closeQReply(); if(this.isTopForm === isTop) { this.pForm.style.display = this.isHidden ? '' : 'none'; this.isHidden = !this.isHidden; this.updatePAreaBtns(); } else { this.isTopForm = isTop; this.setReply(false, false); } if(evt) { $pd(evt); } }, closeQReply: function() { if(this.isQuick) { this.isQuick = false; this.lastQuickPNum = -1; if(!TNum) { this._toggleQuickReply(0); $del($id('thr_id')); } this.setReply(false, !TNum || Cfg['addPostForm'] > 1); } }, refreshCapImg: function(focus) { var src, img; if(aib.abu && (img = $id('captcha_div')) && img.hasAttribute('onclick')) { src = {'isCustom': true, 'focus': focus}; img.dispatchEvent(new CustomEvent('click', { 'bubbles': true, 'cancelable': true, 'detail': (nav.Firefox ? cloneInto(src, document.defaultView) : src) })); return; } if(!this.cap || (aib.krau && !$q('input[name="captcha_name"]', this.form).hasAttribute('value'))) { return; } img = this.recap ? $id('recaptcha_image') : $t('img', this.capTr); if(aib.dobr || aib.krau || aib.dvachnet || this.recap) { img.click(); } else if(img) { src = img.getAttribute('src'); if(aib.kus || aib.tinyIb) { src = src.replace(/\?[^?]+$|$/, (aib._410 ? '?board=' + brd + '&' : '?') + Math.random()); } else { src = src.replace(/pl$/, 'pl?key=mainpage&amp;dummy=') .replace(/dummy=[\d\.]*/, 'dummy=' + Math.random()); src = this.tNum ? src.replace(/mainpage|res\d+/, 'res' + this.tNum) : src.replace(/res\d+/, 'mainpage'); } img.src = ''; img.src = src; } this.cap.value = ''; if(focus) { this.cap.focus(); } if(this._lastCapUpdate) { this._lastCapUpdate = Date.now(); } }, setReply: function(quick, hide) { if(quick) { this.qArea.appendChild(this.pForm); } else { $after(this.pArea[+this.isTopForm], this.qArea); $after(this._pBtn[+this.isTopForm], this.pForm); } this.isHidden = hide; this.qArea.style.display = quick ? '' : 'none'; this.pForm.style.display = hide ? 'none' : ''; this.updatePAreaBtns(); }, updatePAreaBtns: function() { var txt = 'de-abtn de-parea-btn-', rep = TNum ? 'reply' : 'thrd'; $t('a', this._pBtn[+this.isTopForm]).className = txt + (this.pForm.style.display === '' ? 'close' : rep); $t('a', this._pBtn[+!this.isTopForm]).className = txt + rep; }, _lastCapUpdate: 0, _pBtn: [], _init: function() { var btn, el; this.pForm = $New('div', {'id': 'de-pform'}, [this.form, this.oeForm]); dForm.insertAdjacentHTML('beforebegin', '<div class="de-parea"><div>[<a href="#"></a>]</div><hr></div>'); this.pArea[0] = dForm.previousSibling; this._pBtn[0] = this.pArea[0].firstChild; this._pBtn[0].firstElementChild.onclick = this.showMainReply.bind(this, false); el = aib.fch ? $c('board', dForm) : dForm; el.insertAdjacentHTML('afterend', '<div class="de-parea"><div>[<a href="#"></a>]</div><hr></div>'); this.pArea[1] = el.nextSibling; this._pBtn[1] = this.pArea[1].firstChild; this._pBtn[1].firstElementChild.onclick = this.showMainReply.bind(this, true); this.qArea = $add('<div id="de-qarea" class="' + aib.cReply + '" style="display: none;"></div>'); this.isTopForm = Cfg['addPostForm'] !== 0; this.setReply(false, !TNum || Cfg['addPostForm'] > 1); if(Cfg['addPostForm'] === 3) { $append(this.qArea, [ $add('<span id="de-qarea-target">' + Lng.replyTo[lang] + ' <a class="de-abtn"></a></span>'), $new('span', {'id': 'de-qarea-close', 'text': '\u2716'}, {'click': this.closeQReply.bind(this)}) ]); } if(aib.tire) { $each($Q('input[type="hidden"]', dForm), $del); dForm.appendChild($c('userdelete', doc.body)); this.dpass = $q('input[type="password"]', dForm); } if(!this.form) { return; } aib.disableRedirection(this.form); this.form.style.display = 'inline-block'; this.form.style.textAlign = 'left'; if(nav.Firefox) { this.txta.addEventListener('mouseup', function() { saveCfg('textaWidth', parseInt(this.style.width, 10)); saveCfg('textaHeight', parseInt(this.style.height, 10)); }, false); } else { this.txta.insertAdjacentHTML('afterend', '<div id="de-txt-resizer"></div>'); this.txta.nextSibling.addEventListener('mousedown', { el: this.txta, elStyle: this.txta.style, handleEvent: function(e) { switch(e.type) { case 'mousedown': doc.body.addEventListener('mousemove', this, false); doc.body.addEventListener('mouseup', this, false); $pd(e); return; case 'mousemove': var cr = this.el.getBoundingClientRect(); this.elStyle.width = (e.pageX - cr.left - window.pageXOffset) + 'px'; this.elStyle.height = (e.pageY - cr.top - window.pageYOffset) + 'px'; return; default: // mouseup doc.body.removeEventListener('mousemove', this, false); doc.body.removeEventListener('mouseup', this, false); saveCfg('textaWidth', parseInt(this.elStyle.width, 10)); saveCfg('textaHeight', parseInt(this.elStyle.height, 10)); } } }, false); } if(aib.kus) { while(this.subm.nextSibling) { $del(this.subm.nextSibling); } } if(Cfg['addSageBtn'] && this.mail) { btn = $new('span', {'id': 'de-sagebtn'}, {'click': function(e) { e.stopPropagation(); $pd(e); toggleCfg('sageReply'); this._setSage(); }.bind(this)}); el = getAncestor(this.mail, 'LABEL') || this.mail; if(el.nextElementSibling || el.previousElementSibling) { el.style.display = 'none'; $after(el, btn); } else { getAncestor(this.mail, 'TR').style.display = 'none'; $after(this.name || this.subm, btn); } this._setSage(); if(aib._2chru) { while(btn.nextSibling) { $del(btn.nextSibling); } } } this.addTextPanel(); this.txta.style.cssText = 'padding: 0; resize: both; width: ' + Cfg['textaWidth'] + 'px; height: ' + Cfg['textaHeight'] + 'px;'; this.txta.addEventListener('keypress', function(e) { var code = e.charCode || e.keyCode; if((code === 33 || code === 34) && e.which === 0) { e.target.blur(); window.focus(); } }, false); if(!aib.tiny) { this.subm.value = Lng.reply[lang]; } this.subm.addEventListener('click', function(e) { var temp, val = this.txta.value; if(aib._2chru && !aib.reqCaptcha) { GM_xmlhttpRequest({ 'method': 'GET', 'url': '/' + brd + '/api/requires-captcha', 'onreadystatechange': function(xhr) { if(xhr.readyState === 4 && xhr.status === 200) { aib.reqCaptcha = true; if(JSON.parse(xhr.responseText)['requires-captcha'] === '1') { $id('captcha_tr').style.display = 'table-row'; $after(this.cap, $new('span', { 'class': 'shortened', 'style': 'margin: 0px 0.5em;', 'text': 'проверить капчу'}, { 'click': function() { GM_xmlhttpRequest({ 'method': 'POST', 'url': '/' + brd + '/api/validate-captcha', 'onreadystatechange': function(str) { if(str.readyState === 4 && str.status === 200) { if(JSON.parse(str.responseText)['status'] === 'ok') { this.innerHTML = 'можно постить'; } else { this.innerHTML = 'неверная капча'; setTimeout(function() { this.innerHTML = 'проверить капчу'; }.bind(this), 1000); } } }.bind(this) }) } })) } else { this.subm.click(); } } }.bind(this) }); $pd(e); return; } if(Cfg['warnSubjTrip'] && this.subj && /#.|##./.test(this.subj.value)) { $pd(e); $alert(Lng.subjHasTrip[lang], 'upload', false); return; } if(spells.haveOutreps) { val = spells.outReplace(val); } if(this.tNum && pByNum[this.tNum].subj === 'Dollchan Extension Tools') { temp = '\n\n' + this._wrapText(aib.formButtons.bb[5], aib.formButtons.tag[5], '-'.repeat(50) + '\n' + nav.ua + '\nv' + version); if(!val.contains(temp)) { val += temp; } } this.txta.value = val; if(Cfg['ajaxReply']) { $alert(Lng.checking[lang], 'upload', true); } if(Cfg['favOnReply'] && this.tNum) { pByNum[this.tNum].thr.setFavorState(true); } if(this.video && (val = this.video.value) && (val = val.match(new YouTube().ytReg))) { this.video.value = 'http://www.youtube.com/watch?v=' + val[1]; } if(this.isQuick) { this.pForm.style.display = 'none'; this.qArea.style.display = 'none'; $after(this._pBtn[+this.isTopForm], this.pForm); } }.bind(this), false); $each($Q('input[type="text"], input[type="file"]', this.form), function(node) { node.size = 30; }); if(Cfg['noGoto'] && this.gothr) { this.gothr.style.display = 'none'; } if(Cfg['noPassword'] && this.passw) { getAncestor(this.passw, 'TR').style.display = 'none'; } window.addEventListener('load', function() { if(Cfg['userName'] && this.name) { setTimeout(PostForm.setUserName, 1e3); } if(this.passw) { setTimeout(PostForm.setUserPassw, 1e3); } }.bind(this), false); if(this.cap) { if(!(aib.fch && doc.cookie.indexOf('pass_enabled=1') > -1)) { this.capTr = getAncestor(this.cap, 'TR'); this.txta.addEventListener('focus', this._captchaInit.bind(this, this.capTr.innerHTML), false); if(this.file) { this.file.addEventListener('click', this._captchaInit.bind(this, this.capTr.innerHTML), false); } if(!aib.krau) { this.capTr.style.display = 'none'; } this.capTr.innerHTML = ''; } this.cap = null; } if(Cfg['ajaxReply'] === 2) { if(aib.krau) { this.form.removeAttribute('onsubmit'); } this.form.onsubmit = function(e) { $pd(e); if(aib.krau) { aib.addProgressTrack.click(); } new html5Submit(this.form, this.subm, checkUpload); }.bind(this); } else if(Cfg['ajaxReply'] === 1) { this.form.target = 'de-iframe-pform'; this.form.onsubmit = null; } if(el = this.file) { if('files' in el && el.files.length > 0) { el.obj = new FileInput(this, el); el.obj.clear(this.fileTd); } else { this.eventFiles(null); } } }, _setSage: function() { var c = Cfg['sageReply']; $id('de-sagebtn').innerHTML = '&nbsp;' + ( c ? '<span class="de-btn-sage"></span><b style="color: red;">SAGE</b>' : '<i>(no&nbsp;sage)</i>' ); if(this.mail.type === 'text') { this.mail.value = c ? 'sage' : aib.fch ? 'noko' : ''; } else { this.mail.checked = c; } }, _toggleQuickReply: function(tNum) { if(this.oeForm) { $q('input[name="oek_parent"], input[name="replyto"]', this.oeForm).value = tNum; } if(this.form) { $q('#thr_id, input[name*="thread"]', this.form).value = tNum; if(aib.pony) { $q('input[name="quickreply"]', this.form).value = tNum || ''; } } }, _captchaInit: function(html) { if(this.capInited) { return; } this.capTr.innerHTML = html; this.cap = $q('input[type="text"][name*="aptcha"]:not([name="recaptcha_challenge_field"])', this.capTr); if(aib.iich || aib.abu) { $t('td', this.capTr).textContent = 'Капча'; } if(aib.fch) { $script('loadRecaptcha()'); } if(aib.tire) { $script('show_captcha()'); } if(aib.krau) { aib.initCaptcha.click(); $id('captcha_image').setAttribute('onclick', 'requestCaptcha(true);'); } if(aib.dvachnet) { $script('get_captcha()'); } setTimeout(this._captchaUpd.bind(this), 100); }, _captchaUpd: function() { var img, a; if((this.recap = $id('recaptcha_response_field')) && (img = $id('recaptcha_image'))) { this.cap = this.recap; img.setAttribute('onclick', 'Recaptcha.reload()'); img.style.cssText = 'width: 300px; cursor: pointer;'; } else if(aib.fch) { setTimeout(this._captchaUpd.bind(this), 100); return; } this.capInited = true; this.cap.autocomplete = 'off'; this.cap.onkeypress = (function() { var ru = 'йцукенгшщзхъфывапролджэячсмитьбюё', en = 'qwertyuiop[]asdfghjkl;\'zxcvbnm,.`'; return function(e) { if(!Cfg['captchaLang'] || e.which === 0) { return; } var i, code = e.charCode || e.keyCode, chr = String.fromCharCode(code).toLowerCase(); if(Cfg['captchaLang'] === 1) { if(code < 0x0410 || code > 0x04FF || (i = ru.indexOf(chr)) === -1) { return; } chr = en[i]; } else { if(code < 0x0021 || code > 0x007A || (i = en.indexOf(chr)) === -1) { return; } chr = ru[i]; } $pd(e); $txtInsert(e.target, chr); }; })(); if(aib.krau) { return; } if(aib.abu || aib.dobr || aib.dvachnet || this.recap || !(img = $q('img', this.capTr))) { this.capTr.style.display = ''; return; } if(!aib.kus && !aib.tinyIb) { this._lastCapUpdate = Date.now(); this.cap.onfocus = function() { if(this._lastCapUpdate && (Date.now() - this._lastCapUpdate > 3e5)) { this.refreshCapImg(false); } }.bind(this); if(!TNum && this.isQuick) { this.refreshCapImg(false); } } img.title = Lng.refresh[lang]; img.alt = Lng.loading[lang]; img.style.cssText = 'display: block; border: none; cursor: pointer;'; img.onclick = this.refreshCapImg.bind(this, true); if((a = img.parentNode).tagName === 'A') { $after(a, img); $del(a); } this.capTr.style.display = ''; }, _wrapText: function(isBB, tag, text) { var m; if(isBB) { if(text.contains('\n')) { return '[' + tag + ']' + text + '[/' + tag + ']'; } m = text.match(/^(\s*)(.*?)(\s*)$/); return m[1] + '[' + tag + ']' + m[2] + '[/' + tag + ']' + m[3]; } for(var rv = '', i = 0, arr = text.split('\n'), len = arr.length; i < len; ++i) { m = arr[i].match(/^(\s*)(.*?)(\s*)$/); rv += '\n' + m[1] + (tag === '^H' ? m[2] + '^H'.repeat(m[2].length) : tag + m[2] + tag) + m[3]; } return rv.slice(1); } } function FileInput(form, el) { this.el = el; this.place = el.parentNode; this.form = form; } FileInput.prototype = { haveBtns: false, imgFile: null, thumb: null, clear: function(parent) { var form = this.form, cln = parent.cloneNode(false); cln.innerHTML = parent.innerHTML; parent.parentNode.replaceChild(cln, parent); this.el.obj = this; form.file = this.el = $q('input[type="file"]', cln); if(!form.fileTd.parentNode) { form.fileTd = cln; } form.eventFiles(cln); }, delUtils: function() { if(Cfg['fileThumb']) { this._delPview(); } else { $del(this._delUtil); $del(this._rjUtil); } this.imgFile = this._delUtil = this._rjUtil = null; this.haveBtns = false; this.clear(this.el.parentNode); }, updateUtils: function() { this.init(true); if(this._delUtil) { $after(this._buttonsPlace, this._delUtil); } if(this._rjUtil) { $after(this._buttonsPlace, this._rjUtil); } }, handleEvent: function(e) { switch(e.type) { case 'change': this._onFileChange(); break; case 'click': if(e.target === this._delUtil) { this.delUtils(); } else if(e.target === this._rjUtil) { this._addRarJpeg(); } else if(e.target.className === 'de-file-img') { this.el.click(); } e.stopPropagation(); $pd(e); break; case 'dragover': this.thumb.classList.add('de-file-drag'); $after(this.thumb, this.el); break; case 'dragleave': case 'drop': setTimeout(function() { this.thumb.classList.remove('de-file-drag'); var el = this.place.firstChild; if(el) { $before(el, this.el); } else { this.place.appendChild(this.el); } }.bind(this), 10); break; case 'mouseover': this.thumb.classList.add('de-file-hover'); break; case 'mouseout': this.thumb.classList.remove('de-file-hover'); } }, init: function(inited) { var imgTd, fileTr = this.form.fileTd.parentNode; if(Cfg['fileThumb']) { fileTr.style.display = 'none'; imgTd = this.form.fileImageTD; imgTd.insertAdjacentHTML('beforeend', '<div class="de-file de-file-off"><div class="de-file-img">' + '<div class="de-file-img" title="' + Lng.clickToAdd[lang] + '"></div></div></div>'); this.thumb = imgTd.lastChild; this.thumb.addEventListener('click', this, false); this.thumb.addEventListener('mouseover', this, false); this.thumb.addEventListener('mouseout', this, false); this.thumb.addEventListener('dragover', this, false); this.el.addEventListener('dragleave', this, false); this.el.addEventListener('drop', this, false); if(inited) { this._showPviewImage(); } } else if(inited) { fileTr.style.display = ''; this._delPview(); } if(!inited) { this.el.addEventListener('change', this, false); } }, _delUtil: null, _rjUtil: null, get _buttonsPlace() { return Cfg['fileThumb'] ? this.thumb.firstChild : this.el; }, _addRarJpeg: function() { var el = this.form.rarInput; el.onchange = function(e) { $del(this._rjUtil); var file = e.target.files[0], fr = new FileReader(), btnsPlace = this._buttonsPlace; btnsPlace.insertAdjacentHTML('afterend', '<span><span class="de-wait"></span>' + Lng.wait[lang] + '</span>'); this._rjUtil = btnsPlace.nextSibling; fr.onload = function(file, node, e) { if(this._buttonsPlace.nextSibling === node) { node.className = 'de-file-rarmsg de-file-utils'; node.title = this.el.files[0].name + ' + ' + file.name; node.textContent = this.el.files[0].name.replace(/^.+\./, '') + ' + ' + file.name.replace(/^.+\./, '') this.imgFile = e.target.result; } }.bind(this, file, btnsPlace.nextSibling); fr.readAsArrayBuffer(file); }.bind(this); el.click(); }, _delPview: function() { var thumb = this.thumb.firstChild.firstChild.firstChild; if(thumb) { window.URL.revokeObjectURL(thumb.src); } $del(this.thumb); this.thumb = null; }, _onFileChange: function() { if(Cfg['fileThumb']) { this._showPviewImage(); } else { this.form.eventFiles(null); } if(!this.haveBtns) { this.haveBtns = true; $after(this._buttonsPlace, this._delUtil = $new('span', { 'class': 'de-file-del de-file-utils', 'title': Lng.removeFile[lang]}, { 'click': this })); } else if(this.imgFile) { this.imgFile = null; } if(aib.fch || nav.Presto || !/^image\/(?:png|jpeg)$/.test(this.el.files[0].type)) { return; } if(this._rjUtil) { $del(this._rjUtil); this._rjUtil = null; } $after(this._buttonsPlace, this._rjUtil = $new('span', { 'class': 'de-file-rar de-file-utils', 'title': Lng.helpAddFile[lang]}, { 'click': this })); }, _showPviewImage: function() { var fr, files = this.el.files; if(files && files[0]) { fr = new FileReader(); fr.onload = function(e) { this.form.eventFiles(null); var file = this.el.files[0], thumb = this.thumb; if(!thumb) { return; } thumb.className = 'de-file'; thumb = thumb.firstChild.firstChild; thumb.title = file.name + ', ' + (file.size/1024).toFixed(2) + 'KB'; thumb.insertAdjacentHTML('afterbegin', file.type === 'video/webm' ? '<video class="de-file-img" loop autoplay muted src=""></video>' : '<img class="de-file-img" src="">'); thumb = thumb.firstChild; thumb.src = window.URL.createObjectURL(new Blob([e.target.result])); thumb = thumb.nextSibling; if(thumb) { window.URL.revokeObjectURL(thumb.src); $del(thumb); } }.bind(this); fr.readAsArrayBuffer(files[0]); } } } //============================================================================================================ // IMAGES //============================================================================================================ function genImgHash(data) { var i, j, l, c, t, u, g, buf = new Uint8Array(data[0]), oldw = data[1], oldh = data[2], tmp = oldw * oldh, newh = 8, neww = 8, levels = 3, areas = 256 / levels, values = 256 / (levels - 1), hash = 0; for(i = 0, j = 0; i < tmp; i++, j += 4) { buf[i] = buf[j] * 0.3 + buf[j + 1] * 0.59 + buf[j + 2] * 0.11; } for(i = 0; i < newh; i++) { for(j = 0; j < neww; j++) { tmp = i / (newh - 1) * (oldh - 1); l = Math.min(tmp | 0, oldh - 2); u = tmp - l; tmp = j / (neww - 1) * (oldw - 1); c = Math.min(tmp | 0, oldw - 2); t = tmp - c; hash = (hash << 4) + Math.min(values * (((buf[l * oldw + c] * ((1 - t) * (1 - u)) + buf[l * oldw + c + 1] * (t * (1 - u)) + buf[(l + 1) * oldw + c + 1] * (t * u) + buf[(l + 1) * oldw + c] * ((1 - t) * u)) / areas) | 0), 255); if(g = hash & 0xF0000000) { hash ^= g >>> 24; } hash &= ~g; } } return {hash: hash}; } function ImgBtnsShowHider(nextFn, prevFn) { dForm.insertAdjacentHTML('beforeend', '<div style="display: none;">' + '<div id="de-img-btn-next" de-title="' + Lng.nextImg[lang] + '"><div></div></div>' + '<div id="de-img-btn-prev" de-title="' + Lng.prevImg[lang] + '"><div></div></div></div>'); var btns = dForm.lastChild; this._btns = btns; this._btnsStyle = btns.style; this._nextFn = nextFn; this._prevFn = prevFn; window.addEventListener('mousemove', this, false); btns.addEventListener('mouseover', this, false); } ImgBtnsShowHider.prototype = { handleEvent: function(e) { switch(e.type) { case 'mousemove': var curX = e.clientX, curY = e.clientY; if(this._oldX !== curX || this._oldY !== curY) { this._oldX = curX; this._oldY = curY; this.show(); } break; case 'mouseover': if(!this.hasEvents) { this.hasEvents = true; this._btns.addEventListener('mouseout', this, false); this._btns.addEventListener('click', this, false); } if(!this._hidden) { clearTimeout(this._hideTmt); KeyEditListener.setTitle(this._btns.firstChild, 17); KeyEditListener.setTitle(this._btns.lastChild, 4); } break; case 'mouseout': this._setHideTmt(); break; case 'click': switch(e.target.parentNode.id) { case 'de-img-btn-next': this._nextFn(); return; case 'de-img-btn-prev': this._prevFn(); return; default: return; } } }, hide: function() { this._btnsStyle.display = 'none'; this._hidden = true; this._oldX = this._oldY = -1; }, remove: function() { $del(this._btns); window.removeEventListener('mousemove', this, false); clearTimeout(this._hideTmt); }, show: function() { if(this._hidden) { this._btnsStyle.display = ''; this._hidden = false; this._setHideTmt(); } }, _hasEvents: false, _hideTmt: 0, _hidden: true, _oldX: -1, _oldY: -1, _setHideTmt: function() { clearTimeout(this._hideTmt); this._hideTmt = setTimeout(this.hide.bind(this), 2000); } }; function AttachmentViewer(data) { this._show(data); } AttachmentViewer.prototype = { data: null, close: function(e) { if(this.hasOwnProperty('_btns')) { this._btns.remove(); } this._remove(e); }, handleEvent: function(e) { var temp, isOverEvent = false; if(this.data.isVideo && this.data.isControlClick(e, this._elStyle.height)) { return; } switch(e.type) { case 'mousedown': this._oldX = e.clientX; this._oldY = e.clientY; doc.body.addEventListener('mousemove', this, true); doc.body.addEventListener('mouseup', this, true); break; case 'mousemove': var curX = e.clientX, curY = e.clientY; if(curX !== this._oldX || curY !== this._oldY) { this._elStyle.left = parseInt(this._elStyle.left, 10) + curX - this._oldX + 'px'; this._elStyle.top = parseInt(this._elStyle.top, 10) + curY - this._oldY + 'px'; this._oldX = curX; this._oldY = curY; this._moved = true; } return; case 'mouseup': doc.body.removeEventListener('mousemove', this, true); doc.body.removeEventListener('mouseup', this, true); return; case 'click': if(e.button === 0) { if(this._moved) { this._moved = false; } else { this.close(e); Attachment.viewer = null; } e.stopPropagation(); break; } return; case 'mouseover': isOverEvent = true; case 'mouseout': temp = e.relatedTarget; if(!temp || (temp !== this._obj && !this._obj.contains(temp))) { if(isOverEvent) { Pview.mouseEnter(this.data.post); } else if(Pview.top && this.data.post.el !== temp && !this.data.post.el.contains(temp)) { Pview.top.markToDel(); } } return; default: // wheel event var curX = e.clientX, curY = e.clientY, oldL = parseInt(this._elStyle.left, 10), oldT = parseInt(this._elStyle.top, 10), oldW = parseFloat(this._elStyle.width), oldH = parseFloat(this._elStyle.height), d = nav.Firefox ? -e.detail : e.wheelDelta, newW = oldW * (d > 0 ? 1.25 : 0.8), newH = oldH * (d > 0 ? 1.25 : 0.8); this._elStyle.width = newW + 'px'; this._elStyle.height = newH + 'px'; this._elStyle.left = parseInt(curX - (newW/oldW) * (curX - oldL), 10) + 'px'; this._elStyle.top = parseInt(curY - (newH/oldH) * (curY - oldT), 10) + 'px'; } $pd(e); }, navigate: function(isForward) { var data = this.data; do { data = this._navigateHelper(data, isForward); } while(!data.isVideo && !data.isImage); this.update(data, null); }, update: function(data, showButtons, e) { this._remove(e); this._show(data, showButtons); }, _data: null, _elStyle: null, _obj: null, _oldX: 0, _oldY: 0, _moved: false, get _btns() { var val = new ImgBtnsShowHider(this.navigate.bind(this, true), this.navigate.bind(this, false)); Object.defineProperty(this, '_btns', { value: val }); return val; }, _getHolder: function(data) { var obj, html, size = data.computeFullSize(false), el = data.getFullObject(), screenWidth = Post.sizing.wWidth, screenHeight = Post.sizing.wHeight; html = '<div class="de-pic-holder de-img-center" style="top:' + ((screenHeight - size[1]) / 2 - 1) + 'px; left:' + ((screenWidth - size[0]) / 2 - 1) + 'px; width:' + size[0] + 'px; height:' + size[1] + 'px; display: block"></div>'; obj = $add(html); if(data.isImage) { obj.insertAdjacentHTML('afterbegin', '<a href="' + data.src + '"></a>'); obj.firstChild.appendChild(el); } else { obj.appendChild(el); } return obj; }, _navigateHelper: function(data, isForward) { var post = data.post, imgs = post.allImages; if(isForward ? data.idx + 1 === imgs.length : data.idx === 0) { do { post = post.getAdjacentVisPost(!isForward); if(!post) { post = isForward ? firstThr.op : lastThr.last; if(post.hidden || post.thr.hidden) { post = post.getAdjacentVisPost(!isForward); } } imgs = post.allImages; } while(imgs.length === 0); return imgs[isForward ? 0 : imgs.length - 1]; } return imgs[isForward ? data.idx + 1 : data.idx - 1] }, _show: function(data) { var obj = this._getHolder(data), style = obj.style; this._elStyle = style; this.data = data; this._obj = obj; obj.addEventListener(nav.Firefox ? 'DOMMouseScroll' : 'mousewheel', this, true); obj.addEventListener('mousedown', this, true); obj.addEventListener('click', this, true); if(data.inPview) { obj.addEventListener('mouseover', this, true); obj.addEventListener('mouseout', this, true); } if(!data.inPview) { this._btns.show(); } else if(this.hasOwnProperty('_btns')) { this._btns.hide(); } dForm.appendChild(obj); }, _remove: function(e) { $del(this._obj); if(e && this.data.inPview) { this.data.sendCloseEvent(e, false); } } }; function IAttachmentData() {} IAttachmentData.prototype = { expanded: false, get inPview() { var val = this.post.isPview; Object.defineProperty(this, 'inPview', { value: val }); return val; }, get isImage() { var val = /\.jpe?g|\.png|\.gif/i.test(this.src) || (this.src.startsWith('blob:') && !this.el.hasAttribute('de-video')); Object.defineProperty(this, 'isImage', { value: val }); return val; }, get isVideo() { var val = /\.webm$/i.test(this.src) || (this.src.startsWith('blob:') && this.el.hasAttribute('de-video')); Object.defineProperty(this, 'isVideo', { value: val }); return val; }, get height() { var dat = this._getImageSize(); Object.defineProperties(this, { 'width': { value: dat[0] }, 'height': { value: dat[1] } }); return dat[1]; }, get src() { var val = this._getImageSrc();; Object.defineProperty(this, 'src', { value: val }); return val; }, get width() { var dat = this._getImageSize(); Object.defineProperties(this, { 'width': { value: dat[0] }, 'height': { value: dat[1] } }); return dat[0]; }, get wrap() { var val = this._getImageWrap(); Object.defineProperty(this, 'wrap', { value: val }); return val; }, collapse: function(e) { if(!this.isVideo || !this.isControlClick(e, this._fullEl.style.height)) { this.expanded = false; $del(this._fullEl); this._fullEl = null; this.el.parentNode.style.display = ''; $del((aib.hasPicWrap ? this.wrap : this.el.parentNode).nextSibling); if(e && this.inPview) { this.sendCloseEvent(e, true); } return true; } return false; }, computeFullSize: function(inPost) { var newH, newW, scrH, scrW = inPost ? Post.sizing.wWidth - this._offset : Post.sizing.wWidth; newW = !Cfg['resizeImgs'] || this.width < (scrW - 5) ? this.width : scrW - 5; newH = newW * this.height / this.width; if(!inPost) { scrH = Post.sizing.wHeight; if(Cfg['resizeImgs'] && newH > scrH) { newH = scrH - 2; newW = newH * this.width / this.height; } } return [newW / Post.sizing.dPxRatio, newH / Post.sizing.dPxRatio]; }, expand: function(inPost, e) { var size, el = this.el; if(!inPost) { if(Attachment.viewer) { if(Attachment.viewer.data === this) { Attachment.viewer.close(e); Attachment.viewer = null; return; } Attachment.viewer.update(this, e); } else { Attachment.viewer = new AttachmentViewer(this); } return; } this.expanded = true; (aib.hasPicWrap ? this.wrap : el.parentNode).insertAdjacentHTML('afterend', '<div class="de-after-fimg"></div>'); size = this.computeFullSize(inPost); el.parentNode.style.display = 'none'; this._fullEl = this.getFullObject(); this._fullEl.className = 'de-img-full'; this._fullEl.style.width = size[0] + 'px'; this._fullEl.style.height = size[1] + 'px'; $after(el.parentNode, this._fullEl); }, getFullObject: function() { var obj; if(this.isVideo) { if(nav.canPlayWebm) { obj = $add('<video style="width: 100%; height: 100%" src="' + this.src + '" loop autoplay ' + (Cfg['webmControl'] ? 'controls ' : '') + (Cfg['webmVolume'] === 0 ? 'muted ' : '') + '></video>'); if(Cfg['webmVolume'] !== 0) { obj.oncanplay = function() { this.volume = Cfg['webmVolume'] / 100; }; } obj.onerror = function() { if(!this.onceLoaded) { this.load(); this.onceLoaded = true; } }; obj.onvolumechange = function() { saveCfg('webmVolume', Math.round(this.volume * 100)); }; } else { obj = $add('<object style="width: 100%; height: 100%" data="' + this.src + '" type="video/quicktime">' + '<param name="pluginurl" value="http://www.apple.com/quicktime/download/" />' + '<param name="controller" value="' + (Cfg['webmControl'] ? 'true' : 'false') + '" />' + '<param name="autoplay" value="true" />' + '<param name="scale" value="tofit" />' + '<param name="volume" value="' + Math.round(Cfg['webmVolume'] * 2.55) + '" />' + '<param name="wmode" value="transparent" /></object>'); } } else { obj = $add('<img style="width: 100%; height: 100%" src="' + this.src + '" alt="' + this.src + '"></a>'); obj.onload = obj.onerror = function(e) { if(this.naturalHeight + this.naturalWidth === 0 && !this.onceLoaded) { this.src = this.src; this.onceLoaded = true; } }; } return obj; }, isControlClick: function(e, styleHeight) { return Cfg['webmControl'] && e.clientY > (e.target.getBoundingClientRect().top + parseInt(styleHeight, 10) - 30); }, sendCloseEvent: function(e, inPost) { var pv = this.post, cr = pv.el.getBoundingClientRect(), x = e.pageX - pageXOffset, y = e.pageY - pageYOffset; if(!inPost) { while(x > cr.right || x < cr.left || y > cr.bottom || y < cr.top) { if(pv = pv.parent) { cr = pv.el.getBoundingClientRect(); } else { if(Pview.top) { Pview.top.markToDel(); } return; } } if(pv.kid) { pv.kid.markToDel(); } else { clearTimeout(Pview.delTO); } } else if(x > cr.right || y > cr.bottom && Pview.top) { Pview.top.markToDel(); } }, _fullEl: null, get _offset() { var val = -1; if(this._useCache) { val = this._glob._offset; } if(val === -1) { if(this.post.hidden) { this.post.hideContent(false); val = this.el.getBoundingClientRect().left + window.pageXOffset; this.post.hideContent(true); } else { val = this.el.getBoundingClientRect().left + window.pageXOffset; } if(this._useCache) { this._glob._offset = val; } } Object.defineProperty(this, '_offset', { value: val }); return val; } }; function EmbeddedImage(post, el, idx) { this.post = post; this.el = el; this.idx = idx; } EmbeddedImage.prototype = Object.create(IAttachmentData.prototype, { _useCache: { value: false }, _getImageSize: { value: function() { var iEl = new Image(); iEl.src = this.el.src; return [iEl.width, iEl.height]; } }, _getImageSrc: { value: function() { return this.el.src; } }, _getImageWrap: { value: function() { return this.el.parentNode; } } }); function Attachment(post, el, idx) { this.post = post; this.el = el; this.idx = idx; } Attachment.viewer = null; Attachment.prototype = Object.create(IAttachmentData.prototype, { data: { get: function() { var img = this.el, cnv = this._glob.canvas, w = cnv.width = img.naturalWidth, h = cnv.height = img.naturalHeight, ctx = cnv.getContext('2d'); ctx.drawImage(img, 0, 0); return [ctx.getImageData(0, 0, w, h).data.buffer, w, h]; } }, hash: { configurable: true, get: function() { var hash; if(this._processing) { this._needToHide = true; } else if(aib.fch || this.el.complete) { hash = this._maybeGetHash(null); if(hash !== null) { return hash; } } else { this.el.onload = this.el.onerror = this._onload.bind(this); } this.post.hashImgsBusy++; return null; } }, info: { configurable: true, get: function() { var el = $c(aib.cFileInfo, this.wrap), val = el ? el.textContent : ''; Object.defineProperty(this, 'info', { value: val }); return val; } }, weight: { configurable: true, get: function() { var val = aib.getImgWeight(this.info); Object.defineProperty(this, 'weight', { value: val }); return val; } }, getHash: { value: function atGetHash(Fn) { if(this.hasOwnProperty('hash')) { Fn(this.hash); } else { this.callback = Fn; if(!this._processing) { var hash = this._maybeGetHash(); if(hash !== null) { Fn(hash); } } } } }, _glob: { value: { get canvas() { var val = doc.createElement('canvas'); Object.defineProperty(this, 'canvas', { value: val }); return val; }, get storage() { try { var val = JSON.parse(sesStorage['de-imageshash']); } finally { if(!val) { val = {}; } spells.addCompleteFunc(this._saveStorage.bind(this)); Object.defineProperty(this, 'storage', { value: val }); return val; } }, get workers() { var val = new workerQueue(4, genImgHash, function(e) {}); spells.addCompleteFunc(this._clearWorkers.bind(this)); Object.defineProperty(this, 'workers', { value: val, configurable: true }); return val; }, _expAttach: null, _offset: -1, _saveStorage: function() { sesStorage['de-imageshash'] = JSON.stringify(this.storage); }, _clearWorkers: function() { this.workers.clear(); delete this.workers; } } }, _callback: { writable: true, value: null }, _processing: { writable: true, value: false }, _needToHide: { writable: true, value: false }, _useCache: { configurable: true, get: function() { var val = !this.inPview && this.post.count > 4; Object.defineProperty(this, '_useCache', { value: val }); return val; } }, _getImageSize: { value: function atGetImgSize() { return aib.getImgSize(this.info); } }, _getImageSrc: { value: function atGetImageSrc() { return aib.getImgLink(this.el).href; } }, _getImageWrap: { value: function atGetImageWrap() { return aib.getImgWrap(this.el.parentNode); } }, _endLoad: { value: function atEndLoad(hash) { this.post.hashImgsBusy--; if(this.post.hashHideFun !== null) { this.post.hashHideFun(hash); } } }, _maybeGetHash: { value: function atMaybeGetHash() { var data, val; if(this.src in this._glob.storage) { val = this._glob.storage[this.src]; } else if(aib.fch) { downloadImgData(this.el.src, this._onload4chan.bind(this)); this._callback = null; return null; } else if(this.el.naturalWidth + this.el.naturalHeight === 0) { val = -1; } else { data = this.data; this._glob.workers.run(data, [data[0]], this._wrkEnd.bind(this)); this._callback = null; return null; } Object.defineProperty(this, 'hash', { value: val }); return val; } }, _onload: { value: function atOnLoad() { var hash = this._maybeGetHash(null); if(hash !== null) { this._endLoad(hash); } } }, _onload4chan: { value: function atOnload4chan(maybeData) { if(maybeData === null) { Object.defineProperty(this, 'hash', { value: -1 }); this._endLoad(-1); } else { var buffer = maybeData.buffer, data = [buffer, this.el.naturalWidth, this.el.naturalHeight]; this._glob.workers.run(data, [buffer], this._wrkEnd.bind(this)); } } }, _wrkEnd: { value: function atWrkEnd(data) { var hash = data.hash; Object.defineProperty(this, 'hash', { value: hash }); this._endLoad(hash); if(this.callback) { this.callback(hash); this.callback = null; } this._glob.storage[this.src] = hash; } } }); function addImagesSearch(el) { for(var link, i = 0, els = $Q(aib.qImgLink, el), len = els.length; i < len; i++) { link = els[i]; if(/google\.|tineye\.com|iqdb\.org/.test(link.href)) { $del(link); continue; } if(link.firstElementChild) { continue; } link.insertAdjacentHTML('beforebegin', '<span class="de-btn-src" de-menu="imgsrc"></span>'); } } function embedImagesLinks(el) { for(var a, link, i = 0, els = $Q(aib.qMsgImgLink, el); link = els[i++];) { if(link.parentNode.tagName === 'SMALL') { return; } a = link.cloneNode(false); a.target = '_blank'; a.innerHTML = '<img class="de-img-pre" src="' + a.href + '">'; $before(link, a); } } //============================================================================================================ // POST //============================================================================================================ function Post(el, thr, num, count, isOp, prev) { var refEl, html; this.count = count; this.el = el; this.isOp = isOp; this.num = num; this._pref = refEl = $q(aib.qRef, el); this.prev = prev; this.thr = thr; this.ref = []; if(prev) { prev.next = this; } el.post = this; html = '<span class="de-ppanel' + (isOp ? '' : ' de-ppanel-cnt') + '"><span class="de-btn-hide" de-menu="hide"></span><span class="de-btn-rep"></span>'; if(isOp) { if(!TNum && !aib.arch) { html += '<span class="de-btn-expthr" de-menu="expand"></span>'; } html += '<span class="de-btn-fav"></span>'; } if(this.sage = aib.getSage(this.el)) { html += '<span class="de-btn-sage" title="SAGE"></span>'; } // html += '<span class="de-btn-udolil" style="font-weight: bold; color: red; cursor: pointer;">[УДОЛИЛ!!11]</span>'; refEl.insertAdjacentHTML('afterend', html + '</span>'); this.btns = refEl.nextSibling; if(Cfg['expandPosts'] === 1 && this.trunc) { this._getFull(this.trunc, true); } el.addEventListener('mouseover', this, true); } Post.hiddenNums = []; Post.getWrds = function(text) { return text.replace(/\s+/g, ' ').replace(/[^a-zа-яё ]/ig, '').substring(0, 800).split(' '); }; Post.findSameText = function(oNum, oHid, oWords, date, post) { var j, words = Post.getWrds(post.text), len = words.length, i = oWords.length, olen = i, _olen = i, n = 0; if(len < olen * 0.4 || len > olen * 3) { return; } while(i--) { if(olen > 6 && oWords[i].length < 3) { _olen--; continue; } j = len; while(j--) { if(words[j] === oWords[i] || oWords[i].match(/>>\d+/) && words[j].match(/>>\d+/)) { n++; } } } if(n < _olen * 0.4 || len > _olen * 3) { return; } if(oHid) { post.note = ''; if(!post.spellHidden) { post.setVisib(false); } if(post.userToggled) { delete bUVis[brd][post.num]; post.userToggled = false; } } else { post.setUserVisib(true, date, true); post.note = 'similar to >>' + oNum; } return false; }; Post.sizing = { get dPxRatio() { var val = window.devicePixelRatio || 1; Object.defineProperty(this, 'dPxRatio', { value: val }); return val; }, get wHeight() { var val = window.innerHeight; if(!this._enabled) { window.addEventListener('resize', this, false); this._enabled = true; } Object.defineProperties(this, { 'wWidth': { writable: true, configurable: true, value: doc.documentElement.clientWidth }, 'wHeight': { writable: true, configurable: true, value: val } }); return val; }, get wWidth() { var val = doc.documentElement.clientWidth; if(!this._enabled) { window.addEventListener('resize', this, false); this._enabled = true; } Object.defineProperties(this, { 'wWidth': { writable: true, configurable: true, value: val }, 'wHeight': { writable: true, configurable: true, value: window.innerHeight } }); return val; }, handleEvent: function() { this.wHeight = window.innerHeight; this.wWidth = doc.documentElement.clientWidth; }, _enabled: false }; Post.prototype = { banned: false, deleted: false, hasRef: false, hasYTube: false, hidden: false, hashHideFun: null, hashImgsBusy: 0, imagesExpanded: false, inited: true, isPview: false, kid: null, next: null, omitted: false, parent: null, prev: null, spellHidden: false, sticked: false, userToggled: false, viewed: false, ytHideFun: null, ytInfo: null, ytLinksLoading: 0, addFuncs: function() { updRefMap(this, true); embedMP3Links(this); if(Cfg['addImgs']) { embedImagesLinks(this.el); } if(isExpImg) { this.toggleImages(true); } }, handleEvent: function(e) { var temp, el = e.target, type = e.type, isOutEvent = type === 'mouseout'; if(type === 'click') { if(e.button !== 0) { return; } switch(el.tagName) { case 'IMG': if(el.classList.contains('de-video-thumb')) { if(Cfg['addYouTube'] === 3) { this.ytLink.classList.add('de-current'); new YouTube().addPlayer(this.ytObj, this.ytInfo, el.classList.contains('de-ytube')); $pd(e); } } else if(Cfg['expandImgs'] !== 0) { this._clickImage(el, e); } return; case 'VIDEO': if(Cfg['expandImgs'] !== 0 && !(Cfg['webmControl'] && e.clientY > (el.getBoundingClientRect().top + parseInt(el.style.height, 10) - 30))) { this._clickImage(el, e); } return; case 'A': if(el.classList.contains('de-video-link')) { var m = el.ytInfo; if(this.ytInfo === m) { if(Cfg['addYouTube'] === 3) { if($c('de-video-thumb', this.ytObj)) { el.classList.add('de-current'); new YouTube().addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } else { el.classList.remove('de-current'); new YouTube().addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } } else { el.classList.remove('de-current'); this.ytObj.innerHTML = ''; this.ytInfo = null; } } else if(Cfg['addYouTube'] > 2) { this.ytLink.classList.remove('de-current'); this.ytLink = el; new YouTube().addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } else { this.ytLink.classList.remove('de-current'); this.ytLink = el; el.classList.add('de-current'); new YouTube().addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube')); } $pd(e); } else { temp = el.parentNode; if(temp === this.trunc) { this._getFull(temp, false); $pd(e); e.stopPropagation(); } else if(Cfg['insertNum'] && pr.form && temp === this._pref && !/Reply|Ответ/.test(el.textContent)) { if(TNum && Cfg['addPostForm'] > 1 && !pr.isQuick) { pr.showQuickReply(this, this.num, true); } else { if(aib._420 && pr.txta.value === 'Comment') { pr.txta.value = ''; } $txtInsert(pr.txta, '>>' + this.num); } $pd(e); e.stopPropagation(); } } return; } switch(el.className) { case 'de-btn-expthr': this.thr.load(1, false, null); $del(this._menu); this._menu = null; return; case 'de-btn-fav': this.thr.setFavorState(true); return; case 'de-btn-fav-sel': this.thr.setFavorState(false); return; case 'de-btn-hide': case 'de-btn-hide-user': if(this.isPview) { pByNum[this.num].toggleUserVisib(); this.btns.firstChild.className = 'de-btn-hide-user'; if(pByNum[this.num].hidden) { this.btns.classList.add('de-post-hide'); } else { this.btns.classList.remove('de-post-hide'); } } else { this.toggleUserVisib(); } $del(this._menu); this._menu = null; return; case 'de-btn-rep': pr.showQuickReply(this.isPview ? this.getTopParent() : this, this.num, !this.isPview); return; case 'de-btn-sage': addSpell(9, '', false); return; case 'de-btn-stick': case 'de-btn-stick-on': el.className = this.sticked ? 'de-btn-stick' : 'de-btn-stick-on'; this.sticked = !this.sticked; return; case 'de-btn-udolil': this.thr.deletePost(this, false, true); return; } if(el.classList[0] === 'de-menu-item') { this._clickMenu(el); } return; } if(!this._hasEvents) { this._hasEvents = true; this.el.addEventListener('click', this, true); this.el.addEventListener('mouseout', this, true); } else if(this.isPview && isOutEvent) { this._handleMouseEvents(e.relatedTarget, false); } switch(el.classList[0]) { case 'de-reflink': case 'de-preflink': if(Cfg['linksNavig']) { if(isOutEvent) { clearTimeout(this._linkDelay); if(this.kid) { this.kid.markToDel(); } } else { clearTimeout(Pview.delTO); this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']); } $pd(e); e.stopPropagation(); } return; case 'de-btn-expthr': case 'de-btn-hide': case 'de-btn-hide-user': this._addButtonTitle(el); case 'de-btn-src': if(isOutEvent) { this._closeMenu(e.relatedTarget); } else { this._menuDelay = setTimeout(this._addMenu.bind(this, el), Cfg['linksOver']); } return; case 'de-btn-rep': this._addButtonTitle(el); if(!isOutEvent) { quotetxt = $txtSelect(); } return; case 'de-menu': case 'de-menu-item': if(isOutEvent) { this._closeMenu(e.relatedTarget); } else { clearTimeout(this._menuDelay); } return; } if(Cfg['linksNavig'] && el.tagName === 'A' && !el.lchecked) { if(el.textContent.startsWith('>>')) { el.className = 'de-preflink ' + el.className; clearTimeout(Pview.delTO); this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']); $pd(e); e.stopPropagation(); } else { el.lchecked = true; } return; } if(this.isPview && !isOutEvent) { this._handleMouseEvents(e.relatedTarget, true); } }, hideContent: function(hide) { if(hide) { this.el.classList.add('de-post-hide'); } else { this.el.classList.remove('de-post-hide'); } if(nav.Chrome) { if(hide) { this.el.classList.remove('de-post-unhide'); } else { this.el.classList.add('de-post-unhide'); } if(!chromeCssUpd) { chromeCssUpd = setTimeout(function() { doc.head.insertAdjacentHTML('beforeend', '<style id="de-csshide" type="text/css">\ .de-post-hide > ' + aib.qHide + ' { display: none !important; }\ .de-post-unhide > ' + aib.qHide + ' { display: !important; }\ </style>'); $del(doc.head.lastChild); chromeCssUpd = null; }, 200); } } }, hideRefs: function() { if(!Cfg['hideRefPsts'] || !this.hasRef) { return; } this.ref.forEach(function(num) { var pst = pByNum[num]; if(pst && !pst.userToggled) { pst.setVisib(true); pst.note = 'reference to >>' + this.num; pst.hideRefs(); } }, this); }, getAdjacentVisPost: function(toUp) { var post = toUp ? this.prev : this.next; while(post) { if(post.thr.hidden) { post = toUp ? post.thr.op.prev : post.thr.last.next; } else if(post.hidden || post.omitted) { post = toUp ? post.prev : post.next } else { return post; } } return null; }, get html() { var val = this.el.innerHTML; Object.defineProperty(this, 'html', { configurable: true, value: val }); return val; }, get images() { var i, len, el, els = $Q(aib.qThumbImages, this.el), imgs = []; for(i = 0, len = els.length; i < len; ++i) { el = els[i]; el.imgIdx = i; imgs.push(new Attachment(this, el, i)); } Object.defineProperty(this, 'images', { value: imgs }); return imgs; }, get allImages() { var i, len, el, els, val = this.images.slice(), allIdx = val.length; if(Cfg['addImgs']) { for(i = 0, els = $C('de-img-pre', this.el), len = els.length; i < len; ++i, ++allIdx) { el = els[i]; el.imgIdx = allIdx; val.push(new EmbeddedImage(this, el, allIdx)); } } Object.defineProperty(this, 'allImages', { value: val }); return val; }, get mp3Obj() { var val = $new('div', {'class': 'de-mp3'}, null); $before(this.msg, val); Object.defineProperty(this, 'mp3Obj', { value: val }); return val; }, get msg() { var val = $q(aib.qMsg, this.el); Object.defineProperty(this, 'msg', { configurable: true, value: val }); return val; }, get nextInThread() { var post = this.next; return !post || post.count === 0 ? null : post; }, get nextNotDeleted() { var post = this.nextInThread; while(post && post.deleted) { post = post.nextInThread; } return post; }, set note(val) { if(this.isOp) { this.noteEl.textContent = val ? '(autohide: ' + val + ')' : '(' + this.title + ')'; } else if(!Cfg['delHiddPost']) { this.noteEl.textContent = val ? 'autohide: ' + val : ''; } }, get noteEl() { var val; if(this.isOp) { val = this.thr.el.previousElementSibling.lastChild; } else { this.btns.insertAdjacentHTML('beforeend', '<span class="de-post-note"></span>'); val = this.btns.lastChild; } Object.defineProperty(this, 'noteEl', { value: val }); return val; }, get posterName() { var pName = $q(aib.qName, this.el), val = pName ? pName.textContent : ''; Object.defineProperty(this, 'posterName', { value: val }); return val; }, get posterTrip() { var pTrip = $c(aib.cTrip, this.el), val = pTrip ? pTrip.textContent : ''; Object.defineProperty(this, 'posterTrip', { value: val }); return val; }, select: function() { if(this.isOp) { if(this.hidden) { this.thr.el.previousElementSibling.classList.add('de-selected'); } this.thr.el.classList.add('de-selected'); } else { this.el.classList.add('de-selected'); } }, setUserVisib: function(hide, date, sync) { this.setVisib(hide); this.btns.firstChild.className = 'de-btn-hide-user'; this.userToggled = true; if(hide) { this.note = ''; this.hideRefs(); } else { this.unhideRefs(); } bUVis[brd][this.num] = [+!hide, date]; if(sync) { locStorage['__de-post'] = JSON.stringify({ 'brd': brd, 'date': date, 'isOp': this.isOp, 'num': this.num, 'hide': hide, 'title': this.isOp ? this.title : '' }); locStorage.removeItem('__de-post'); } }, setVisib: function(hide) { var el, tEl; if(this.hidden === hide) { return; } if(this.isOp) { this.hidden = this.thr.hidden = hide; tEl = this.thr.el; tEl.style.display = hide ? 'none' : ''; el = $id('de-thr-hid-' + this.num); if(el) { el.style.display = hide ? '' : 'none'; } else { tEl.insertAdjacentHTML('beforebegin', '<div class="' + aib.cReply + ' de-thr-hid" id="de-thr-hid-' + this.num + '">' + Lng.hiddenThrd[lang] + ' <a href="#">№' + this.num + '</a> <span class="de-thread-note"></span></div>'); el = $t('a', tEl.previousSibling); el.onclick = el.onmouseover = el.onmouseout = function(e) { switch(e.type) { case 'click': this.toggleUserVisib(); $pd(e); return; case 'mouseover': this.thr.el.style.display = ''; return; default: // mouseout if(this.hidden) { this.thr.el.style.display = 'none'; } } }.bind(this); } return; } if(Cfg['delHiddPost']) { if(hide) { this.wrap.classList.add('de-hidden'); this.wrap.insertAdjacentHTML('beforebegin', '<span style="counter-increment: de-cnt 1;"></span>'); } else if(this.hidden) { this.wrap.classList.remove('de-hidden'); $del(this.wrap.previousSibling); } } else { if(!hide) { this.note = ''; } this._pref.onmouseover = this._pref.onmouseout = hide && function(e) { this.hideContent(e.type === 'mouseout'); }.bind(this); } this.hidden = hide; this.hideContent(hide); if(Cfg['strikeHidd']) { setTimeout(this._strikePostNum.bind(this, hide), 50); } }, spellHide: function(note) { this.spellHidden = true; if(!this.userToggled) { if(TNum && !this.deleted) { sVis[this.count] = 0; } if(!this.hidden) { this.hideRefs(); } this.setVisib(true); this.note = note; } }, spellUnhide: function() { this.spellHidden = false; if(!this.userToggled) { if(TNum && !this.deleted) { sVis[this.count] = 1; } this.setVisib(false); this.unhideRefs(); } }, get subj() { var subj = $c(aib.cSubj, this.el), val = subj ? subj.textContent : ''; Object.defineProperty(this, 'subj', { value: val }); return val; }, get text() { var val = this.msg.innerHTML .replace(/<\/?(?:br|p|li)[^>]*?>/gi,'\n') .replace(/<[^>]+?>/g,'') .replace(/&gt;/g, '>') .replace(/&lt;/g, '<') .replace(/&nbsp;/g, '\u00A0') .trim(); Object.defineProperty(this, 'text', { configurable: true, value: val }); return val; }, get title() { var val = this.subj || this.text.substring(0, 70).replace(/\s+/g, ' ') Object.defineProperty(this, 'title', { value: val }); return val; }, get tNum() { return this.thr.num; }, toggleImages: function(expand) { for(var dat, i = 0, imgs = this.allImages, len = imgs.length; i < len; ++i) { dat = imgs[i]; if(dat.isImage && (dat.expanded ^ expand)) { if(expand) { dat.expand(true, null); } else { dat.collapse(null); } } } this.imagesExpanded = expand; }, toggleUserVisib: function() { var isOp = this.isOp, hide = !this.hidden, date = Date.now(); this.setUserVisib(hide, date, true); if(isOp) { if(hide) { hThr[brd][this.num] = this.title; } else { delete hThr[brd][this.num]; } saveHiddenThreads(false); } saveUserPosts(true); }, get topCoord() { var el = this.isOp && this.hidden ? this.thr.el.previousElementSibling : this.el; return el.getBoundingClientRect().top; }, get trunc() { var el = $q(aib.qTrunc, this.el), val = null; if(el && /long|full comment|gekürzt|слишком|длинн|мног|полная версия/i.test(el.textContent)) { val = el; } Object.defineProperty(this, 'trunc', { configurable: true, value: val }); return val; }, unhideRefs: function() { if(!Cfg['hideRefPsts'] || !this.hasRef) { return; } this.ref.forEach(function(num) { var pst = pByNum[num]; if(pst && pst.hidden && !pst.userToggled && !pst.spellHidden) { pst.setVisib(false); pst.unhideRefs(); } }); }, unselect: function() { if(this.isOp) { var el = $id('de-thr-hid-' + this.num); if(el) { el.classList.remove('de-selected'); } this.thr.el.classList.remove('de-selected'); } else { this.el.classList.remove('de-selected'); } }, updateMsg: function(newMsg) { var origMsg = aib.dobr ? this.msg.firstElementChild : this.msg, ytExt = $c('de-video-ext', origMsg), ytLinks = $Q(':not(.de-video-ext) > .de-video-link', origMsg); origMsg.parentNode.replaceChild(newMsg, origMsg); Object.defineProperties(this, { 'msg': { configurable: true, value: newMsg }, 'trunc': { configurable: true, value: null } }); delete this.html; delete this.text; new YouTube().updatePost(this, ytLinks, $Q('a[href*="youtu"]', newMsg), false); if(ytExt) { newMsg.appendChild(ytExt); } this.addFuncs(); spells.check(this); closeAlert($id('de-alert-load-fullmsg')); }, get wrap() { var val = aib.getWrap(this.el, this.isOp); Object.defineProperty(this, 'wrap', { value: val }); return val; }, get ytData() { var val = []; Object.defineProperty(this, 'ytData', { value: val }); return val; }, get ytObj() { var val = aib.insertYtPlayer(this.msg, '<div class="de-video-obj"></div>'); Object.defineProperty(this, 'ytObj', { value: val }); return val; }, _hasEvents: false, _linkDelay: 0, _menu: null, _menuDelay: 0, _selRange: null, _selText: '', _addButtonTitle: function(el) { if(el.hasTitle) { return; } el.hasTitle = true; switch(el.className) { case 'de-btn-hide': case 'de-btn-hide-user': el.title = Lng.togglePost[lang]; return; case 'de-btn-expthr': el.title = Lng.expandThrd[lang]; return; case 'de-btn-rep': el.title = Lng.replyToPost[lang]; return; } }, _addMenu: function(el) { var html, cr = el.getBoundingClientRect(), isLeft = false, className = 'de-menu ' + aib.cReply, xOffset = window.pageXOffset; switch(el.getAttribute('de-menu')) { case 'hide': if(!Cfg['menuHiddBtn']) { return; } html = this._addMenuHide(); break; case 'expand': html = '<span class="de-menu-item" info="thr-exp">' + Lng.selExpandThrd[lang] .join('</span><span class="de-menu-item" info="thr-exp">') + '</span>'; break; case 'imgsrc': isLeft = true; className += ' de-imgmenu'; html = this._addMenuImgSrc(el); break; } doc.body.insertAdjacentHTML('beforeend', '<div class="' + className + '" style="position: absolute; ' + ( isLeft ? 'left: ' + (cr.left + xOffset) : 'right: ' + (doc.documentElement.clientWidth - cr.right - xOffset) ) + 'px; top: ' + (window.pageYOffset + cr.bottom) + 'px;">' + html + '</div>'); if(this._menu) { clearTimeout(this._menuDelay); $del(this._menu); } this._menu = doc.body.lastChild; this._menu.addEventListener('click', this, false); this._menu.addEventListener('mouseover', this, false); this._menu.addEventListener('mouseout', this, false); }, _addMenuHide: function() { var sel, ssel, str = '', addItem = function(name) { str += '<span info="spell-' + name + '" class="de-menu-item">' + Lng.selHiderMenu[name][lang] + '</span>'; }; sel = nav.Presto ? doc.getSelection() : window.getSelection(); if(ssel = sel.toString()) { this._selText = ssel; this._selRange = sel.getRangeAt(0); addItem('sel'); } if(this.posterName) { addItem('name'); } if(this.posterTrip) { addItem('trip'); } if(this.images.length === 0) { addItem('noimg'); } else { addItem('img'); addItem('ihash'); } if(this.text) { addItem('text'); } else { addItem('notext'); } return str; }, _addMenuImgSrc: function(el) { var p = el.nextSibling.href + '" target="_blank">' + Lng.search[lang], c = doc.body.getAttribute('de-image-search'), str = ''; if(c) { c = c.split(';'); c.forEach(function(el) { var info = el.split(','); str += '<a class="de-src' + info[0] + (!info[1] ? '" onclick="de_isearch(event, \'' + info[0] + '\')" de-url="' : '" href="' + info[1] ) + p + info[0] + '</a>'; }); } return '<a class="de-menu-item de-imgmenu de-src-iqdb" href="http://iqdb.org/?url=' + p + 'IQDB</a>' + '<a class="de-menu-item de-imgmenu de-src-tineye" href="http://tineye.com/search/?url=' + p + 'TinEye</a>' + '<a class="de-menu-item de-imgmenu de-src-google" href="http://google.com/searchbyimage?image_url=' + p + 'Google</a>' + '<a class="de-menu-item de-imgmenu de-src-saucenao" href="http://saucenao.com/search.php?url=' + p + 'SauceNAO</a>' + str; }, _addPview: function(link) { var tNum = (link.pathname.match(/.+?\/[^\d]*(\d+)/) || [,0])[1], pNum = (link.textContent.trim().match(/\d+$/) || [tNum])[0], pv = this.isPview ? this.kid : Pview.top; if(pv && pv.num === pNum) { Pview.del(pv.kid); setPviewPosition(link, pv.el, Cfg['animation'] && animPVMove); if(pv.parent.num !== this.num) { $each($C('de-pview-link', pv.el), function(el) { el.classList.remove('de-pview-link'); }); pv._markLink(this.num); } this.kid = pv; pv.parent = this; } else { this.kid = new Pview(this, link, tNum, pNum); } }, _clickImage: function(el, e) { // We need to get allImages getter before imgIdx property, do not remove allImgs var var data, allImgs = this.allImages; if(el.classList.contains('de-img-full')) { if(!allImgs[el.previousSibling.firstElementChild.imgIdx].collapse(e)) { return; } } else if(el.imgIdx === undefined || !(data = allImgs[el.imgIdx]) || !(data.isImage || data.isVideo)) { return; } else { data.expand((Cfg['expandImgs'] === 1) ^ e.ctrlKey, e); } $pd(e); e.stopPropagation(); }, _clickMenu: function(el) { $del(this._menu); this._menu = null; switch(el.getAttribute('info')) { case 'spell-sel': var start = this._selRange.startContainer, end = this._selRange.endContainer; if(start.nodeType === 3) { start = start.parentNode; } if(end.nodeType === 3) { end = end.parentNode; } if((nav.matchesSelector(start, aib.qMsg + ' *') && nav.matchesSelector(end, aib.qMsg + ' *')) || (nav.matchesSelector(start, '.' + aib.cSubj) && nav.matchesSelector(end, '.' + aib.cSubj)) ) { if(this._selText.contains('\n')) { addSpell(1 /* #exp */, '/' + regQuote(this._selText).replace(/\r?\n/g, '\\n') + '/', false); } else { addSpell(0 /* #words */, this._selText.replace(/\)/g, '\\)').toLowerCase(), false); } } else { dummy.innerHTML = ''; dummy.appendChild(this._selRange.cloneContents()); addSpell(2 /* #exph */, '/' + regQuote(dummy.innerHTML.replace(/^<[^>]+>|<[^>]+>$/g, '')) + '/', false); } return; case 'spell-name': addSpell(6 /* #name */, this.posterName.replace(/\)/g, '\\)'), false); return; case 'spell-trip': addSpell(7 /* #trip */, this.posterTrip.replace(/\)/g, '\\)'), false); return; case 'spell-img': var img = this.images[0], w = img.weight, wi = img.width, h = img.height; addSpell(8 /* #img */, [0, [w, w], [wi, wi, h, h]], false); return; case 'spell-ihash': this.images[0].getHash(function(hash) { addSpell(4 /* #ihash */, hash, false); }); return; case 'spell-noimg': addSpell(0x108 /* (#all & !#img) */, '', true); return; case 'spell-text': var num = this.num, hidden = this.hidden, wrds = Post.getWrds(this.text), time = Date.now(); for(var post = firstThr.op; post; post = post.next) { Post.findSameText(num, hidden, wrds, time, post); } saveUserPosts(true); return; case 'spell-notext': addSpell(0x10B /* (#all & !#tlen) */, '', true); return; case 'thr-exp': this.thr.load(parseInt(el.textContent, 10), false, null); return; } }, _closeMenu: function(rt) { clearTimeout(this._menuDelay); if(this._menu && (!rt || rt.className !== 'de-menu-item')) { this._menuDelay = setTimeout(function() { $del(this._menu); this._menu = null; }.bind(this), 75); } }, _getFull: function(node, isInit) { if(aib.dobr) { $del(node.nextSibling); $del(node.previousSibling); $del(node); if(isInit) { this.msg.replaceChild($q('.alternate > div', this.el), this.msg.firstElementChild); } else { this.updateMsg($q('.alternate > div', this.el)); } return; } if(!isInit) { $alert(Lng.loading[lang], 'load-fullmsg', true); } ajaxLoad(aib.getThrdUrl(brd, this.tNum), true, function(node, form, xhr) { if(this.isOp) { this.updateMsg(replacePost($q(aib.qMsg, form))); $del(node); } else { for(var i = 0, els = aib.getPosts(form), len = els.length; i < len; i++) { if(this.num === aib.getPNum(els[i])) { this.updateMsg(replacePost($q(aib.qMsg, els[i]))); $del(node); return; } } } }.bind(this, node), null); }, _markLink: function(pNum) { $each($Q('a[href*="' + pNum + '"]', this.el), function(num, el) { if(el.textContent === '>>' + num) { el.classList.add('de-pview-link'); } }.bind(null, pNum)); }, _strikePostNum: function(isHide) { var idx, num = this.num; if(isHide) { Post.hiddenNums.push(+num); } else { idx = Post.hiddenNums.indexOf(+num); if(idx !== -1) { Post.hiddenNums.splice(idx, 1); } } $each($Q('a[href*="#' + num + '"]', dForm), isHide ? function(el) { el.classList.add('de-ref-hid'); } : function(el) { el.classList.remove('de-ref-hid'); }); } }; //============================================================================================================ // PREVIEW //============================================================================================================ function Pview(parent, link, tNum, pNum) { var b, post = pByNum[pNum]; if(Cfg['noNavigHidd'] && post && post.hidden) { return; } this.parent = parent; this._link = link; this.num = pNum; this.thr = parent.thr; Object.defineProperty(this, 'tNum', { value: tNum }); if(post && (!post.isOp || !parent.isPview || !parent._loaded)) { this._showPost(post); return; } b = link.pathname.match(/^\/?(.+\/)/)[1].replace(aib.res, '').replace(/\/$/, ''); if(post = this._cache && this._cache[b + tNum] && this._cache[b + tNum].getPost(pNum)) { this._loaded = true; this._showPost(post); } else { this._showText('<span class="de-wait">' + Lng.loading[lang] + '</span>'); ajaxLoad(aib.getThrdUrl(b, tNum), true, this._onload.bind(this, b), this._onerror.bind(this)); } } Pview.clearCache = function() { Pview.prototype._cache = {}; }; Pview.del = function(pv) { if(!pv) { return; } var el, vPost = Attachment.viewer && Attachment.viewer.data.post; pv.parent.kid = null; if(!pv.parent.isPview) { Pview.top = null; } do { clearTimeout(pv._readDelay); if(vPost === pv) { Attachment.viewer.close(null); Attachment.viewer = vPost = null; } el = pv.el; if(Cfg['animation']) { nav.animEvent(el, $del); el.classList.add('de-pview-anim'); el.style[nav.animName] = 'de-post-close-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r'); } else { $del(el); } } while(pv = pv.kid); }; Pview.mouseEnter = function(post) { if(post.kid) { post.kid.markToDel(); } else { clearTimeout(Pview.delTO); } }; Pview.delTO = 0; Pview.top = null; Pview.prototype = Object.create(Post.prototype, { isPview: { value: true }, getTopParent: { value: function pvGetBoardParent() { var post = this.parent; while(post.isPview) { post = post.parent; } return post; } }, markToDel: { value: function pvMarkToDel() { clearTimeout(Pview.delTO); var lastSticked, el = this; do { if(el.sticked) { lastSticked = el; } } while(el = el.kid); if(!lastSticked || lastSticked.kid) { Pview.delTO = setTimeout(Pview.del, Cfg['linksOut'], lastSticked ? lastSticked.kid : this); } } }, _loaded: { value: false, writable: true }, _cache: { value: {}, writable: true }, _readDelay: { value: 0, writable: true }, _handleMouseEvents: { value: function pvHandleMouseEvents(el, isOverEvent) { if(!el || (el !== this.el && !this.el.contains(el))) { if(isOverEvent) { Pview.mouseEnter(this); } else if(Pview.top && (!this._menu || (this._menu !== el && !this._menu.contains(el)))) { Pview.top.markToDel(); } } } }, _onerror: { value: function(eCode, eMsg, xhr) { Pview.del(this); this._showText(eCode === 404 ? Lng.postNotFound[lang] : getErrorMessage(eCode, eMsg)); } }, _onload: { value: function pvOnload(b, form, xhr) { var rm, parent = this.parent, parentNum = parent.num, cache = this._cache[b + this.tNum] = new PviewsCache(form, b, this.tNum), post = cache.getPost(this.num); if(post && (brd !== b || !post.hasRef || post.ref.indexOf(parentNum) === -1)) { if(post.hasRef) { rm = $c('de-refmap', post.el) } else { post.msg.insertAdjacentHTML('afterend', '<div class="de-refmap"></div>'); rm = post.msg.nextSibling; } rm.insertAdjacentHTML('afterbegin', '<a class="de-reflink" href="' + aib.getThrdUrl(b, parent.tNum) + aib.anchor + parentNum + '">&gt;&gt;' + (brd === b ? '' : '/' + brd + '/') + parentNum + '</a><span class="de-refcomma">, </span>'); } if(parent.kid === this) { Pview.del(this); if(post) { this._loaded = true; this._showPost(post); } else { this._showText(Lng.postNotFound[lang]); } } } }, _showPost: { value: function pvShowPost(post) { var btns, el = this.el = post.el.cloneNode(true), pText = '<span class="de-btn-rep" title="' + Lng.replyToPost[lang] + '"></span>' + (post.sage ? '<span class="de-btn-sage" title="SAGE"></span>' : '') + '<span class="de-btn-stick" title="' + Lng.attachPview[lang] + '"></span>' + (post.deleted ? '' : '<span style="margin-right: 4px; vertical-align: 1px; color: #4f7942; ' + 'font: bold 11px tahoma; cursor: default;">' + (post.isOp ? 'OP' : post.count + 1) + '</span>'); el.post = this; el.className = aib.cReply + ' de-pview' + (post.viewed ? ' de-viewed' : ''); el.style.display = ''; if(Cfg['linksNavig'] === 2) { this._markLink(this.parent.num); } this._pref = $q(aib.qRef, el); if(post.inited) { this.btns = btns = $c('de-ppanel', el); this.isOp = post.isOp; btns.classList.remove('de-ppanel-cnt'); if(post.hidden) { btns.classList.add('de-post-hide'); } btns.innerHTML = '<span class="de-btn-hide' + (post.userToggled ? '-user' : '') + '" de-menu="hide" title="' + Lng.togglePost[lang] + '"></span>' + pText; $each($Q((!TNum && post.isOp ? aib.qOmitted + ', ' : '') + '.de-img-full, .de-after-fimg', el), $del); $each($Q(aib.qThumbImages, el), function(el) { el.parentNode.style.display = ''; }); if(post.hasYTube) { if(post.ytInfo !== null) { Object.defineProperty(this, 'ytObj', { value: $c('de-video-obj', el) }); this.ytInfo = post.ytInfo; } new YouTube().updatePost(this, $C('de-video-link', post.el), $C('de-video-link', el), true); } if(Cfg['addImgs']) { $each($C('de-img-pre', el), function(el) { el.style.display = ''; }); } if(Cfg['markViewed']) { this._readDelay = setTimeout(function(pst) { if(!pst.viewed) { pst.el.classList.add('de-viewed'); pst.viewed = true; } var arr = (sesStorage['de-viewed'] || '').split(','); arr.push(pst.num); sesStorage['de-viewed'] = arr; }, post.text.length > 100 ? 2e3 : 500, post); } } else { this._pref.insertAdjacentHTML('afterend', '<span class="de-ppanel">' + pText + '</span'); embedMP3Links(this); new YouTube().parseLinks(this); if(Cfg['addImgs']) { embedImagesLinks(el); } if(Cfg['imgSrcBtns']) { addImagesSearch(el); } } el.addEventListener('click', this, true); this._showPview(el); } }, _showPview: { value: function pvShowPview(el, id) { if(this.parent.isPview) { Pview.del(this.parent.kid); } else { Pview.del(Pview.top); Pview.top = this; } this.parent.kid = this; el.addEventListener('mouseover', this, true); el.addEventListener('mouseout', this, true); (aib.arch ? doc.body : dForm).appendChild(el); setPviewPosition(this._link, el, false); if(Cfg['animation']) { nav.animEvent(el, function(node) { node.classList.remove('de-pview-anim'); node.style[nav.animName] = ''; }); el.classList.add('de-pview-anim'); el.style[nav.animName] = 'de-post-open-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r'); } } }, _showText: { value: function pvShowText(txt) { this._showPview(this.el = $add('<div class="' + aib.cReply + ' de-pview-info de-pview">' + txt + '</div>')); } }, }); function PviewsCache(form, b, tNum) { var i, len, post, pBn = {}, pProto = Post.prototype, thr = $q(aib.qThread, form) || form, posts = aib.getPosts(thr); for(i = 0, len = posts.length; i < len; ++i) { post = posts[i]; pBn[aib.getPNum(post)] = Object.create(pProto, { count: { value: i + 1 }, el: { value: post, writable: true }, inited: { value: false }, pvInited: { value: false, writable: true }, ref: { value: [], writable: true } }); } pBn[tNum] = this._opObj = Object.create(pProto, { inited: { value: false }, isOp: { value: true }, msg: { value: $q(aib.qMsg, thr), writable: true }, ref: { value: [], writable: true } }); this._brd = b; this._thr = thr; this._tNum = tNum; this._tUrl = aib.getThrdUrl(b, tNum); this._posts = pBn; if(Cfg['linksNavig'] === 2) { genRefMap(pBn, this._tUrl); } } PviewsCache.prototype = { getPost: function(num) { if(num === this._tNum) { return this._op; } var pst = this._posts[num]; if(pst && !pst.pvInited) { pst.el = replacePost(pst.el); delete pst.msg; if(pst.hasRef) { addRefMap(pst, this._tUrl); } pst.pvInited = true; } return pst; }, get _op() { var i, j, len, num, nRef, oRef, rRef, oOp, op = this._opObj; op.el = replacePost(aib.getOp(this._thr)); op.msg = $q(aib.qMsg, op.el); if(this._brd === brd && (oOp = pByNum[this._tNum])) { oRef = op.ref; rRef = []; for(i = j = 0, nRef = oOp.ref, len = nRef.length; j < len; ++j) { num = nRef[j]; if(oRef[i] === num) { i++; } else if(oRef.indexOf(num) !== -1) { continue; } rRef.push(num) } for(len = oRef.length; i < len; i++) { rRef.push(oRef[i]); } op.ref = rRef; if(rRef.length !== 0) { op.hasRef = true; addRefMap(op, this._tUrl); } } else if(op.hasRef) { addRefMap(op, this._tUrl); } Object.defineProperty(this, '_op', { value: op }); return op; } }; function PviewMoved() { if(this.style[nav.animName]) { this.classList.remove('de-pview-anim'); this.style.cssText = this.newPos; this.newPos = false; $each($C('de-css-move', doc.head), $del); this.removeEventListener(nav.animEnd, PviewMoved, false); } } function animPVMove(pView, lmw, top, oldCSS) { var uId = 'de-movecss-' + Math.round(Math.random() * 1e3); $css('@' + nav.cssFix + 'keyframes ' + uId + ' {to { ' + lmw + ' top:' + top + '; }}').className = 'de-css-move'; if(pView.newPos) { pView.style.cssText = pView.newPos; pView.removeEventListener(nav.animEnd, PviewMoved, false); } else { pView.style.cssText = oldCSS; } pView.newPos = lmw + ' top:' + top + ';'; pView.addEventListener(nav.animEnd, PviewMoved, false); pView.classList.add('de-pview-anim'); pView.style[nav.animName] = uId; } function setPviewPosition(link, pView, animFun) { if(pView.link === link) { return; } pView.link = link; var isTop, top, oldCSS, cr = link.getBoundingClientRect(), offX = cr.left + window.pageXOffset + link.offsetWidth / 2, offY = cr.top + window.pageYOffset, bWidth = doc.documentElement.clientWidth, isLeft = offX < bWidth / 2, tmp = (isLeft ? offX : offX - Math.min(parseInt(pView.offsetWidth, 10), offX - 10)), lmw = 'max-width:' + (bWidth - tmp - 10) + 'px; left:' + tmp + 'px;'; if(animFun) { oldCSS = pView.style.cssText; pView.style.cssText = 'opacity: 0; ' + lmw; } else { pView.style.cssText = lmw; } top = pView.offsetHeight; isTop = top + cr.top + link.offsetHeight < window.innerHeight || cr.top - top < 5; top = (isTop ? offY + link.offsetHeight : offY - top) + 'px'; pView.aLeft = isLeft; pView.aTop = isTop; if(animFun) { animFun(pView, lmw, top, oldCSS); } else { pView.style.top = top; } } function addRefMap(post, tUrl) { var i, ref, len, bStr = '<a ' + aib.rLinkClick + ' href="' + tUrl + aib.anchor, html = ['<div class="de-refmap">']; for(i = 0, ref = post.ref, len = ref.length; i < len; ++i) { html.push(bStr, ref[i], '" class="de-reflink">&gt;&gt;', ref[i], '</a><span class="de-refcomma">, </span>'); } html.push('</div>'); if(aib.dobr) { post.msg.nextElementSibling.insertAdjacentHTML('beforeend', html.join('')); } else { post.msg.insertAdjacentHTML('afterend', html.join('')); } } function genRefMap(posts, thrURL) { var tc, lNum, post, ref, i, len, links, url, pNum, opNums = Thread.tNums; for(pNum in posts) { for(i = 0, links = $T('a', posts[pNum].msg), len = links.length; i < len; ++i) { tc = links[i].textContent; if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in posts)) { post = posts[lNum]; ref = post.ref; if(ref.indexOf(pNum) === -1) { ref.push(pNum); post.hasRef = true; } if(opNums.indexOf(lNum) !== -1) { links[i].classList.add('de-opref'); } if(thrURL) { url = links[i].getAttribute('href'); if(url[0] === '#') { links[i].setAttribute('href', thrURL + url); } } } } } } function updRefMap(post, add) { var tc, ref, idx, link, lNum, lPost, i, len, links, pNum = post.num, strNums = add && Cfg['strikeHidd'] && Post.hiddenNums.length !== 0 ? Post.hiddenNums : null, opNums = add && Thread.tNums; for(i = 0, links = $T('a', post.msg), len = links.length; i < len; ++i) { link = links[i]; tc = link.textContent; if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in pByNum)) { lPost = pByNum[lNum]; if(!TNum) { link.href = '#' + (aib.fch ? 'p' : '') + lNum; } if(add) { if(strNums && strNums.lastIndexOf(lNum) !== -1) { link.classList.add('de-ref-hid'); } if(opNums.indexOf(lNum) !== -1) { link.classList.add('de-opref'); } if(lPost.ref.indexOf(pNum) === -1) { lPost.ref.push(pNum); post.hasRef = true; if(Cfg['hideRefPsts'] && lPost.hidden) { if(!post.hidden) { post.hideRefs(); } post.setVisib(true); post.note = 'reference to >>' + lNum; } } else { continue; } } else if(lPost.hasRef) { ref = lPost.ref; idx = ref.indexOf(pNum); if(idx === -1) { continue; } ref.splice(idx, 1); if(ref.length === 0) { lPost.hasRef = false; $del($c('de-refmap', lPost.el)); continue; } } $del($c('de-refmap', lPost.el)); addRefMap(lPost, ''); } } } //============================================================================================================ // THREAD //============================================================================================================ function Thread(el, prev) { if(aib._420 || aib.tiny) { $after(el, el.lastChild); $del($c('clear', el)); } var i, pEl, lastPost, els = aib.getPosts(el), len = els.length, num = aib.getTNum(el), omt = TNum ? 1 : aib.getOmitted($q(aib.qOmitted, el), len); this.num = num; Thread.tNums.push(+num); this.pcount = omt + len; pByNum[num] = lastPost = this.op = el.post = new Post(aib.getOp(el), this, num, 0, true, prev ? prev.last : null); for(i = 0; i < len; i++) { num = aib.getPNum(pEl = els[i]); pByNum[num] = lastPost = new Post(pEl, this, num, omt + i, false, lastPost); } this.last = lastPost; el.style.counterReset = 'de-cnt ' + omt; el.removeAttribute('id'); el.setAttribute('de-thread', null); visPosts = Math.max(visPosts, len); this.el = el; this.prev = prev; if(prev) { prev.next = this; } } Thread.parsed = false; Thread.clearPostsMark = function() { firstThr.clearPostsMarks(); }; Thread.loadNewPosts = function(e) { if(e) { $pd(e); } $alert(Lng.loading[lang], 'newposts', true); firstThr.clearPostsMarks(); updater.forceLoad(); }; Thread.tNums = []; Thread.prototype = { hasNew: false, hidden: false, loadedOnce: false, next: null, get lastNotDeleted() { var post = this.last; while(post.deleted) { post = post.prev; } return post; }, get nextNotHidden() { for(var thr = this.next; thr && thr.hidden; thr = thr.next) {} return thr; }, get prevNotHidden() { for(var thr = this.prev; thr && thr.hidden; thr = thr.prev) {} return thr; }, get topCoord() { return this.op.topCoord; }, clearPostsMarks: function() { if(this.hasNew) { this.hasNew = false; $each($Q('.de-new-post', this.el), function(el) { el.classList.remove('de-new-post'); }); doc.removeEventListener('click', Thread.clearPostsMark, true); } }, deletePost: function(post, delAll, removePost) { var tPost, idx = post.count, count = 0; do { if(removePost) { $del(post.wrap); delete pByNum[post.num]; if(post.hidden) { post.unhideRefs(); } updRefMap(post, false); if(post.prev.next = post.next) { post.next.prev = post.prev; } if(this.last === post) { this.last = post.prev; } } else { post.deleted = true; post.btns.classList.remove('de-ppanel-cnt'); post.btns.classList.add('de-ppanel-del'); ($q('input[type="checkbox"]', post.el) || {}).disabled = true; } post = post.nextNotDeleted; count++; } while(delAll && post); if(!spells.hasNumSpell) { sVis.splice(idx, count); } for(tPost = post; tPost; tPost = tPost.nextInThread) { tPost.count -= count; } this.pcount -= count; return post; }, load: function(last, smartScroll, Fn) { if(!Fn) { $alert(Lng.loading[lang], 'load-thr', true); } ajaxLoad(aib.getThrdUrl(brd, this.num), true, function threadOnload(last, smartScroll, Fn, form, xhr) { this.loadFromForm(last, smartScroll, form); Fn && Fn(); }.bind(this, last, smartScroll, Fn), function(eCode, eMsg, xhr) { $alert(getErrorMessage(eCode, eMsg), 'load-thr', false); if(typeof this === 'function') { this(); } }.bind(Fn)); }, loadFromForm: function(last, smartScroll, form) { var nextCoord, els = aib.getPosts(form), op = this.op, thrEl = this.el, expEl = $c('de-expand', thrEl), nOmt = last === 1 ? 0 : Math.max(els.length - last, 0); if(smartScroll) { if(this.next) { nextCoord = this.next.topCoord; } else { smartScroll = false; } } pr.closeQReply(); $del($q(aib.qOmitted + ', .de-omitted', thrEl)); if(!this.loadedOnce) { if(op.trunc) { op.updateMsg(replacePost($q(aib.qMsg, form))); } op.ref = []; this.loadedOnce = true; } this._checkBans(op, form); this._parsePosts(els); thrEl.style.counterReset = 'de-cnt ' + (nOmt + 1); if(this._processExpandThread(els, last === 1 ? els.length : last)) { $del(expEl); } else if(!expEl) { thrEl.insertAdjacentHTML('beforeend', '<span class="de-expand">[<a href="' + aib.getThrdUrl(brd, this.num) + aib.anchor + this.last.num + '">' + Lng.collapseThrd[lang] + '</a>]</span>'); thrEl.lastChild.onclick = function(e) { $pd(e); this.load(visPosts, true, null); }.bind(this); } else if(expEl !== thrEl.lastChild) { thrEl.appendChild(expEl); } if(nOmt !== 0) { op.el.insertAdjacentHTML('afterend', '<div class="de-omitted">' + nOmt + '</div>'); } if(smartScroll) { scrollTo(pageXOffset, pageYOffset - (nextCoord - this.next.topCoord)); } closeAlert($id('de-alert-load-thr')); }, loadNew: function(Fn, useAPI) { if(aib.dobr && useAPI) { return getJsonPosts('/api/thread/' + brd + '/' + TNum + '.json', function checkNewPosts(status, sText, json, xhr) { if(status !== 200 || json['error']) { Fn(status, sText || json['message'], 0, xhr); } else { if(this._lastModified !== json['last_modified'] || this.pcount !== json['posts_count']) { this._lastModified = json['last_modified']; updater.updateXHR(this.loadNew(Fn, false)); } else { Fn(200, '', 0, xhr); } Fn = null; } }.bind(this) ); } return ajaxLoad(aib.getThrdUrl(brd, TNum), true, function parseNewPosts(form, xhr) { Fn(200, '', this.loadNewFromForm(form), xhr); Fn = null; }.bind(this), function(eCode, eMsg, xhr) { Fn(eCode, eMsg, 0, xhr); Fn = null; }); }, loadNewFromForm: function(form) { this._checkBans(firstThr.op, form); var lastOffset = pr.isVisible ? pr.topCoord : null, info = this._parsePosts(aib.getPosts(form)); if(lastOffset !== null) { scrollTo(pageXOffset, pageYOffset - (lastOffset - pr.topCoord)); } if(info[0] !== 0) { $id('de-panel-info').firstChild.textContent = this.pcount + '/' + $Q(aib.qThumbImages, dForm).length; } return info[1]; }, setFavorState: function(val) { var fav = 'de-btn-fav', favSel = 'de-btn-fav-sel'; ($c(val ? fav : favSel, this.op.btns) || {}).className = val ? favSel : fav; getStoredObj('DESU_Favorites', function(fav) { var h = aib.host, b = brd, num = this.num; if(val) { if(!fav[h]) { fav[h] = {}; } if(!fav[h][brd]) { fav[h][brd] = {}; } fav[h][brd]['url'] = aib.prot + '//' + aib.host + aib.getPageUrl(brd, 0); fav[h][brd][num] = { 'cnt': this.pcount, 'new': 0, 'txt': this.op.title, 'url': aib.getThrdUrl(brd, num) }; } else { removeFavoriteEntry(fav, h, b, num, false); } saveFavorites(fav); }.bind(this)); }, updateHidden: function(data) { var realHid, date = Date.now(), thr = this; do { realHid = thr.num in data; if(thr.hidden ^ realHid) { if(realHid) { thr.op.setUserVisib(true, date, false); data[thr.num] = thr.op.title; } else if(thr.hidden) { thr.op.setUserVisib(false, date, false); } } } while(thr = thr.next); }, _lastModified: '', _addPost: function(parent, el, i, prev) { var post, num = aib.getPNum(el), wrap = aib.getWrap(el, false); el = replacePost(el); pByNum[num] = post = new Post(el, this, num, i, false, prev); Object.defineProperty(post, 'wrap', { value: wrap }); parent.appendChild(wrap); if(TNum && Cfg['animation']) { nav.animEvent(post.el, function(node) { node.classList.remove('de-post-new'); }); post.el.classList.add('de-post-new'); } new YouTube().parseLinks(post); if(Cfg['imgSrcBtns']) { addImagesSearch(el); } post.addFuncs(); preloadImages(el); if(TNum && Cfg['markNewPosts']) { this._addPostMark(el); } return post; }, _addPostMark: function(postEl) { if(updater.focused) { this.clearPostsMarks(); } else { if(!this.hasNew) { this.hasNew = true; doc.addEventListener('click', Thread.clearPostsMark, true); } postEl.classList.add('de-new-post'); } }, _checkBans: function(op, thrNode) { var pEl, bEl, post, i, bEls, len; if(aib.qBan) { for(i = 0, bEls = $Q(aib.qBan, thrNode), len = bEls.length; i < len; ++i) { bEl = bEls[i]; pEl = aib.getPostEl(bEl); post = pEl ? pByNum[aib.getPNum(pEl)] : op; if(post && !post.banned) { if(!$q(aib.qBan, post.el)) { post.msg.appendChild(bEl); } post.banned = true; } } } }, _importPosts: function(last, newPosts, begin, end) { var newCount, newVisCount, fragm = doc.createDocumentFragment(), newCount = newVisCount = end - begin; for(; begin < end; ++begin) { last = this._addPost(fragm, newPosts[begin], begin + 1, last); newVisCount -= spells.check(last); } return [newCount, newVisCount, fragm, last]; }, _parsePosts: function(nPosts) { var i, cnt, firstChangedPost, res, temp, saveSpells = false, newPosts = 0, newVisPosts = 0, len = nPosts.length, post = this.lastNotDeleted; if(aib.dobr || (post.count !== 0 && (post.count > len || aib.getPNum(nPosts[post.count - 1]) !== post.num))) { firstChangedPost = null; post = this.op.nextNotDeleted; for(i = post.count - 1; i < len && post; ) { if(post.num !== aib.getPNum(nPosts[i])) { if(+post.num > +aib.getPNum(nPosts[i])) { if(!firstChangedPost) { firstChangedPost = post.prev; } cnt = 0; do { cnt++; i++; } while(+aib.getPNum(nPosts[i]) < +post.num); res = this._importPosts(post.prev, nPosts, i - cnt, i); newPosts += res[0]; this.pcount += res[0]; newVisPosts += res[1]; $after(post.prev.wrap, res[2]); res[3].next = post; post.prev = res[3]; for(temp = post; temp; temp = temp.nextInThread) { temp.count += cnt; } } else { if(!firstChangedPost) { firstChangedPost = post; } post = this.deletePost(post, false, !TNum); } } else { i++; post = post.nextNotDeleted; } } if(i === len && post) { this.deletePost(post, true, !TNum); } if(firstChangedPost && spells.hasNumSpell) { disableSpells(); for(post = firstChangedPost.nextInThread; post; post = post.nextInThread) { spells.check(post); } saveSpells = true; } if(newPosts !== 0) { for(post = firstChangedPost; post; post = post.nextInThread) { updRefMap(post, true); } } } if(len + 1 > this.pcount) { res = this._importPosts(this.last, nPosts, this.lastNotDeleted.count, len); newPosts += res[0]; newVisPosts += res[1]; this.el.appendChild(res[2]); this.last = res[3]; this.pcount = len + 1; saveSpells = true; } getStoredObj('DESU_Favorites', function(fav) { var el, f, h = aib.host; if(fav[h] && fav[h][brd] && (f = fav[h][brd][this.op.num])) { if(el = $id('de-content-fav')) { el = $q('.de-fav-current > .de-entry[de-num="' + this.op.num + '"] .de-fav-inf-old', el); el.textContent = this.pcount; el.nextElementSibling.textContent = 0; } f['cnt'] = this.pcount; f['new'] = 0; saveFavorites(fav); } }.bind(this)); if(saveSpells) { spells.end(savePosts); } return [newPosts, newVisPosts]; }, _processExpandThread: function(nPosts, num) { var i, fragm, tPost, len, needRMUpdate, post = this.op.next, vPosts = this.pcount === 1 ? 0 : this.last.count - post.count + 1; if(vPosts > num) { while(vPosts-- !== num) { post.wrap.classList.add('de-hidden'); post.omitted = true; post = post.next; } needRMUpdate = false; } else if(vPosts < num) { fragm = doc.createDocumentFragment(); tPost = this.op; len = nPosts.length; for(i = Math.max(0, len - num), len -= vPosts; i < len; ++i) { tPost = this._addPost(fragm, nPosts[i], i + 1, tPost); spells.check(tPost); } $after(this.op.el, fragm); tPost.next = post; if(post) { post.prev = tPost; } needRMUpdate = true; num = Math.min(len + vPosts, num); } else { return num <= visPosts; } while(vPosts-- !== 0) { if(post.trunc) { post.updateMsg(replacePost($q(aib.qMsg, nPosts[post.count - 1]))); } if(post.omitted) { post.wrap.classList.remove('de-hidden'); post.omitted = false; } if(needRMUpdate) { updRefMap(post, true); } post = post.next; } return num <= visPosts; } }; //============================================================================================================ // IMAGEBOARD //============================================================================================================ function getImageBoard(checkDomains, checkOther) { var ibDomains = { '02ch.net': [{ qPostRedir: { value: 'input[name="gb2"][value="thread"]' }, ru: { value: true }, timePattern: { value: 'yyyy+nn+dd++w++hh+ii+ss' } }], get '22chan.net'() { return this['ernstchan.com']; }, '2chru.net': [{ _2chru: { value: true } }, 'form[action*="imgboard.php?delete"]'], get '2-chru.net'() { return this['2chru.net']; }, get '2ch.cm'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.hk'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.pm'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.re'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.tf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.wf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2ch.yt'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2-ch.so'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; }, get '2-ch.su'() { return this['2--ch.ru']; }, '2--ch.ru': [{ tire: { value: true }, qPages: { value: 'table[border="1"] tr:first-of-type > td:first-of-type a' }, qPostRedir: { value: null }, qTable: { value: 'table:not(.postfiles)' }, qThread: { value: '.threadz' }, getOmitted: { value: function(el, len) { var txt; return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] - len : 1; } }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 0 ? p : 0) + '.memhtml'; } }, css: { value: 'span[id$="_display"], #fastload { display: none !important; }' }, docExt: { value: '.html' }, hasPicWrap: { value: true }, isBB: { value: true }, ru: { value: true } }], '410chan.org': [{ _410: { value: true }, qPostRedir: { value: 'input#noko' }, getSage: { value: function(post) { var el = $c('filetitle', post); return el && el.textContent.contains('\u21E9'); } }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['**', '*', '__', '^^', '%%', '`', '', '', 'q'] } }); } }, isBB: { value: false }, timePattern: { value: 'dd+nn+yyyy++w++hh+ii+ss' } }, 'script[src*="kusaba"]'], '420chan.org': [{ // Posting doesn't work (antispam protection) _420: { value: true }, qBan: { value: '.ban' }, qError: { value: 'pre' }, qHide: { value: '.replyheader ~ *' }, qPages: { value: '.pagelist > a:last-child' }, qPostRedir: { value: null }, qThread: { value: '[id*="thread"]' }, getTNum: { value: function(op) { return $q('a[id]', op).id.match(/\d+/)[0]; } }, css: { value: '#content > hr, .hidethread, .ignorebtn, .opqrbtn, .qrbtn, noscript { display: none !important; }\ .de-thr-hid { margin: 1em 0; }' }, docExt: { value: '.php' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['**', '*', '', '', '%', 'pre', '', '', 'q'] } }); } }, isBB: { value: true } }], '4chan.org': [{ fch: { value: true }, cFileInfo: { value: 'fileText' }, cOPost: { value: 'op' }, cReply: { value: 'post reply' }, cSubj: { value: 'subject' }, qBan: { value: 'strong[style="color: red;"]' }, qDelBut: { value: '.deleteform > input[type="submit"]' }, qError: { value: '#errmsg' }, qHide: { value: '.postInfo ~ *' }, qImgLink: { value: '.fileText > a' }, qName: { value: '.name' }, qOmitted: { value: '.summary.desktop' }, qPages: { value: '.pagelist > .pages:not(.cataloglink) > a:last-of-type' }, qPostForm: { value: 'form[name="post"]' }, qPostRedir: { value: null }, qRef: { value: '.postInfo > .postNum' }, qTable: { value: '.replyContainer' }, qThumbImages: { value: '.fileThumb > img' }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 1 ? p : ''); } }, getSage: { value: function(post) { return !!$q('.id_Heaven, .useremail[href^="mailto:sage"]', post); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, getWrap: { value: function(el, isOp) { return el.parentNode; } }, anchor: { value: '#p' }, css: { value: '.backlink, .extButton, hr.desktop, .navLinks, .postMenuBtn, #togglePostFormLink { display: none !important; }\ .postForm { display: table !important; }\ textarea { margin-right: 0 !important; }' }, docExt: { value: '' }, firstPage: { value: 1 }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['**', '*', '__', '^H', 'spoiler', 'code', '', '', 'q'] }, bb: { value: [false, false, false, false, true, true, false, false, false] } }); } }, rLinkClick: { value: '' }, rep: { value: true }, res: { value: 'thread/' }, timePattern: { value: 'nn+dd+yy+w+hh+ii-?s?s?' } }], '55ch.org': [{ _55ch: { value: true }, init: { value: function() { $script('$ = function() {}'); } } }, 'form[name*="postcontrols"]'], '7chan.org': [{ init: { value: function() { return true; } } }], 'belchan.org': [{ belch: { value: true } }, 'script[src*="kusaba"]'], 'britfa.gs': [{ init: { value: function() { return true; } } }], get 'dmirrgetyojz735v.onion'() { return this['2chru.net']; }, 'dobrochan.com': [{ dobr: { value: true }, anchor: { value: '#i' }, cFileInfo: { value: 'fileinfo' }, cSubj: { value: 'replytitle' }, qDForm: { value: 'form[action*="delete"]' }, qError: { value: '.post-error, h2' }, qMsg: { value: '.postbody' }, qOmitted: { value: '.abbrev > span:first-of-type' }, qPages: { value: '.pages > tbody > tr > td' }, qPostRedir: { value: 'select[name="goto"]' }, qTrunc: { value: '.abbrev > span:nth-last-child(2)' }, getImgLink: { value: function(img) { var el = img.parentNode; if(el.tagName === 'A') { return el; } return $q('.fileinfo > a', img.previousElementSibling ? el : el.parentNode); } }, getImgWrap: { value: function(el) { return el.tagName === 'A' ? (el.previousElementSibling ? el : el.parentNode).parentNode : el.firstElementChild.tagName === 'IMG' ? el.parentNode : el; } }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 0 ? p + this.docExt : 'index.xhtml'); } }, getTNum: { value: function(op) { return $q('a[name]', op).name.match(/\d+/)[0]; } }, insertYtPlayer: { value: function(msg, playerHtml) { var prev = msg.previousElementSibling, node = prev.tagName === 'BR' ? prev : msg; node.insertAdjacentHTML('beforebegin', playerHtml); return node.previousSibling; } }, css: { value: '.delete > img, .popup, .reply_, .search_google, .search_iqdb { display: none !important; }\ .delete { background: none; }\ .delete_checkbox { position: static !important; }\ .file + .de-video-obj { float: left; margin: 5px 20px 5px 5px; }\ .de-video-obj + div { clear: left; }' }, disableRedirection: { value: function(el) { ($q(this.qPostRedir, el) || {}).selectedIndex = 1; } }, hasPicWrap: { value: true }, init: { value: function() { if(window.location.pathname === '/settings') { nav = getNavFuncs(); $q('input[type="button"]', doc).addEventListener('click', function() { readCfg(function() { saveCfg('__hanarating', $id('rating').value); }); }, false); return true; } } }, rLinkClick: { value: 'onclick="Highlight(event, this.getAttribute(\'de-num\'))"' }, ru: { value: true }, timePattern: { value: 'dd+m+?+?+?+?+?+yyyy++w++hh+ii-?s?s?' } }], get 'dobrochan.org'() { return this['dobrochan.com']; }, 'dva-ch.net': [{ dvachnet: { value: true }, }], 'ernstchan.com': [{ cOPost: { value: 'thread_OP' }, cReply: { value: 'post' }, cRPost: { value: 'thread_reply' }, qError: { value: '.error' }, qMsg: { value: '.text' }, css: { value: '.content > hr, .de-parea > hr { display: none !important }' } }, 'link[href$="phutaba.css"]'], 'hiddenchan.i2p': [{ hid: { value: true } }, 'script[src*="kusaba"]'], get 'honokakawai.com'() { return this['2--ch.ru']; }, 'iichan.hk': [{ iich: { value: true } }], 'inach.org': [{ qPostRedir: { value: 'input[name="fieldnoko"]' }, css: { value: '#postform > table > tbody > tr:first-child { display: none !important; }' }, isBB: { value: true } }], 'krautchan.net': [{ krau: { value: true }, cFileInfo: { value: 'fileinfo' }, cReply: { value: 'postreply' }, cRPost: { value: 'postreply' }, cSubj: { value: 'postsubject' }, qBan: { value: '.ban_mark' }, qDForm: { value: 'form[action*="delete"]' }, qError: { value: '.message_text' }, qHide: { value: 'div:not(.postheader)' }, qImgLink: { value: '.filename > a' }, qOmitted: { value: '.omittedinfo' }, qPages: { value: 'table[border="1"] > tbody > tr > td > a:nth-last-child(2) + a' }, qPostRedir: { value: 'input#forward_thread' }, qRef: { value: '.postnumber' }, qThread: { value: '.thread_body' }, qThumbImages: { value: 'img[id^="thumbnail_"]' }, qTrunc: { value: 'p[id^="post_truncated"]' }, getImgWrap: { value: function(el) { return el.parentNode; } }, getSage: { value: function(post) { return !!$c('sage', post); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, insertYtPlayer: { value: function(msg, playerHtml) { var pMsg = msg.parentNode, prev = pMsg.previousElementSibling, node = prev.hasAttribute('style') ? prev : pMsg; node.insertAdjacentHTML('beforebegin', playerHtml); return node.previousSibling; } }, css: { value: 'img[id^="translate_button"], img[src$="button-expand.gif"], img[src$="button-close.gif"], body > center > hr, form > div:first-of-type > hr, h2, .sage { display: none !important; }\ div[id^="Wz"] { z-index: 10000 !important; }\ .de-thr-hid { margin-bottom: ' + (!TNum ? '7' : '2') + 'px; float: none !important; }\ .file_reply + .de-video-obj, .file_thread + .de-video-obj { margin: 5px 20px 5px 5px; float: left; }\ .de-video-obj + div { clear: left; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'aa', '', '', 'q'] }, }); } }, hasPicWrap: { value: true }, init: { value: function() { doc.body.insertAdjacentHTML('beforeend', '<div style="display: none;">' + '<div onclick="window.lastUpdateTime = 0;"></div>' + '<div onclick="if(boardRequiresCaptcha) { requestCaptcha(true); }"></div>' + '<div onclick="setupProgressTracking();"></div>' + '</div>'); var els = doc.body.lastChild.children; this.btnZeroLUTime = els[0]; this.initCaptcha = els[1]; this.addProgressTrack = els[2]; } }, isBB: { value: true }, rep: { value: true }, res: { value: 'thread-' }, rLinkClick: { value: 'onclick="highlightPost(this.textContent.substr(2)))"' }, timePattern: { value: 'yyyy+nn+dd+hh+ii+ss+--?-?-?-?-?' } }], 'lambdadelta.net': [{ qHide: { value: '.de-ppanel ~ *' }, css: { value: '.content > hr { display: none !important }' } }, 'link[href$="phutaba.css"]'], 'mlpg.co': [{ getWrap: { value: function(el, isOp) { return el.parentNode; } }, css: { value: '.image-hover, form > div[style="text-align: center;"], form > div[style="text-align: center;"] + hr { display: none !important; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', '-', 'spoiler', 'c', '', '', 'q'] }, }); } }, isBB: { value: true } }, 'form[name*="postcontrols"]'], 'ponychan.net': [{ pony: { value: true }, cOPost: { value: 'op' }, qPages: { value: 'table[border="0"] > tbody > tr > td:nth-child(2) > a:last-of-type' }, css: { value: '#bodywrap3 > hr { display: none !important; }' } }, 'script[src*="kusaba"]'], 'syn-ch.ru': [{ css: { value: '.fa-sort, .image_id { display: none !important; }\ time:after { content: none; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sub', 'sup', 'q'] }, }); } }, init: { value: function() { $script('$ = function() {}'); } }, isBB: { value: true } }, 'form[name*="postcontrols"]'], get 'syn-ch.com'() { return this['syn-ch.ru']; }, get 'syn-ch.org'() { return this['syn-ch.ru']; }, 'touhouchan.org': [{ toho: { value: true }, qPostRedir: { value: 'input[name="gb2"][value="thread"]' }, css: { value: 'span[id$="_display"], #bottom_lnks { display: none !important; }' }, isBB: { value: true } }] }; var ibEngines = { '#ABU_css, #ShowLakeSettings': { abu: { value: true }, qBan: { value: 'font[color="#C12267"]' }, qDForm: { value: '#posts_form, #delform' }, qOmitted: { value: '.mess_post, .omittedposts' }, qPostRedir: { value: null }, getImgWrap: { value: function(el) { return el.parentNode.parentNode; } }, getSage: { writable: true, value: function(post) { if($c('postertripid', dForm)) { this.getSage = function(post) { return !$c('postertripid', post); }; } else { this.getSage = Object.getPrototypeOf(this).getSage; } return this.getSage(post); } }, cssEn: { value: '#ABU_alert_wait, .ABU_refmap, #captcha_div + font, #CommentToolbar, .postpanel, #usrFlds + tbody > tr:first-child, body > center { display: none !important; }\ .de-abtn { transition: none; }\ #de-txt-panel { font-size: 16px !important; }\ .reflink:before { content: none !important; }' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sup', 'sub', 'q'] } }); } }, init: { value: function() { var cd = $id('captcha_div'), img = cd && $t('img', cd); if(img) { cd.setAttribute('onclick', ['var el, i = 4,', 'isCustom = (typeof event.detail === "object") && event.detail.isCustom;', "if(!isCustom && event.target.tagName !== 'IMG') {", 'return;', '}', 'do {', img.getAttribute('onclick'), '} while(--i > 0 && !/<img|не нужно/i.test(this.innerHTML));', "if(el = this.getElementsByTagName('img')[0]) {", "el.removeAttribute('onclick');", "if((!isCustom || event.detail.focus) && (el = this.querySelector('input[type=\\'text\\']'))) {", 'el.focus();', '}', '}' ].join('')); img.removeAttribute('onclick'); } } }, isBB: { value: true } }, 'form[action*="futaba.php"]': { futa: { value: true }, qDForm: { value: 'form:not([enctype])' }, qImgLink: { value: 'a[href$=".jpg"], a[href$=".png"], a[href$=".gif"]' }, qOmitted: { value: 'font[color="#707070"]' }, qPostForm: { value: 'form:nth-of-type(1)' }, qPostRedir: { value: null }, qRef: { value: '.del' }, qThumbImages: { value: 'a[href$=".jpg"] > img, a[href$=".png"] > img, a[href$=".gif"] > img' }, getPageUrl: { value: function(b, p) { return fixBrd(b) + (p > 0 ? p + this.docExt : 'futaba.htm'); } }, getPNum: { value: function(post) { return $t('input', post).name; } }, getPostEl: { value: function(el) { while(el && el.tagName !== 'TD' && !el.hasAttribute('de-thread')) { el = el.parentElement; } return el; } }, getPosts: { value: function(thr) { return $Q('td:nth-child(2)', thr); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, cssEn: { value: '.de-cfg-body, .de-content { font-family: arial; }\ .ftbl { width: auto; margin: 0; }\ .reply { background: #f0e0d6; }\ span { font-size: inherit; }' }, docExt: { value: '.htm' } }, 'form[action*="imgboard.php?delete"]': { tinyIb: { value: true }, qPostRedir: { value: null }, ru: { value: true } }, 'form[name*="postcontrols"]': { tiny: { value: true }, cFileInfo: { value: 'fileinfo' }, cOPost: { value: 'op' }, cReply: { value: 'post reply' }, cSubj: { value: 'subject' }, cTrip: { value: 'trip' }, qDForm: { value: 'form[name="postcontrols"]' }, qHide: { value: '.intro ~ *'}, qImgLink: { value: 'p.fileinfo > a:first-of-type' }, qMsg: { value: '.body' }, qName: { value: '.name' }, qOmitted: { value: '.omitted' }, qPages: { value: '.pages > a:nth-last-of-type(2)' }, qPostForm: { value: 'form[name="post"]' }, qPostRedir: { value: null }, qRef: { value: '.post_no:nth-of-type(2)' }, qTrunc: { value: '.toolong' }, firstPage: { value: 1 }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ["'''", "''", '__', '^H', '**', '`', '', '', 'q'] }, }); } }, timePattern: { value: 'nn+dd+yy++w++hh+ii+ss' }, getPageUrl: { value: function(b, p) { return p > 1 ? fixBrd(b) + p + this.docExt : fixBrd(b); } }, getTNum: { value: function(op) { return $q('input[type="checkbox"]', op).name.match(/\d+/)[0]; } }, cssEn: { get: function() { return '.banner, .mentioned, .post-hover { display: none !important; }\ div.post.reply { float: left; clear: left; display: block; }\ form, form table { margin: 0; }'; } } }, 'script[src*="kusaba"]': { kus: { value: true }, cOPost: { value: 'postnode' }, qError: { value: 'h1, h2, div[style*="1.25em"]' }, qPostRedir: { value: null }, cssEn: { value: '.extrabtns, #newposts_get, .replymode, .ui-resizable-handle, blockquote + a { display: none !important; }\ .ui-wrapper { display: inline-block; width: auto !important; height: auto !important; padding: 0 !important; }' }, isBB: { value: true }, rLinkClick: { value: 'onclick="highlight(this.textContent.substr(2), true)"' } }, 'link[href$="phutaba.css"]': { cSubj: { value: 'subject' }, cTrip: { value: 'tripcode' }, qHide: { value: '.post > .post_body' }, qPages: { value: '.pagelist > li:nth-last-child(2)' }, qPostRedir: { value: 'input[name="gb2"][value="thread"]' }, getImgWrap: { value: function(el) { return el.parentNode.parentNode; } }, getSage: { value: function(post) { return !!$q('.sage', post); } }, docExt: { value: '' }, formButtons: { get: function() { return Object.create(this._formButtons, { tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] }, }); } }, isBB: { value: true }, res: { value: 'thread/' } } }; var ibBase = { cFileInfo: 'filesize', cOPost: 'oppost', cReply: 'reply', cRPost: 'reply', cSubj: 'filetitle', cTrip: 'postertrip', qBan: '', qDelBut: 'input[type="submit"]', qDForm: '#delform, form[name="delform"]', qError: 'h1, h2, font[size="5"]', qHide: '.de-ppanel ~ *', get qImgLink() { var val = '.' + this.cFileInfo + ' a[href$=".jpg"]:nth-of-type(1), ' + '.' + this.cFileInfo + ' a[href$=".png"]:nth-of-type(1), ' + '.' + this.cFileInfo + ' a[href$=".gif"]:nth-of-type(1), ' + '.' + this.cFileInfo + ' a[href$=".webm"]:nth-of-type(1)'; Object.defineProperty(this, 'qImgLink', { value: val }); return val; }, qMsg: 'blockquote', get qMsgImgLink() { var val = this.qMsg + ' a[href*=".jpg"], ' + this.qMsg + ' a[href*=".png"], ' + this.qMsg + ' a[href*=".gif"], ' + this.qMsg + ' a[href*=".jpeg"]'; Object.defineProperty(this, 'qMsgImgLink', { value: val }); return val; }, qName: '.postername, .commentpostername', qOmitted: '.omittedposts', qPages: 'table[border="1"] > tbody > tr > td:nth-child(2) > a:last-of-type', qPostForm: '#postform', qPostRedir: 'input[name="postredir"][value="1"]', qRef: '.reflink', qTable: 'form > table, div > table', qThumbImages: '.thumb, .de-thumb, .ca_thumb, img[src*="thumb"], img[src*="/spoiler"], img[src^="blob:"]', get qThread() { var val = $c('thread', doc) ? '.thread' : $q('div[id*="_info"][style*="float"]', doc) ? 'div[id^="t"]:not([style])' : '[id^="thread"]'; Object.defineProperty(this, 'qThread', { value: val }); return val; }, qTrunc: '.abbrev, .abbr, .shortened', getImgLink: function(img) { var el = img.parentNode; return el.tagName === 'SPAN' ? el.parentNode : el; }, getImgSize: function(info) { if(info) { var sz = info.match(/(\d+)\s?[x×]\s?(\d+)/); return [sz[1], sz[2]]; } return [-1, -1]; }, getImgWeight: function(info) { var w = info.match(/(\d+(?:[\.,]\d+)?)\s*([mkк])?i?[bб]/i); return w[2] === 'M' ? (w[1] * 1e3) | 0 : !w[2] ? Math.round(w[1] / 1e3) : w[1]; }, getImgWrap: function(el) { var node = (el.tagName === 'SPAN' ? el.parentNode : el).parentNode; return node.tagName === 'SPAN' ? node.parentNode : node; }, getOmitted: function(el, len) { var txt; return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] + 1 : 1; }, getOp: function(thr) { var el, op, opEnd; if(op = $c(this.cOPost, thr)) { return op; } op = thr.ownerDocument.createElement('div'), opEnd = $q(this.qTable + ', div[id^="repl"]', thr); while((el = thr.firstChild) !== opEnd) { op.appendChild(el); } if(thr.hasChildNodes()) { thr.insertBefore(op, thr.firstChild); } else { thr.appendChild(op); } return op; }, getPNum: function(post) { return post.id.match(/\d+/)[0]; }, getPageUrl: function(b, p) { return fixBrd(b) + (p > 0 ? p + this.docExt : ''); }, getPostEl: function(el) { while(el && !el.classList.contains(this.cRPost) && !el.hasAttribute('de-thread')) { el = el.parentElement; } return el; }, getPosts: function(thr) { return $Q('.' + this.cRPost, thr); }, getSage: function(post) { var a = $q('a[href^="mailto:"], a[href="sage"]', post); return !!a && /sage/i.test(a.href); }, getThrdUrl: function(b, tNum) { return this.prot + '//' + this.host + fixBrd(b) + this.res + tNum + this.docExt; }, getTNum: function(op) { return $q('input[type="checkbox"]', op).value; }, getWrap: function(el, isOp) { if(isOp) { return el; } if(el.tagName === 'TD') { Object.defineProperty(this, 'getWrap', { value: function(el, isOp) { return isOp ? el : getAncestor(el, 'TABLE'); }}); } else { Object.defineProperty(this, 'getWrap', { value: function(el, isOp) { return el; }}); } return this.getWrap(el, isOp); }, insertYtPlayer: function(msg, playerHtml) { msg.insertAdjacentHTML('beforebegin', playerHtml); return msg.previousSibling; }, anchor: '#', css: '', cssEn: '', disableRedirection: function(el) { if(this.qPostRedir) { ($q(this.qPostRedir, el) || {}).checked = true; } }, dm: '', docExt: '.html', firstPage: 0, get _formButtons() { var bb = this.isBB; return { id: ['bold', 'italic', 'under', 'strike', 'spoil', 'code', 'sup', 'sub', 'quote'], val: ['B', 'i', 'U', 'S', '%', 'C', 'v', '^', '&gt;'], tag: bb ? ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] : ['**', '*', '', '^H', '%%', '`', '', '', 'q'], bb: [bb, bb, bb, bb, bb, bb, bb, bb, bb] }; }, get formButtons() { return this._formButtons; }, hasPicWrap: false, host: window.location.hostname, init: null, isBB: false, get lastPage() { var el = $q(this.qPages, doc), val = el && +aProto.pop.call(el.textContent.match(/\d+/g) || []) || 0; if(pageNum === val + 1) { val++; } Object.defineProperty(this, 'lastPage', { value: val }); return val; }, prot: window.location.protocol, get reCrossLinks() { var val = new RegExp('>https?:\\/\\/[^\\/]*' + this.dm + '\\/([a-z0-9]+)\\/' + regQuote(this.res) + '(\\d+)(?:[^#<]+)?(?:#i?(\\d+))?<', 'g'); Object.defineProperty(this, 'reCrossLinks', { value: val }); return val; }, get rep() { var val = dTime || spells.haveReps || Cfg['crossLinks']; Object.defineProperty(this, 'rep', { value: val }); return val; }, res: 'res/', rLinkClick: 'onclick="highlight(this.textContent.substr(2))"', ru: false, timePattern: 'w+dd+m+yyyy+hh+ii+ss' }; var i, ibObj = null, dm = window.location.hostname .match(/(?:(?:[^.]+\.)(?=org\.|net\.|com\.))?[^.]+\.[^.]+$|^\d+\.\d+\.\d+\.\d+$|localhost/)[0]; if(checkDomains) { if(dm in ibDomains) { ibObj = (function createBoard(info) { return Object.create( info[2] ? createBoard(ibDomains[info[2]]) : info[1] ? Object.create(ibBase, ibEngines[info[1]]) : ibBase, info[0] ); })(ibDomains[dm]); checkOther = false; } } if(checkOther) { for(i in ibEngines) { if($q(i, doc)) { ibObj = Object.create(ibBase, ibEngines[i]); break; } } if(!ibObj) { ibObj = ibBase; } } if(ibObj) { ibObj.dm = dm; } return ibObj; }; //============================================================================================================ // BROWSER //============================================================================================================ function getNavFuncs() { if(!('contains' in String.prototype)) { String.prototype.contains = function(s) { return this.indexOf(s) !== -1; }; String.prototype.startsWith = function(s) { return this.indexOf(s) === 0; }; } if(!('repeat' in String.prototype)) { String.prototype.repeat = function(nTimes) { return new Array(nTimes + 1).join(this.valueOf()); }; } if(!('clz32' in Math)) { Math.clz32 = function(x) { return x < 1 ? x === 0 ? 32 : 0 : 31 - ((Math.log(x) / Math.LN2) >> 0); }; } if('toJSON' in aProto) { delete aProto.toJSON; } if(!('URL' in window)) { window.URL = window.webkitURL; } var ua = window.navigator.userAgent, presto = window.opera ? +window.opera.version() : 0, opera11 = presto ? presto < 12.1 : false, webkit = ua.contains('WebKit/'), chrome = webkit && ua.contains('Chrome/'), safari = webkit && !chrome, isGM = typeof GM_setValue === 'function' && (!chrome || !GM_setValue.toString().contains('not supported')), isChromeStorage = window.chrome && !!window.chrome.storage, isScriptStorage = !!scriptStorage && !ua.contains('Opera Mobi'); if(!window.GM_xmlhttpRequest) { window.GM_xmlhttpRequest = $xhr; } return { get ua() { return navigator.userAgent + (this.Firefox ? ' [' + navigator.buildID + ']' : ''); }, Firefox: ua.contains('Gecko/'), Opera11: opera11, Presto: presto, WebKit: webkit, Chrome: chrome, Safari: safari, isGM: isGM, isChromeStorage: isChromeStorage, isScriptStorage: isScriptStorage, isGlobal: isGM || isChromeStorage || isScriptStorage, cssFix: webkit ? '-webkit-' : opera11 ? '-o-' : '', Anim: !opera11, animName: webkit ? 'webkitAnimationName' : opera11 ? 'OAnimationName' : 'animationName', animEnd: webkit ? 'webkitAnimationEnd' : opera11 ? 'oAnimationEnd' : 'animationend', animEvent: function(el, Fn) { el.addEventListener(this.animEnd, function aEvent() { this.removeEventListener(nav.animEnd, aEvent, false); Fn(this); Fn = null; }, false); }, fixLink: safari ? getAbsLink : function fixLink(url) { return url; }, get hasWorker() { var val = 'Worker' in (this.Firefox ? unsafeWindow : Window); Object.defineProperty(this, 'hasWorker', { value: val }); return val; }, get canPlayMP3() { var val = !!new Audio().canPlayType('audio/mp3; codecs="mp3"'); Object.defineProperty(this, 'canPlayMP3', { value: val }); return val; }, get canPlayWebm() { var val = !!new Audio().canPlayType('video/webm; codecs="vp8,vorbis"'); Object.defineProperty(this, 'canPlayWebm', { value: val }); return val; }, get matchesSelector() { var dE = doc.documentElement, fun = dE.matchesSelector || dE.mozMatchesSelector || dE.webkitMatchesSelector || dE.oMatchesSelector, val = Function.prototype.call.bind(fun); Object.defineProperty(this, 'matchesSelector', { value: val }); return val; } }; } //============================================================================================================ // INITIALIZATION //============================================================================================================ function Initialization(checkDomains) { if(/^(?:about|chrome|opera|res)/i.test(window.location)) { return false; } try { locStorage = window.localStorage; sesStorage = window.sessionStorage; sesStorage['__de-test'] = 1; } catch(e) { if(typeof unsafeWindow !== 'undefined') { locStorage = unsafeWindow.localStorage; sesStorage = unsafeWindow.sessionStorage; } } if(!(locStorage && typeof locStorage === 'object' && sesStorage)) { GM_log('WEBSTORAGE ERROR: please, enable webstorage!'); return false; } var intrv, url; switch(window.name) { case '': break; case 'de-iframe-pform': case 'de-iframe-dform': $script('window.top.postMessage("A' + window.name + '" + document.documentElement.outerHTML, "*");'); return false; case 'de-iframe-fav': intrv = setInterval(function() { $script('window.top.postMessage("B' + (doc.body.offsetHeight + 5) + '", "*");'); }, 1500); window.addEventListener('load', setTimeout.bind(window, clearInterval, 3e4, intrv), false); liteMode = true; pr = {}; } if(!aib) { aib = getImageBoard(checkDomains, true); } if(aib.init && aib.init()) { return false; } dForm = $q(aib.qDForm, doc); if(!dForm || $id('de-panel')) { return false; } nav = getNavFuncs(); window.addEventListener('storage', function(e) { var data, temp, post, val = e.newValue; if(!val) { return; } switch(e.key) { case '__de-post': { try { data = JSON.parse(val); } catch(e) { return; } temp = data['hide']; if(data['brd'] === brd && (post = pByNum[data['num']]) && (post.hidden ^ temp)) { post.setUserVisib(temp, data['date'], false); } else { if(!(data['brd'] in bUVis)) { bUVis[data['brd']] = {}; } bUVis[data['brd']][data['num']] = [+!temp, data['date']]; } if(data['isOp']) { if(!(data['brd'] in hThr)) { if(temp) { hThr[data['brd']] = {}; } else { break; } } if(temp) { hThr[data['brd']][data['num']] = data['title']; } else { delete hThr[data['brd']][data['num']]; } } break; } case '__de-threads': { try { hThr = JSON.parse(val); } catch(e) { return; } if(!(brd in hThr)) { hThr[brd] = {}; } firstThr.updateHidden(hThr[brd]); break; } case '__de-spells': { try { data = JSON.parse(val); } catch(e) { return; } Cfg['hideBySpell'] = data['hide']; if(temp = $q('input[info="hideBySpell"]', doc)) { temp.checked = data['hide']; } doc.body.style.display = 'none'; disableSpells(); if(data['data']) { spells.setSpells(data['data'], false); if(temp = $id('de-spell-edit')) { temp.value = spells.list; } } else { if(data['data'] === '') { spells.disable(); if(temp = $id('de-spell-edit')) { temp.value = ''; } saveCfg('spells', ''); } spells.enable = false; } doc.body.style.display = ''; } default: return; } toggleContent('hid', true); }, false); url = (window.location.pathname || '').match(new RegExp( '^(?:\\/?([^\\.]*?(?:\\/[^\\/]*?)?)\\/?)?' + '(' + regQuote(aib.res) + ')?' + '(\\d+|index|wakaba|futaba)?' + '(\\.(?:[a-z]+))?(?:\\/|$)' )); brd = url[1].replace(/\/$/, ''); TNum = url[2] ? url[3] : aib.futa ? +(window.location.search.match(/\d+/) || [false])[0] : false; pageNum = url[3] && !TNum ? +url[3] || aib.firstPage : aib.firstPage; if(!aib.hasOwnProperty('docExt') && url[4]) { aib.docExt = url[4]; } dummy = doc.createElement('div'); return true; } function parseThreadNodes(form, threads) { var el, i, len, node, fNodes = aProto.slice.call(form.childNodes), cThr = doc.createElement('div'); for(i = 0, len = fNodes.length - 1; i < len; ++i) { node = fNodes[i]; if(node.tagName === 'HR') { form.insertBefore(cThr, node); form.insertBefore(cThr.lastElementChild, node); el = cThr.lastElementChild; if(el.tagName === 'BR') { form.insertBefore(el, node); } threads.push(cThr); cThr = doc.createElement('div'); } else { cThr.appendChild(node); } } cThr.appendChild(fNodes[i]); form.appendChild(cThr); return threads; } function parseDelform(node, thrds) { var i, lThr, len = thrds.length; $each($T('script', node), $del); if(len === 0) { Thread.parsed = true; thrds = parseThreadNodes(dForm, []); len = thrds.length; } if(len) { firstThr = lThr = new Thread(thrds[0], null); } for(i = 1; i < len; i++) { lThr = new Thread(thrds[i], lThr); } lastThr = lThr; node.setAttribute('de-form', ''); node.removeAttribute('id'); if(aib.abu && TNum) { lThr = firstThr.el; while((node = lThr.nextSibling) && node.tagName !== 'HR') { $del(node); } } } function replaceString(txt) { if(dTime) { txt = dTime.fix(txt); } if(aib.fch || aib.krau) { if(aib.fch) { txt = txt.replace(/(?:<span>)?([^\s<>]+)<wbr>([^\s<>]+)(?:<\/span>)?/g, '$1$2'); } txt = txt.replace(/(^|>|\s|&gt;)(https*:\/\/.*?)(<\/a>)?(?=$|<|\s)/ig, function(x, a, b, c) { return c ? x : a + '<a href="' + b + '">' + b + '</a>'; }); } if(spells.haveReps) { txt = spells.replace(txt); } if(Cfg['crossLinks']) { txt = txt.replace(aib.reCrossLinks, function(str, b, tNum, pNum) { return '>&gt;&gt;/' + b + '/' + (pNum || tNum) + '<'; }); } return txt; } function replacePost(el) { if(aib.rep) { el.innerHTML = replaceString(el.innerHTML); } return el; } function replaceDelform() { if(liteMode) { doc.body.insertAdjacentHTML('afterbegin', dForm.outerHTML); dForm = doc.body.firstChild; window.addEventListener('load', function() { while(dForm.nextSibling) { $del(dForm.nextSibling); } }, false); } else if(aib.rep) { dForm.insertAdjacentHTML('beforebegin', replaceString(dForm.outerHTML)); dForm.style.display = 'none'; dForm.id = 'de-dform-old'; dForm = dForm.previousSibling; window.addEventListener('load', function() { $del($id('de-dform-old')); }, false); } } function initDelformAjax() { var btn; if(Cfg['ajaxReply'] === 2) { dForm.onsubmit = $pd; if(btn = $q(aib.qDelBut, dForm)) { btn.onclick = function(e) { $pd(e); pr.closeQReply(); $alert(Lng.deleting[lang], 'deleting', true); new html5Submit(dForm, e.target, checkDelete); }; } } else if(Cfg['ajaxReply'] === 1) { dForm.insertAdjacentHTML('beforeend', '<iframe name="de-iframe-pform" src="about:blank" style="display: none;"></iframe>' + '<iframe name="de-iframe-dform" src="about:blank" style="display: none;"></iframe>' ); dForm.target = 'de-iframe-dform'; dForm.onsubmit = function() { pr.closeQReply(); $alert(Lng.deleting[lang], 'deleting', true); }; } } function initThreadUpdater(title, enableUpdate) { var focused, delay, checked404, loadTO, audioRep, currentXHR, audioEl, stateButton, hasAudio, initDelay, favIntrv, favNorm, favHref, notifGranted, enabled = false, disabledByUser = true, inited = false, lastECode = 200, sendError = false, newPosts = 0, aPlayers = 0; if(('hidden' in doc) || ('webkitHidden' in doc)) { focused = !(doc.hidden || doc.webkitHidden); doc.addEventListener((nav.WebKit ? 'webkit' : '') + 'visibilitychange', function() { if(doc.hidden || doc.webkitHidden) { focused = false; firstThr && firstThr.clearPostsMarks(); } else { onVis(); } }, false); } else { focused = false; window.addEventListener('focus', onVis, false); window.addEventListener('blur', function() { focused = false; firstThr.clearPostsMarks(); }, false); window.addEventListener('mousemove', function mouseMove() { window.removeEventListener('mousemove', mouseMove, false); onVis(); }, false); } if(enableUpdate) { init(); } if(focused && Cfg['desktNotif'] && ('permission' in Notification)) { switch(Notification.permission.toLowerCase()) { case 'default': requestNotifPermission(); break; case 'denied': saveCfg('desktNotif', 0); } } function init() { audioEl = null; stateButton = null; hasAudio = false; initDelay = Cfg['updThrDelay'] * 1e3; favIntrv = 0; favNorm = notifGranted = inited = true; favHref = ($q('head link[rel="shortcut icon"]', doc) || {}).href; enable(true); } function enable(startLoading) { enabled = true; checked404 = false; newPosts = 0; delay = initDelay; if(startLoading) { loadTO = setTimeout(loadPostsFun, delay); } } function disable(byUser) { disabledByUser = byUser; if(enabled) { clearTimeout(loadTO); enabled = hasAudio = false; setState('off'); var btn = $id('de-btn-audio-on'); if(btn) { btn.id = 'de-btn-audio-off'; } } } function toggleAudio(aRep) { if(!audioEl) { audioEl = $new('audio', { 'preload': 'auto', 'src': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/signal.ogg' }, null); } audioRep = aRep; return hasAudio = !hasAudio; } function audioNotif() { if(focused) { hasAudio = false; } else { audioEl.play() setTimeout(audioNotif, audioRep); hasAudio = true; } } function requestNotifPermission() { notifGranted = false; Notification.requestPermission(function(state) { if(state.toLowerCase() === 'denied') { saveCfg('desktNotif', 0); } else { notifGranted = true; } }); } function loadPostsFun() { currentXHR = firstThr.loadNew(onLoaded, true); } function forceLoadPosts() { if(currentXHR) { currentXHR.abort(); } if(!enabled && !disabledByUser) { enable(false); } else { clearTimeout(loadTO); delay = initDelay; } loadPostsFun(); } function onLoaded(eCode, eMsg, lPosts, xhr) { if(currentXHR !== xhr && eCode === 0) { // Loading aborted return; } currentXHR = null; infoLoadErrors(eCode, eMsg, -1); if(eCode !== 200 && eCode !== 304) { lastECode = eCode; if(!Cfg['noErrInTitle']) { updateTitle(); } if(eCode !== 0 && Math.floor(eCode / 500) === 0) { if(eCode === 404 && !checked404) { checked404 = true; } else { updateTitle(); disable(false); return; } } setState('warn'); if(enabled) { loadTO = setTimeout(loadPostsFun, delay); } return; } if(lastECode !== 200) { lastECode = 200; setState('on'); checked404 = false; if((focused || lPosts === 0) && !Cfg['noErrInTitle']) { updateTitle(); } } if(!focused) { if(lPosts !== 0) { if(Cfg['favIcoBlink'] && favHref && newPosts === 0) { favIntrv = setInterval(function() { $del($q('link[rel="shortcut icon"]', doc.head)); doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' + (!favNorm ? favHref : 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAA' + 'AQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVR' + 'Ix2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII=') + '">'); favNorm = !favNorm; }, 800); } newPosts += lPosts; updateTitle(); if(Cfg['desktNotif'] && notifGranted) { var post = firstThr.last, imgs = post.images, notif = new Notification(aib.dm + '/' + brd + '/' + TNum + ': ' + newPosts + Lng.newPost[lang][lang !== 0 ? +(newPosts !== 1) : (newPosts % 10) > 4 || (newPosts % 10) === 0 || (((newPosts % 100) / 10) | 0) === 1 ? 2 : (newPosts % 10) === 1 ? 0 : 1] + Lng.newPost[lang][3], { 'body': post.text.substring(0, 250).replace(/\s+/g, ' '), 'tag': aib.dm + brd + TNum, 'icon': imgs.length === 0 ? favHref : imgs[0].src }); notif.onshow = function() { setTimeout(this.close.bind(this), 12e3); }; notif.onclick = function() { window.focus(); }; notif.onerror = function() { window.focus(); requestNotifPermission(); }; } if(hasAudio) { if(audioRep) { audioNotif(); } else { audioEl.play() } } delay = initDelay; } else if(delay !== 12e4) { delay = Math.min(delay + initDelay, 12e4); } } if(enabled) { loadTO = setTimeout(loadPostsFun, delay); } } function setState(state) { var btn = stateButton || (stateButton = $q('a[id^="de-btn-upd"]', doc)); btn.id = 'de-btn-upd-' + state; btn.title = Lng.panelBtn['upd-' + (state === 'off' ? 'off' : 'on')][lang]; } function onVis() { if(Cfg['favIcoBlink'] && favHref) { clearInterval(favIntrv); favNorm = true; $del($q('link[rel="shortcut icon"]', doc.head)); doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' + favHref + '">'); } newPosts = 0; focused = true; sendError = false; setTimeout(function() { updateTitle(); if(enabled) { forceLoadPosts(); } }, 200); } function updateTitle() { doc.title = (aPlayers === 0 ? '' : '♫ ') + (sendError === true ? '{' + Lng.error[lang] + '} ' : '') + (lastECode === 200 ? '' : '{' + lastECode + '} ') + (newPosts === 0 ? '' : '[' + newPosts + '] ') + title; } function addPlayingTag() { aPlayers++; if(aPlayers === 1) { updateTitle(); } } function removePlayingTag() { aPlayers = Math.max(aPlayers - 1, 0); if(aPlayers === 0) { updateTitle(); } } function sendErrNotif() { if(Cfg['sendErrNotif'] && !focused) { sendError = true; updateTitle(); } } return { get enabled() { return enabled; }, get focused() { return focused; }, forceLoad: forceLoadPosts, enable: function() { if(!inited) { init(); } else if(!enabled) { enable(true); } else { return; } setState('on'); }, disable: function() { disable(true); }, updateXHR: function(newXHR) { currentXHR = newXHR; }, toggleAudio: toggleAudio, addPlayingTag: addPlayingTag, removePlayingTag: removePlayingTag, sendErrNotif: sendErrNotif }; } function initPage() { if(Cfg['updScript']) { checkForUpdates(false, function(html) { $alert(html, 'updavail', false); }); } if(TNum) { if(Cfg['rePageTitle']) { if(aib.abu) { window.addEventListener('load', function() { doc.title = '/' + brd + ' - ' + firstThr.op.title; }, false); } doc.title = '/' + brd + ' - ' + firstThr.op.title; } firstThr.el.insertAdjacentHTML('afterend', '<div id="de-updater-div">&gt;&gt; [<a class="de-abtn" id="de-updater-btn" href="#"></a>]</div>'); firstThr.el.nextSibling.addEventListener('click', Thread.loadNewPosts, false); } else if(needScroll) { setTimeout(window.scrollTo, 20, 0, 0); } updater = initThreadUpdater(doc.title, TNum && Cfg['ajaxUpdThr']); } //============================================================================================================ // MAIN //============================================================================================================ function addDelformStuff(isLog) { preloadImages(null); isLog && new Logger().log('Preload images'); embedMP3Links(null); isLog && new Logger().log('MP3 links'); new YouTube().parseLinks(null); isLog && new Logger().log('YouTube links'); if(Cfg['addImgs']) { embedImagesLinks(dForm); isLog && new Logger().log('Image links'); } if(Cfg['imgSrcBtns']) { addImagesSearch(dForm); isLog && new Logger().log('Sauce buttons'); } if(firstThr && Cfg['linksNavig'] === 2) { genRefMap(pByNum, ''); for(var post = firstThr.op; post; post = post.next) { if(post.hasRef) { addRefMap(post, ''); } } isLog && new Logger().log('Reflinks map'); } } function initScript(checkDomains) { new Logger().init(); if(!Initialization(checkDomains)) { return; } new Logger().log('Init'); readCfg(doScript); } function doScript() { new Logger().log('Config loading'); if(Cfg['disabled']) { addPanel(); scriptCSS(); return; } spells = new Spells(!!Cfg['hideBySpell']); new Logger().log('Parsing spells'); doc.body.style.display = 'none'; replaceDelform(); new Logger().log('Replace delform'); pr = new PostForm($q(aib.qPostForm, doc), false, !liteMode, doc); pByNum = Object.create(null); try { parseDelform(dForm, $Q(aib.qThread, dForm)); } catch(e) { GM_log('DELFORM ERROR:\n' + getPrettyErrorMessage(e)); doc.body.style.display = ''; return; } initDelformAjax(); readViewedPosts(); new Logger().log('Parse delform'); if(Cfg['keybNavig']) { keyNav = new KeyNavigation(); new Logger().log('Init keybinds'); } if(!liteMode) { initPage(); new Logger().log('Init page'); addPanel(); new Logger().log('Add panel'); } initMessageFunctions(); addDelformStuff(true); scriptCSS(); doc.body.style.display = ''; new Logger().log('Apply CSS'); readPosts(); readUserPosts(); readFavoritesPosts(); new Logger().log('Apply spells'); new Logger().finish(); } if(doc.readyState === 'interactive' || doc.readyState === 'complete') { needScroll = false; initScript(true); } else { aib = getImageBoard(true, false); needScroll = true; doc.addEventListener(doc.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll", function wheelFunc(e) { needScroll = false; doc.removeEventListener(e.type, wheelFunc, false); }, false); doc.addEventListener('DOMContentLoaded', initScript.bind(null, false), false); } })(window.opera && window.opera.scriptStorage);
Better new posts indicator in favorites
Dollchan_Extension_Tools.user.js
Better new posts indicator in favorites
<ide><path>ollchan_Extension_Tools.user.js <ide> <ide> function readFavoritesPosts() { <ide> getStoredObj('DESU_Favorites', function(fav) { <del> var thr, temp, update = false; <add> var thr, temp, num, update = false; <ide> if(nav.isChromeStorage && (temp = locStorage.getItem('DESU_Favorites'))) { <ide> temp = JSON.parse(temp); <ide> locStorage.removeItem('DESU_Favorites'); <ide> temp = temp[brd]; <ide> } <ide> for(thr = firstThr; thr; thr = thr.next) { <del> if(thr.num in temp) { <add> if((num = thr.num) in temp) { <ide> $c('de-btn-fav', thr.op.btns).className = 'de-btn-fav-sel'; <ide> if(TNum) { <del> temp[thr.num]['cnt'] = thr.pcount; <del> temp[thr.num]['new'] = 0; <add> temp[num]['cnt'] = thr.pcount; <add> temp[num]['new'] = 0; <ide> } else { <del> temp[thr.num]['new'] = thr.pcount - temp[thr.num]['cnt']; <add> temp[num]['new'] = thr.pcount - temp[num]['cnt']; <ide> } <ide> update = true; <ide> } <ide> $add('<a href="' + i['url'] + '">№' + tNum + '</a>'), <ide> $add('<span class="de-fav-title"> - ' + i['txt'] + '</span>'), <ide> $add('<span class="de-fav-inf-page"></span>'), <del> $add('<span class="de-fav-inf-posts">[<span class="de-fav-inf-old">' + i['cnt'] + <del> '</span>][<span class="de-fav-inf-new">' + i['new'] + '</span>]</span>') <add> $add('<span class="de-fav-inf-posts">[<span class="de-fav-inf-old">' + <add> i['cnt'] + '</span>]<span class="de-fav-inf-new"' + <add> (i['new'] === 0 ? ' style="display: none;"' : '') + <add> '>' + i['new'] + '</span></span>') <ide> ]) <ide> ])); <ide> } <ide> b = el.getAttribute('de-board'), <ide> num = el.getAttribute('de-num'), <ide> f = fav[host][b][num]; <del> if(host !== aib.host || TNum && num === TNum && b === brd) { <add> if(host !== aib.host) { <ide> queue.end(qIdx); <ide> return; <ide> } <ide> var cnt = aib.getPosts(form).length + 1 - this.previousElementSibling.textContent; <ide> this.textContent = cnt; <ide> this.classList.remove('de-wait'); <del> if(cnt > 0) { <add> if(cnt === 0) { <add> this.style.display = 'none'; <add> } else { <add> this.style.display = ''; <ide> f['new'] = cnt; <ide> update = true; <ide> } <ide> .de-entry > div > a { text-decoration: none; }\ <ide> .de-fav-inf-posts, .de-fav-inf-page { float: right; margin-right: 5px; font: bold 16px serif; }\ <ide> .de-fav-inf-new { color: #424f79; }\ <add> .de-fav-inf-new:before { content: " + "; }\ <ide> .de-fav-inf-old { color: #4f7942; }\ <ide> .de-fav-title { margin-right: 15px; }\ <ide> .de-file { display: inline-block; margin: 1px; height: 130px; width: 130px; text-align: center; border: 1px dashed grey; }\ <ide> if(el = $id('de-content-fav')) { <ide> el = $q('.de-fav-current > .de-entry[de-num="' + this.op.num + '"] .de-fav-inf-old', el); <ide> el.textContent = this.pcount; <del> el.nextElementSibling.textContent = 0; <add> el = el.nextElementSibling; <add> el.style.display = 'none'; <add> el.textContent = 0; <ide> } <ide> f['cnt'] = this.pcount; <ide> f['new'] = 0;
Java
apache-2.0
b829e4e48b54e3de6b55be60307759696390a9f1
0
ceylon/ceylon-module-resolver,alesj/ceylon-module-resolver,jvasileff/ceylon-module-resolver,ceylon/ceylon-module-resolver,jvasileff/ceylon-module-resolver,alesj/ceylon-module-resolver
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ceylon.cmr.api; import java.io.Serializable; /** * Artifact lookup context. * * @author <a href="mailto:[email protected]">Ales Justin</a> */ public class ArtifactContext implements Serializable { public static final String CAR = ".car"; public static final String JAR = ".jar"; public static final String ZIP = ".zip"; public static final String SRC = ".src"; public static final String SHA1 = ".sha1"; private String name; private String version; private String suffix = CAR; private boolean localOnly; private boolean ignoreSHA; private boolean throwErrorIfMissing; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public boolean isLocalOnly() { return localOnly; } public void setLocalOnly(boolean localOnly) { this.localOnly = localOnly; } public boolean isIgnoreSHA() { return ignoreSHA; } public void setIgnoreSHA(boolean ignoreSHA) { this.ignoreSHA = ignoreSHA; } public boolean isThrowErrorIfMissing() { return throwErrorIfMissing; } public void setThrowErrorIfMissing(boolean throwErrorIfMissing) { this.throwErrorIfMissing = throwErrorIfMissing; } @Override public String toString() { return getName() + "-" + getVersion(); } }
api/src/main/java/com/redhat/ceylon/cmr/api/ArtifactContext.java
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ceylon.cmr.api; import java.io.Serializable; /** * Artifact lookup context. * * @author <a href="mailto:[email protected]">Ales Justin</a> */ public class ArtifactContext implements Serializable { public static final String CAR = ".car"; public static final String JAR = ".jar"; public static final String ZIP = ".zip"; public static final String SRC = ".src"; private String name; private String version; private String suffix = CAR; private boolean localOnly; private boolean ignoreSHA; private boolean throwErrorIfMissing; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public boolean isLocalOnly() { return localOnly; } public void setLocalOnly(boolean localOnly) { this.localOnly = localOnly; } public boolean isIgnoreSHA() { return ignoreSHA; } public void setIgnoreSHA(boolean ignoreSHA) { this.ignoreSHA = ignoreSHA; } public boolean isThrowErrorIfMissing() { return throwErrorIfMissing; } public void setThrowErrorIfMissing(boolean throwErrorIfMissing) { this.throwErrorIfMissing = throwErrorIfMissing; } @Override public String toString() { return getName() + "-" + getVersion(); } }
ArtifactContext: added SHA1 postfix constant
api/src/main/java/com/redhat/ceylon/cmr/api/ArtifactContext.java
ArtifactContext: added SHA1 postfix constant
<ide><path>pi/src/main/java/com/redhat/ceylon/cmr/api/ArtifactContext.java <ide> public static final String JAR = ".jar"; <ide> public static final String ZIP = ".zip"; <ide> public static final String SRC = ".src"; <add> public static final String SHA1 = ".sha1"; <ide> <ide> private String name; <ide> private String version;
Java
apache-2.0
7c4a0dea94bed2d3f0ab29e14731fef644332d76
0
hurricup/intellij-community,vladmm/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,supersven/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,clumsy/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,izonder/intellij-community,adedayo/intellij-community,supersven/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,semonte/intellij-community,supersven/intellij-community,gnuhub/intellij-community,slisson/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,fitermay/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,clumsy/intellij-community,ernestp/consulo,ahb0327/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,jexp/idea2,blademainer/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,kool79/intellij-community,caot/intellij-community,samthor/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,clumsy/intellij-community,fnouama/intellij-community,signed/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,caot/intellij-community,fnouama/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,robovm/robovm-studio,semonte/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,jagguli/intellij-community,semonte/intellij-community,xfournet/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,da1z/intellij-community,vladmm/intellij-community,allotria/intellij-community,slisson/intellij-community,fitermay/intellij-community,supersven/intellij-community,caot/intellij-community,suncycheng/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,signed/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,holmes/intellij-community,caot/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,holmes/intellij-community,adedayo/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,semonte/intellij-community,clumsy/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,robovm/robovm-studio,robovm/robovm-studio,asedunov/intellij-community,kool79/intellij-community,kool79/intellij-community,izonder/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,consulo/consulo,izonder/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,ryano144/intellij-community,izonder/intellij-community,robovm/robovm-studio,vladmm/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,signed/intellij-community,consulo/consulo,gnuhub/intellij-community,holmes/intellij-community,slisson/intellij-community,ryano144/intellij-community,robovm/robovm-studio,petteyg/intellij-community,ibinti/intellij-community,xfournet/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,dslomov/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,slisson/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,kool79/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,supersven/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ryano144/intellij-community,signed/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,allotria/intellij-community,ernestp/consulo,akosyakov/intellij-community,supersven/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,signed/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,ibinti/intellij-community,kool79/intellij-community,FHannes/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,caot/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,kool79/intellij-community,FHannes/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,signed/intellij-community,fitermay/intellij-community,signed/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,da1z/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,blademainer/intellij-community,asedunov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,jexp/idea2,lucafavatella/intellij-community,youdonghai/intellij-community,jexp/idea2,hurricup/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,izonder/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,jagguli/intellij-community,hurricup/intellij-community,asedunov/intellij-community,amith01994/intellij-community,petteyg/intellij-community,holmes/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,orekyuu/intellij-community,holmes/intellij-community,holmes/intellij-community,allotria/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,retomerz/intellij-community,FHannes/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,allotria/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,da1z/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,blademainer/intellij-community,supersven/intellij-community,blademainer/intellij-community,da1z/intellij-community,consulo/consulo,supersven/intellij-community,kool79/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,jagguli/intellij-community,da1z/intellij-community,jagguli/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,fitermay/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,semonte/intellij-community,signed/intellij-community,holmes/intellij-community,slisson/intellij-community,samthor/intellij-community,diorcety/intellij-community,hurricup/intellij-community,vladmm/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,kool79/intellij-community,samthor/intellij-community,jagguli/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,slisson/intellij-community,joewalnes/idea-community,ibinti/intellij-community,amith01994/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,joewalnes/idea-community,asedunov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,suncycheng/intellij-community,ernestp/consulo,akosyakov/intellij-community,diorcety/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,jexp/idea2,TangHao1987/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,ernestp/consulo,ahb0327/intellij-community,kdwink/intellij-community,consulo/consulo,ahb0327/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ibinti/intellij-community,apixandru/intellij-community,da1z/intellij-community,vladmm/intellij-community,adedayo/intellij-community,slisson/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,fitermay/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,dslomov/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,da1z/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,signed/intellij-community,vvv1559/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,dslomov/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,adedayo/intellij-community,ibinti/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,hurricup/intellij-community,da1z/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,diorcety/intellij-community,robovm/robovm-studio,caot/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,signed/intellij-community,samthor/intellij-community,ryano144/intellij-community,allotria/intellij-community,supersven/intellij-community,jagguli/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ibinti/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,samthor/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,semonte/intellij-community,caot/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,jexp/idea2,jexp/idea2,lucafavatella/intellij-community,consulo/consulo,ftomassetti/intellij-community,izonder/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,caot/intellij-community,vvv1559/intellij-community,supersven/intellij-community,amith01994/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,jexp/idea2,nicolargo/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,petteyg/intellij-community,fitermay/intellij-community,vladmm/intellij-community,amith01994/intellij-community,xfournet/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,supersven/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community
package com.intellij.ide.startup.impl; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.io.storage.HeavyProcessLatch; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * @author mike */ public class StartupManagerImpl extends StartupManagerEx { private final List<Runnable> myActivities = new ArrayList<Runnable>(); private final List<Runnable> myPostStartupActivities = Collections.synchronizedList(new ArrayList<Runnable>()); private final List<Runnable> myPreStartupActivities = Collections.synchronizedList(new ArrayList<Runnable>()); private static final Logger LOG = Logger.getInstance("#com.intellij.ide.startup.impl.StartupManagerImpl"); private volatile FileSystemSynchronizerImpl myFileSystemSynchronizer = new FileSystemSynchronizerImpl(); private volatile boolean myStartupActivityRunning = false; private volatile boolean myStartupActivityPassed = false; private volatile boolean myPostStartupActivityPassed = false; private volatile boolean myBackgroundIndexing = false; private final Project myProject; public StartupManagerImpl(Project project) { myProject = project; } public void registerStartupActivity(Runnable runnable) { myActivities.add(runnable); } public synchronized void registerPostStartupActivity(Runnable runnable) { myPostStartupActivities.add(runnable); } public void setBackgroundIndexing(boolean backgroundIndexing) { myBackgroundIndexing = backgroundIndexing; } public boolean startupActivityRunning() { return myStartupActivityRunning; } public boolean startupActivityPassed() { return myStartupActivityPassed; } public boolean postStartupActivityPassed() { return myPostStartupActivityPassed; } public void registerPreStartupActivity(Runnable runnable) { myPreStartupActivities.add(runnable); } public FileSystemSynchronizerImpl getFileSystemSynchronizer() { return myFileSystemSynchronizer; } public void runStartupActivities() { ApplicationManager.getApplication().runReadAction( new Runnable() { public void run() { HeavyProcessLatch.INSTANCE.processStarted(); try { runActivities(myPreStartupActivities); if (myFileSystemSynchronizer != null || !ApplicationManager.getApplication().isUnitTestMode()) { myFileSystemSynchronizer.setCancelable(true); myFileSystemSynchronizer.executeFileUpdate(); myFileSystemSynchronizer = null; } myStartupActivityRunning = true; runActivities(myActivities); myStartupActivityRunning = false; myStartupActivityPassed = true; } finally { HeavyProcessLatch.INSTANCE.processFinished(); } } } ); } public synchronized void runPostStartupActivities() { final Application app = ApplicationManager.getApplication(); app.assertIsDispatchThread(); if (myBackgroundIndexing || DumbService.getInstance().isDumb()) { final List<Runnable> dumbAware = CollectionFactory.arrayList(); for (Iterator<Runnable> iterator = myPostStartupActivities.iterator(); iterator.hasNext();) { Runnable runnable = iterator.next(); if (runnable instanceof DumbAware) { dumbAware.add(runnable); iterator.remove(); } } runActivities(dumbAware); DumbService.getInstance().runWhenSmart(new Runnable() { public void run() { if (myProject.isDisposed()) return; runActivities(myPostStartupActivities); myPostStartupActivities.clear(); myPostStartupActivityPassed = true; } }); } else { runActivities(myPostStartupActivities); myPostStartupActivities.clear(); myPostStartupActivityPassed = true; } if (app.isUnitTestMode()) return; VirtualFileManager.getInstance().refresh(!app.isHeadlessEnvironment()); } private static void runActivities(final List<Runnable> activities) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); while (!activities.isEmpty()) { final Runnable runnable = activities.remove(0); if (indicator != null) indicator.checkCanceled(); try { runnable.run(); } catch (ProcessCanceledException e) { throw e; } catch (Throwable ex) { LOG.error(ex); } } } public void runWhenProjectIsInitialized(final Runnable action) { final Runnable runnable; if (action instanceof DumbAware) { runnable = new DumbAwareRunnable() { public void run() { ApplicationManager.getApplication().runWriteAction(action); } }; } else { runnable = new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(action); } }; } if (myProject.isInitialized()) { runnable.run(); } else { registerPostStartupActivity(runnable); } } }
platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java
package com.intellij.ide.startup.impl; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.io.storage.HeavyProcessLatch; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * @author mike */ public class StartupManagerImpl extends StartupManagerEx { private final List<Runnable> myActivities = new ArrayList<Runnable>(); private final List<Runnable> myPostStartupActivities = Collections.synchronizedList(new ArrayList<Runnable>()); private final List<Runnable> myPreStartupActivities = Collections.synchronizedList(new ArrayList<Runnable>()); private static final Logger LOG = Logger.getInstance("#com.intellij.ide.startup.impl.StartupManagerImpl"); private volatile FileSystemSynchronizerImpl myFileSystemSynchronizer = new FileSystemSynchronizerImpl(); private volatile boolean myStartupActivityRunning = false; private volatile boolean myStartupActivityPassed = false; private volatile boolean myPostStartupActivityPassed = false; private volatile boolean myBackgroundIndexing = false; private final Project myProject; public StartupManagerImpl(Project project) { myProject = project; } public void registerStartupActivity(Runnable runnable) { myActivities.add(runnable); } public synchronized void registerPostStartupActivity(Runnable runnable) { myPostStartupActivities.add(runnable); } public void setBackgroundIndexing(boolean backgroundIndexing) { myBackgroundIndexing = backgroundIndexing; } public boolean startupActivityRunning() { return myStartupActivityRunning; } public boolean startupActivityPassed() { return myStartupActivityPassed; } public boolean postStartupActivityPassed() { return myPostStartupActivityPassed; } public void registerPreStartupActivity(Runnable runnable) { myPreStartupActivities.add(runnable); } public FileSystemSynchronizerImpl getFileSystemSynchronizer() { return myFileSystemSynchronizer; } public void runStartupActivities() { ApplicationManager.getApplication().runReadAction( new Runnable() { public void run() { HeavyProcessLatch.INSTANCE.processStarted(); try { runActivities(myPreStartupActivities); if (myFileSystemSynchronizer != null || !ApplicationManager.getApplication().isUnitTestMode()) { myFileSystemSynchronizer.setCancelable(true); myFileSystemSynchronizer.executeFileUpdate(); myFileSystemSynchronizer = null; } myStartupActivityRunning = true; runActivities(myActivities); myStartupActivityRunning = false; myStartupActivityPassed = true; } finally { HeavyProcessLatch.INSTANCE.processFinished(); } } } ); } public synchronized void runPostStartupActivities() { final Application app = ApplicationManager.getApplication(); app.assertIsDispatchThread(); if (myBackgroundIndexing) { final List<Runnable> dumbAware = CollectionFactory.arrayList(); for (Iterator<Runnable> iterator = myPostStartupActivities.iterator(); iterator.hasNext();) { Runnable runnable = iterator.next(); if (runnable instanceof DumbAware) { dumbAware.add(runnable); iterator.remove(); } } runActivities(dumbAware); DumbService.getInstance().runWhenSmart(new Runnable() { public void run() { if (myProject.isDisposed()) return; runActivities(myPostStartupActivities); myPostStartupActivities.clear(); myPostStartupActivityPassed = true; } }); } else { runActivities(myPostStartupActivities); myPostStartupActivities.clear(); myPostStartupActivityPassed = true; } if (app.isUnitTestMode()) return; VirtualFileManager.getInstance().refresh(!app.isHeadlessEnvironment()); } private static void runActivities(final List<Runnable> activities) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); while (!activities.isEmpty()) { final Runnable runnable = activities.remove(0); if (indicator != null) indicator.checkCanceled(); try { runnable.run(); } catch (ProcessCanceledException e) { throw e; } catch (Throwable ex) { LOG.error(ex); } } } public void runWhenProjectIsInitialized(final Runnable action) { final Runnable runnable; if (action instanceof DumbAware) { runnable = new DumbAwareRunnable() { public void run() { ApplicationManager.getApplication().runWriteAction(action); } }; } else { runnable = new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(action); } }; } if (myProject.isInitialized()) { runnable.run(); } else { registerPostStartupActivity(runnable); } } }
startupManager can also be invoked already in dumb mode
platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java
startupManager can also be invoked already in dumb mode
<ide><path>latform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java <ide> public synchronized void runPostStartupActivities() { <ide> final Application app = ApplicationManager.getApplication(); <ide> app.assertIsDispatchThread(); <del> if (myBackgroundIndexing) { <add> if (myBackgroundIndexing || DumbService.getInstance().isDumb()) { <ide> final List<Runnable> dumbAware = CollectionFactory.arrayList(); <ide> for (Iterator<Runnable> iterator = myPostStartupActivities.iterator(); iterator.hasNext();) { <ide> Runnable runnable = iterator.next();
Java
agpl-3.0
dec46880d9424f87099c6a741108616d4f192deb
0
medsob/Tanaguru,Asqatasun/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,medsob/Tanaguru,Tanaguru/Tanaguru,Tanaguru/Tanaguru,medsob/Tanaguru,dzc34/Asqatasun,medsob/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,Asqatasun/Asqatasun,Tanaguru/Tanaguru,Tanaguru/Tanaguru,dzc34/Asqatasun
package org.opens.tanaguru.contentadapter.util; public abstract class HtmlNodeAttr { public final static String CLASS = "class"; public final static String HREF = "href"; public final static String ID = "id"; public final static String LINK = "link"; public final static String REL = "rel"; public final static String SRC = "src"; public final static String STYLE = "style"; public final static String MEDIA = "media"; }
contentadapter/src/main/java/org/opens/tanaguru/contentadapter/util/HtmlNodeAttr.java
package org.opens.tanaguru.contentadapter.util; public abstract class HtmlNodeAttr { public final static String CLASS = "class"; public final static String HREF = "href"; public final static String ID = "id"; public final static String LINK = "link"; public final static String REL = "rel"; public final static String SRC = "src"; public final static String STYLE = "style"; }
10041 Rule from AccessiWeb2 implementation
contentadapter/src/main/java/org/opens/tanaguru/contentadapter/util/HtmlNodeAttr.java
10041 Rule from AccessiWeb2 implementation
<ide><path>ontentadapter/src/main/java/org/opens/tanaguru/contentadapter/util/HtmlNodeAttr.java <ide> public final static String REL = "rel"; <ide> public final static String SRC = "src"; <ide> public final static String STYLE = "style"; <add> public final static String MEDIA = "media"; <ide> }
JavaScript
apache-2.0
452143a5d7d3171e0c978f657512fe5f673d895b
0
apparentlymart/shindig,apache/shindig,apparentlymart/shindig,apparentlymart/shindig,apache/shindig,apache/shindig,apparentlymart/shindig,apache/shindig,apache/shindig
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var gadgets = gadgets || {}; /** * @fileoverview Provides remote content retrieval facilities. * Available to every gadget. */ /** * @static * @class Provides remote content retrieval functions. * @name gadgets.io */ gadgets.io = function() { /** * Holds configuration-related data such as proxy urls. */ var config = {}; /** * Holds state for OAuth. */ var oauthState; /** * Internal facility to create an xhr request. */ function makeXhr() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { var x = new ActiveXObject("Msxml2.XMLHTTP"); if (!x) { x = new ActiveXObject("Microsoft.XMLHTTP"); } return x; } } /** * Checks the xobj for errors, may call the callback with an error response * if the error is fatal. * * @param {Object} xobj The XHR object to check * @param {Function} callback The callback to call if the error is fatal * @return true if the xobj is not ready to be processed */ function hadError(xobj, callback) { if (xobj.readyState !== 4) { return true; } if (xobj.status !== 200) { // TODO Need to work on standardizing errors callback({errors : ["Error " + xobj.status]}); return true; } return false; } /** * Handles non-proxied XHR callback processing. * * @param {String} url * @param {Function} callback * @param {Object} params * @param {Object} xobj */ function processNonProxiedResponse(url, callback, params, xobj) { if (hadError(xobj, callback)) { return; } var data = { body: xobj.responseText }; callback(transformResponseData(params, data)); } var UNPARSEABLE_CRUFT = "throw 1; < don't be evil' >"; /** * Handles XHR callback processing. * * @param {String} url * @param {Function} callback * @param {Object} params * @param {Object} xobj */ function processResponse(url, callback, params, xobj) { if (hadError(xobj, callback)) { return; } var txt = xobj.responseText; // remove unparseable cruft used to prevent cross-site script inclusion txt = txt.substr(UNPARSEABLE_CRUFT.length); // We are using eval directly here because the outer response comes from a // trusted source, and json parsing is slow in IE. var data = eval("(" + txt + ")"); data = data[url]; // Save off any transient OAuth state the server wants back later. if (data.oauthState) { oauthState = data.oauthState; } // Update the security token if the server sent us a new one if (data.st) { shindig.auth.updateSecurityToken(data.st); } callback(transformResponseData(params, data)); } function transformResponseData(params, data) { var resp = { text: data.body, approvalUrl: data.approvalUrl, errors: [] }; if (resp.text) { switch (params.CONTENT_TYPE) { case "JSON": case "FEED": resp.data = gadgets.json.parse(resp.text); if (!resp.data) { resp.errors.push("failed to parse JSON"); resp.data = null; } break; case "DOM": var dom; if (window.ActiveXObject) { dom = new ActiveXObject("Microsoft.XMLDOM"); dom.async = false; dom.validateOnParse = false; dom.resolveExternals = false; if (!dom.loadXML(resp.text)) { resp.errors.push("failed to parse XML"); } else { resp.data = dom; } } else { var parser = new DOMParser(); dom = parser.parseFromString(resp.text, "text/xml"); if ("parsererror" === dom.documentElement.nodeName) { resp.errors.push("failed to parse XML"); } else { resp.data = dom; } } break; default: resp.data = resp.text; break; } } return resp; } /** * Sends an XHR post or get request * * @param realUrl The url to fetch data from that was requested by the gadget * @param proxyUrl The url to proxy through * @param callback The function to call once the data is fetched * @param postData The data to post to the proxyUrl * @param params The params to use when processing the response * @param processResponseFunction The function that should process the * response from the sever before calling the callback */ function makeXhrRequest(realUrl, proxyUrl, callback, paramData, method, params, processResponseFunction) { var xhr = makeXhr(); xhr.open(method, proxyUrl, true); if (callback) { xhr.onreadystatechange = gadgets.util.makeClosure( null, processResponseFunction, realUrl, callback, params, xhr); } if (paramData != null) { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(paramData); } else { xhr.send(null); } } /** * Satisfy a request with data that is prefetched as per the gadget Preload * directive. The preloader will only satisfy a request for a specific piece * of content once. * * @param postData The definition of the request to be executed by the proxy * @param params The params to use when processing the response * @param callback The function to call once the data is fetched * @return true if the request can be satisfied by the preloaded content * false otherwise */ function respondWithPreload(postData, params, callback) { if (gadgets.io.preloaded_ && gadgets.io.preloaded_[postData.url]) { var preload = gadgets.io.preloaded_[postData.url]; if (postData.httpMethod == "GET") { delete gadgets.io.preloaded_[postData.url]; if (preload.rc !== 200) { callback({errors : ["Error " + preload.rc]}); } else { callback(transformResponseData(params, { body: preload.body })); } return true; } } return false; } /** * @param {Object} configuration Configuration settings * @private */ function init (configuration) { config = configuration["core.io"]; } var requiredConfig = { proxyUrl: new gadgets.config.RegExValidator(/.*%(raw)?url%.*/), jsonProxyUrl: gadgets.config.NonEmptyStringValidator }; gadgets.config.register("core.io", requiredConfig, init); return /** @scope gadgets.io */ { /** * Fetches content from the provided URL and feeds that content into the * callback function. * * Example: * <pre> * gadgets.io.makeRequest(url, fn, * {contentType: gadgets.io.ContentType.FEED}); * </pre> * * @param {String} url The URL where the content is located * @param {Function} callback The function to call with the data from the * URL once it is fetched * @param {Map.&lt;gadgets.io.RequestParameters, Object&gt;} opt_params * Additional * <a href="gadgets.io.RequestParameters.html">parameters</a> * to pass to the request * * @member gadgets.io */ makeRequest : function (url, callback, opt_params) { // TODO: This method also needs to respect all members of // gadgets.io.RequestParameters, and validate them. var params = opt_params || {}; // Check if authorization is requested var auth, st; var reqState, oauthService, oauthToken; if (params.AUTHORIZATION && params.AUTHORIZATION !== "NONE") { auth = params.AUTHORIZATION.toLowerCase(); st = shindig.auth.getSecurityToken(); if (params.AUTHORIZATION === "AUTHENTICATED") { reqState = oauthState; oauthService = params.OAUTH_SERVICE; oauthToken = params.OAUTH_TOKEN; } } else { // Non auth'd & non post'd requests are cachable if (!params.REFRESH_INTERVAL && !params.POST_DATA) { params.REFRESH_INTERVAL = 3600; } } var signOwner = params.OWNER_SIGNED; var signViewer = params.VIEWER_SIGNED; var headers = params.HEADERS || {}; if (params.METHOD === "POST" && !headers["Content-Type"]) { headers["Content-Type"] = "application/x-www-form-urlencoded"; } var paramData = { url: url, httpMethod : params.METHOD || "GET", headers: gadgets.io.encodeValues(headers, false), postData : params.POST_DATA || "", authz : auth || "", st : st || "", oauthState : reqState || "", oauthService : oauthService || "", oauthToken : oauthToken || "", contentType : params.CONTENT_TYPE || "TEXT", numEntries : params.NUM_ENTRIES || "3", getSummaries : !!params.GET_SUMMARIES, signOwner : signOwner || "true", signViewer : signViewer || "true", gadget : gadgets.util.getUrlParameters()["url"], // should we bypass gadget spec cache (e.g. to read OAuth provider URLs) bypassSpecCache : gadgets.util.getUrlParameters().nocache || "" }; if (!respondWithPreload(paramData, params, callback, processResponse)) { var refreshInterval = params.REFRESH_INTERVAL || 0; if (refreshInterval > 0) { // this content should be cached // Add paramData to the URL var extraparams = "?refresh=" + refreshInterval + '&' + gadgets.io.encodeValues(paramData); makeXhrRequest(url, config.jsonProxyUrl + extraparams, callback, null, "GET", params, processResponse); } else { makeXhrRequest(url, config.jsonProxyUrl, callback, gadgets.io.encodeValues(paramData), "POST", params, processResponse); } } }, /** * @private */ makeNonProxiedRequest : function (relativeUrl, callback, opt_params) { var params = opt_params || {}; makeXhrRequest(relativeUrl, relativeUrl, callback, params.POST_DATA, params.METHOD, params, processNonProxiedResponse); }, /** * Converts an input object into a URL-encoded data string. * (key=value&amp;...) * * @param {Object} fields The post fields you wish to encode * @param {Boolean} opt_noEscaping An optional parameter specifying whether * to turn off escaping of the parameters. Defaults to false. * @return {String} The processed post data in www-form-urlencoded format. * * @member gadgets.io */ encodeValues : function (fields, opt_noEscaping) { var escape = !opt_noEscaping; var buf = []; var first = false; for (var i in fields) if (fields.hasOwnProperty(i)) { if (!first) { first = true; } else { buf.push("&"); } buf.push(escape ? encodeURIComponent(i) : i); buf.push("="); buf.push(escape ? encodeURIComponent(fields[i]) : fields[i]); } return buf.join(""); }, /** * Gets the proxy version of the passed-in URL. * * @param {String} url The URL to get the proxy URL for * @param {Object} opt_params Optional Parameter Object. * The following properties are supported: * .REFRESH_INTERVAL The number of seconds that this * content should be cached. Defaults to 3600. * * @return {String} The proxied version of the URL * * @member gadgets.io */ getProxyUrl : function (url, opt_params) { var params = opt_params || {}; var refresh = params['REFRESH_INTERVAL'] || '3600'; return config.proxyUrl.replace("%url%", encodeURIComponent(url)). replace("%rawurl%", url). replace("%refresh%", encodeURIComponent(refresh)); } }; }(); gadgets.io.RequestParameters = gadgets.util.makeEnum([ "METHOD", "CONTENT_TYPE", "POST_DATA", "HEADERS", "AUTHORIZATION", "NUM_ENTRIES", "GET_SUMMARIES", "REFRESH_INTERVAL", "OAUTH_SERVICE", "OAUTH_TOKEN" ]); gadgets.io.MethodType = gadgets.util.makeEnum([ "GET", "POST", "PUT", "DELETE", "HEAD" ]); gadgets.io.ContentType = gadgets.util.makeEnum([ "TEXT", "DOM", "JSON", "FEED" ]); gadgets.io.AuthorizationType = gadgets.util.makeEnum([ "NONE", "SIGNED", "AUTHENTICATED" ]);
features/core.io/io.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var gadgets = gadgets || {}; /** * @fileoverview Provides remote content retrieval facilities. * Available to every gadget. */ /** * @static * @class Provides remote content retrieval functions. * @name gadgets.io */ gadgets.io = function() { /** * Holds configuration-related data such as proxy urls. */ var config = {}; /** * Holds state for OAuth. */ var oauthState; /** * Internal facility to create an xhr request. */ function makeXhr() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { var x = new ActiveXObject("Msxml2.XMLHTTP"); if (!x) { x = new ActiveXObject("Microsoft.XMLHTTP"); } return x; } } /** * Checks the xobj for errors, may call the callback with an error response * if the error is fatal. * * @param {Object} xobj The XHR object to check * @param {Function} callback The callback to call if the error is fatal * @return true if the xobj is not ready to be processed */ function hadError(xobj, callback) { if (xobj.readyState !== 4) { return true; } if (xobj.status !== 200) { // TODO Need to work on standardizing errors callback({errors : ["Error " + xobj.status]}); return true; } return false; } /** * Handles non-proxied XHR callback processing. * * @param {String} url * @param {Function} callback * @param {Object} params * @param {Object} xobj */ function processNonProxiedResponse(url, callback, params, xobj) { if (hadError(xobj, callback)) { return; } var data = { body: xobj.responseText }; callback(transformResponseData(params, data)); } var UNPARSEABLE_CRUFT = "throw 1; < don't be evil' >"; /** * Handles XHR callback processing. * * @param {String} url * @param {Function} callback * @param {Object} params * @param {Object} xobj */ function processResponse(url, callback, params, xobj) { if (hadError(xobj, callback)) { return; } var txt = xobj.responseText; // remove unparseable cruft. // TODO: really remove this by eliminating it. It's not any real security // to begin with, and we can solve this problem by using post requests // and / or passing the url in the http headers. txt = txt.substr(UNPARSEABLE_CRUFT.length); // We are using eval directly here because the outer response comes from a // trusted source, and json parsing is slow in IE. var data = eval("(" + txt + ")"); data = data[url]; // Save off any transient OAuth state the server wants back later. if (data.oauthState) { oauthState = data.oauthState; } // Update the security token if the server sent us a new one if (data.st) { shindig.auth.updateSecurityToken(data.st); } callback(transformResponseData(params, data)); } function transformResponseData(params, data) { var resp = { text: data.body, approvalUrl: data.approvalUrl, errors: [] }; if (resp.text) { switch (params.CONTENT_TYPE) { case "JSON": case "FEED": resp.data = gadgets.json.parse(resp.text); if (!resp.data) { resp.errors.push("failed to parse JSON"); resp.data = null; } break; case "DOM": var dom; if (window.ActiveXObject) { dom = new ActiveXObject("Microsoft.XMLDOM"); dom.async = false; dom.validateOnParse = false; dom.resolveExternals = false; if (!dom.loadXML(resp.text)) { resp.errors.push("failed to parse XML"); } else { resp.data = dom; } } else { var parser = new DOMParser(); dom = parser.parseFromString(resp.text, "text/xml"); if ("parsererror" === dom.documentElement.nodeName) { resp.errors.push("failed to parse XML"); } else { resp.data = dom; } } break; default: resp.data = resp.text; break; } } return resp; } /** * Sends an XHR post or get request * * @param realUrl The url to fetch data from that was requested by the gadget * @param proxyUrl The url to proxy through * @param callback The function to call once the data is fetched * @param postData The data to post to the proxyUrl * @param params The params to use when processing the response * @param processResponseFunction The function that should process the * response from the sever before calling the callback */ function makeXhrRequest(realUrl, proxyUrl, callback, paramData, method, params, processResponseFunction) { var xhr = makeXhr(); xhr.open(method, proxyUrl, true); if (callback) { xhr.onreadystatechange = gadgets.util.makeClosure( null, processResponseFunction, realUrl, callback, params, xhr); } if (paramData != null) { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(paramData); } else { xhr.send(null); } } /** * Satisfy a request with data that is prefetched as per the gadget Preload * directive. The preloader will only satisfy a request for a specific piece * of content once. * * @param postData The definition of the request to be executed by the proxy * @param params The params to use when processing the response * @param callback The function to call once the data is fetched * @return true if the request can be satisfied by the preloaded content * false otherwise */ function respondWithPreload(postData, params, callback) { if (gadgets.io.preloaded_ && gadgets.io.preloaded_[postData.url]) { var preload = gadgets.io.preloaded_[postData.url]; if (postData.httpMethod == "GET") { delete gadgets.io.preloaded_[postData.url]; if (preload.rc !== 200) { callback({errors : ["Error " + preload.rc]}); } else { callback(transformResponseData(params, { body: preload.body })); } return true; } } return false; } /** * @param {Object} configuration Configuration settings * @private */ function init (configuration) { config = configuration["core.io"]; } var requiredConfig = { proxyUrl: new gadgets.config.RegExValidator(/.*%(raw)?url%.*/), jsonProxyUrl: gadgets.config.NonEmptyStringValidator }; gadgets.config.register("core.io", requiredConfig, init); return /** @scope gadgets.io */ { /** * Fetches content from the provided URL and feeds that content into the * callback function. * * Example: * <pre> * gadgets.io.makeRequest(url, fn, * {contentType: gadgets.io.ContentType.FEED}); * </pre> * * @param {String} url The URL where the content is located * @param {Function} callback The function to call with the data from the * URL once it is fetched * @param {Map.&lt;gadgets.io.RequestParameters, Object&gt;} opt_params * Additional * <a href="gadgets.io.RequestParameters.html">parameters</a> * to pass to the request * * @member gadgets.io */ makeRequest : function (url, callback, opt_params) { // TODO: This method also needs to respect all members of // gadgets.io.RequestParameters, and validate them. var params = opt_params || {}; // Check if authorization is requested var auth, st; var reqState, oauthService, oauthToken; if (params.AUTHORIZATION && params.AUTHORIZATION !== "NONE") { auth = params.AUTHORIZATION.toLowerCase(); st = shindig.auth.getSecurityToken(); if (params.AUTHORIZATION === "AUTHENTICATED") { reqState = oauthState; oauthService = params.OAUTH_SERVICE; oauthToken = params.OAUTH_TOKEN; } } else { // Non auth'd & non post'd requests are cachable if (!params.REFRESH_INTERVAL && !params.POST_DATA) { params.REFRESH_INTERVAL = 3600; } } var signOwner = params.OWNER_SIGNED; var signViewer = params.VIEWER_SIGNED; var headers = params.HEADERS || {}; if (params.METHOD === "POST" && !headers["Content-Type"]) { headers["Content-Type"] = "application/x-www-form-urlencoded"; } var paramData = { url: url, httpMethod : params.METHOD || "GET", headers: gadgets.io.encodeValues(headers, false), postData : params.POST_DATA || "", authz : auth || "", st : st || "", oauthState : reqState || "", oauthService : oauthService || "", oauthToken : oauthToken || "", contentType : params.CONTENT_TYPE || "TEXT", numEntries : params.NUM_ENTRIES || "3", getSummaries : !!params.GET_SUMMARIES, signOwner : signOwner || "true", signViewer : signViewer || "true", gadget : gadgets.util.getUrlParameters()["url"], // should we bypass gadget spec cache (e.g. to read OAuth provider URLs) bypassSpecCache : gadgets.util.getUrlParameters().nocache || "" }; if (!respondWithPreload(paramData, params, callback, processResponse)) { var refreshInterval = params.REFRESH_INTERVAL || 0; if (refreshInterval > 0) { // this content should be cached // Add paramData to the URL var extraparams = "?refresh=" + refreshInterval + '&' + gadgets.io.encodeValues(paramData); makeXhrRequest(url, config.jsonProxyUrl + extraparams, callback, null, "GET", params, processResponse); } else { makeXhrRequest(url, config.jsonProxyUrl, callback, gadgets.io.encodeValues(paramData), "POST", params, processResponse); } } }, /** * @private */ makeNonProxiedRequest : function (relativeUrl, callback, opt_params) { var params = opt_params || {}; makeXhrRequest(relativeUrl, relativeUrl, callback, params.POST_DATA, params.METHOD, params, processNonProxiedResponse); }, /** * Converts an input object into a URL-encoded data string. * (key=value&amp;...) * * @param {Object} fields The post fields you wish to encode * @param {Boolean} opt_noEscaping An optional parameter specifying whether * to turn off escaping of the parameters. Defaults to false. * @return {String} The processed post data in www-form-urlencoded format. * * @member gadgets.io */ encodeValues : function (fields, opt_noEscaping) { var escape = !opt_noEscaping; var buf = []; var first = false; for (var i in fields) if (fields.hasOwnProperty(i)) { if (!first) { first = true; } else { buf.push("&"); } buf.push(escape ? encodeURIComponent(i) : i); buf.push("="); buf.push(escape ? encodeURIComponent(fields[i]) : fields[i]); } return buf.join(""); }, /** * Gets the proxy version of the passed-in URL. * * @param {String} url The URL to get the proxy URL for * @param {Object} opt_params Optional Parameter Object. * The following properties are supported: * .REFRESH_INTERVAL The number of seconds that this * content should be cached. Defaults to 3600. * * @return {String} The proxied version of the URL * * @member gadgets.io */ getProxyUrl : function (url, opt_params) { var params = opt_params || {}; var refresh = params['REFRESH_INTERVAL'] || '3600'; return config.proxyUrl.replace("%url%", encodeURIComponent(url)). replace("%rawurl%", url). replace("%refresh%", encodeURIComponent(refresh)); } }; }(); gadgets.io.RequestParameters = gadgets.util.makeEnum([ "METHOD", "CONTENT_TYPE", "POST_DATA", "HEADERS", "AUTHORIZATION", "NUM_ENTRIES", "GET_SUMMARIES", "REFRESH_INTERVAL", "OAUTH_SERVICE", "OAUTH_TOKEN" ]); // PUT, DELETE, and HEAD not supported currently. gadgets.io.MethodType = gadgets.util.makeEnum([ "GET", "POST", "PUT", "DELETE", "HEAD" ]); gadgets.io.ContentType = gadgets.util.makeEnum([ "TEXT", "DOM", "JSON", "FEED" ]); gadgets.io.AuthorizationType = gadgets.util.makeEnum([ "NONE", "SIGNED", "AUTHENTICATED" ]);
Remove misleading comments from io.js (fixes SHINDIG-377) git-svn-id: 3f2e04d30bd9db331bbfc569b45e7de8c0d84ef0@667892 13f79535-47bb-0310-9956-ffa450edef68
features/core.io/io.js
Remove misleading comments from io.js (fixes SHINDIG-377)
<ide><path>eatures/core.io/io.js <ide> return; <ide> } <ide> var txt = xobj.responseText; <del> // remove unparseable cruft. <del> // TODO: really remove this by eliminating it. It's not any real security <del> // to begin with, and we can solve this problem by using post requests <del> // and / or passing the url in the http headers. <add> // remove unparseable cruft used to prevent cross-site script inclusion <ide> txt = txt.substr(UNPARSEABLE_CRUFT.length); <ide> // We are using eval directly here because the outer response comes from a <ide> // trusted source, and json parsing is slow in IE. <ide> "OAUTH_TOKEN" <ide> ]); <ide> <del>// PUT, DELETE, and HEAD not supported currently. <ide> gadgets.io.MethodType = gadgets.util.makeEnum([ <ide> "GET", "POST", "PUT", "DELETE", "HEAD" <ide> ]);
Java
mit
ecb5a2d23b0762d64aa896b53b00ae33eb5c968b
0
ppodgorsek/cache-invalidation,ppodgorsek/juncacher
package com.github.ppodgorsek.cache.invalidation.model.impl; import org.springframework.util.Assert; import com.github.ppodgorsek.cache.invalidation.model.InvalidationEntry; import com.github.ppodgorsek.cache.invalidation.model.InvalidationEntryType; /** * Invalidation entry that has an identifier. * * @since 1.0 * @author Paul Podgorsek */ public class IdentifiedInvalidationEntry implements InvalidationEntry { private static final long serialVersionUID = -1324699893292434964L; private InvalidationEntryType type; private String id; /** * Default constructor allowing to set the type and ID. * * @param entryType * The entry's type. * @param entryId * The entry's ID. */ public IdentifiedInvalidationEntry(final InvalidationEntryType entryType, final String entryId) { super(); Assert.notNull(entryType, "The type is required"); Assert.notNull(entryId, "The ID is required"); type = entryType; id = entryId; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof IdentifiedInvalidationEntry) { final IdentifiedInvalidationEntry entryType = (IdentifiedInvalidationEntry) obj; return type.equals(entryType.getType()) && id.equals(entryType.getId()); } return false; } @Override public int hashCode() { return (type + "#" + id).hashCode(); } @Override public String toString() { final StringBuilder sbld = new StringBuilder(getClass().getSimpleName()); sbld.append("[type=").append(type); sbld.append(",id=").append(id); sbld.append("]"); return sbld.toString(); } @Override public InvalidationEntryType getType() { return type; } public void setType(final InvalidationEntryType newType) { Assert.notNull(newType, "The type is required"); type = newType; } public String getId() { return id; } public void setId(final String newId) { Assert.notNull(newId, "The ID is required"); id = newId; } }
cache-invalidation-core/src/main/java/com/github/ppodgorsek/cache/invalidation/model/impl/IdentifiedInvalidationEntry.java
package com.github.ppodgorsek.cache.invalidation.model.impl; import org.springframework.util.Assert; import com.github.ppodgorsek.cache.invalidation.model.InvalidationEntry; import com.github.ppodgorsek.cache.invalidation.model.InvalidationEntryType; /** * Invalidation entry that has an identifier. * * @since 1.0 * @author Paul Podgorsek */ public class IdentifiedInvalidationEntry implements InvalidationEntry { private static final long serialVersionUID = -1324699893292434964L; private InvalidationEntryType type; private String id; /** * Default constructor allowing to set the type and ID. * * @param entryType * The entry's type. * @param entryId * The entry's ID. */ public IdentifiedInvalidationEntry(final InvalidationEntryType entryType, final String entryId) { super(); Assert.notNull(entryType, "The type is required"); Assert.notNull(entryId, "The ID is required"); type = entryType; id = entryId; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof IdentifiedInvalidationEntry) { final IdentifiedInvalidationEntry entryType = (IdentifiedInvalidationEntry) obj; return type.equals(entryType.getType()) && id.equals(entryType.getId()); } return false; } @Override public int hashCode() { return (type + "#" + id).hashCode(); } @Override public String toString() { final StringBuilder sbld = new StringBuilder(getClass().getSimpleName()); sbld.append("[type=").append(type); sbld.append(",id=").append(id); return sbld.toString(); } @Override public InvalidationEntryType getType() { return type; } public void setType(final InvalidationEntryType newType) { Assert.notNull(newType, "The type is required"); type = newType; } public String getId() { return id; } public void setId(final String newId) { Assert.notNull(newId, "The ID is required"); id = newId; } }
Fixed a minor mistake in a toString() method.
cache-invalidation-core/src/main/java/com/github/ppodgorsek/cache/invalidation/model/impl/IdentifiedInvalidationEntry.java
Fixed a minor mistake in a toString() method.
<ide><path>ache-invalidation-core/src/main/java/com/github/ppodgorsek/cache/invalidation/model/impl/IdentifiedInvalidationEntry.java <ide> final StringBuilder sbld = new StringBuilder(getClass().getSimpleName()); <ide> sbld.append("[type=").append(type); <ide> sbld.append(",id=").append(id); <add> sbld.append("]"); <ide> <ide> return sbld.toString(); <ide> }
Java
mit
55b8ee7fb178b445b361f21b6c7d7284e17f84b3
0
jenkinsci/proxmox-plugin,jenkinsci/proxmox-plugin
package org.jenkinsci.plugins.proxmox; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.jvnet.localizer.Localizable; import org.jvnet.localizer.ResourceBundleHolder; import hudson.Messages; import hudson.model.Executor; import hudson.model.Node; import hudson.model.Queue; import hudson.model.Slave; import hudson.slaves.OfflineCause; import hudson.slaves.SlaveComputer; public class VirtualMachineSlaveComputer extends SlaveComputer { /** * The resource bundle reference * */ private final static ResourceBundleHolder holder = ResourceBundleHolder.get(Messages.class); public VirtualMachineSlaveComputer(Slave slave) { super(slave); } @Override public void taskAccepted(Executor executor, Queue.Task task) { super.taskAccepted(executor, task); final Node node = getNode(); if (node instanceof VirtualMachineSlave) { final VirtualMachineSlave slave = (VirtualMachineSlave) node; final VirtualMachineLauncher launcher = (VirtualMachineLauncher) slave.getLauncher(); if (launcher.isLaunchSupported() && (slave.getRevertPolicy() == VirtualMachineLauncher.RevertPolicy.BEFORE_JOB)) { try { final Future<?> disconnectFuture = disconnect(OfflineCause.create(new Localizable(holder, "Disconnect before snapshot revert"))); disconnectFuture.get(); launcher.revertSnapshot(this, getListener()); launcher.launch(this, getListener()); } catch (IOException | InterruptedException e) { getListener().getLogger().println("ERROR: Snapshot revert failed: " + e.getMessage()); } catch (ExecutionException e) { getListener().getLogger().println("ERROR: Exception while performing asynchronous disconnect: " + e.getMessage()); } } } } @Override protected Future<?> _connect(boolean forceReconnect) { return super._connect(forceReconnect); } }
src/main/java/org/jenkinsci/plugins/proxmox/VirtualMachineSlaveComputer.java
package org.jenkinsci.plugins.proxmox; import java.io.IOException; import java.util.concurrent.Future; import org.jvnet.localizer.Localizable; import org.jvnet.localizer.ResourceBundleHolder; import hudson.Messages; import hudson.model.Executor; import hudson.model.Node; import hudson.model.Queue; import hudson.model.Slave; import hudson.slaves.OfflineCause; import hudson.slaves.SlaveComputer; public class VirtualMachineSlaveComputer extends SlaveComputer { /** * The resource bundle reference * */ private final static ResourceBundleHolder holder = ResourceBundleHolder.get(Messages.class); public VirtualMachineSlaveComputer(Slave slave) { super(slave); } @Override public void taskAccepted(Executor executor, Queue.Task task) { super.taskAccepted(executor, task); final Node node = getNode(); if (node instanceof VirtualMachineSlave) { final VirtualMachineSlave slave = (VirtualMachineSlave) node; final VirtualMachineLauncher launcher = (VirtualMachineLauncher) slave.getLauncher(); if (launcher.isLaunchSupported() && (slave.getRevertPolicy() == VirtualMachineLauncher.RevertPolicy.BEFORE_JOB)) { try { disconnect(OfflineCause.create(new Localizable(holder, "Disconnect before snapshot revert"))); launcher.revertSnapshot(this, getListener()); launcher.launch(this, getListener()); } catch (IOException | InterruptedException e) { getListener().getLogger().println("ERROR: Snapshot revert failed: " + e.getMessage()); } } } } @Override protected Future<?> _connect(boolean forceReconnect) { return super._connect(forceReconnect); } }
Waiting for agent disconnect before revert (#7)
src/main/java/org/jenkinsci/plugins/proxmox/VirtualMachineSlaveComputer.java
Waiting for agent disconnect before revert (#7)
<ide><path>rc/main/java/org/jenkinsci/plugins/proxmox/VirtualMachineSlaveComputer.java <ide> package org.jenkinsci.plugins.proxmox; <ide> <ide> import java.io.IOException; <add>import java.util.concurrent.ExecutionException; <ide> import java.util.concurrent.Future; <ide> <ide> import org.jvnet.localizer.Localizable; <ide> <ide> if (launcher.isLaunchSupported() && (slave.getRevertPolicy() == VirtualMachineLauncher.RevertPolicy.BEFORE_JOB)) { <ide> try { <del> disconnect(OfflineCause.create(new Localizable(holder, "Disconnect before snapshot revert"))); <add> final Future<?> disconnectFuture = disconnect(OfflineCause.create(new Localizable(holder, "Disconnect before snapshot revert"))); <add> <add> disconnectFuture.get(); <ide> launcher.revertSnapshot(this, getListener()); <ide> launcher.launch(this, getListener()); <ide> } catch (IOException | InterruptedException e) { <ide> getListener().getLogger().println("ERROR: Snapshot revert failed: " + e.getMessage()); <del> } <add> } catch (ExecutionException e) { <add> getListener().getLogger().println("ERROR: Exception while performing asynchronous disconnect: " + e.getMessage()); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
9ca9b3a8d1219b1c4b805ca3ff121be9bcf42c30
0
happlebao/pysonar2,happlebao/pysonar2,happlebao/pysonar2,lambdalab/pysonar2,lambdalab/pysonar2,lambdalab/pysonar2
package org.yinwang.pysonar.types; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.yinwang.pysonar.Analyzer; import org.yinwang.pysonar.State; import org.yinwang.pysonar.TypeStack; import org.yinwang.pysonar.ast.FunctionDef; import org.yinwang.pysonar.hash.MyHashMap; import java.util.*; public class FunType extends Type { private static final int MAX_ARROWS = 10; @NotNull public Map<Type, Type> arrows = new MyHashMap<>(); public FunctionDef func; @Nullable public ClassType cls = null; public State env; @Nullable public Type selfType; // self's type for calls public List<Type> defaultTypes; // types for default parameters (evaluated at def time) public FunType() { } public FunType(FunctionDef func, State env) { this.func = func; this.env = env; } public FunType(Type from, Type to) { addMapping(from, to); table.addSuper(Analyzer.self.builtins.BaseFunction.table); table.setPath(Analyzer.self.builtins.BaseFunction.table.path); } public void addMapping(Type from, Type to) { // if (from instanceof TupleType) { // from = simplifySelf((TupleType) from); // } if (arrows.size() < MAX_ARROWS) { arrows.put(from, to); // Map<Type, Type> oldArrows = arrows; // arrows = compressArrows(arrows); // // if (toString().length() > 900) { // arrows = oldArrows; // } } } @Nullable public Type getMapping(@NotNull Type from) { return arrows.get(from); } public boolean oversized() { return arrows.size() >= MAX_ARROWS; } public Type getReturnType() { if (!arrows.isEmpty()) { return arrows.values().iterator().next(); } else { return Type.UNKNOWN; } } public void setCls(ClassType cls) { this.cls = cls; } public void setSelfType(Type selfType) { this.selfType = selfType; } public void setDefaultTypes(List<Type> defaultTypes) { this.defaultTypes = defaultTypes; } @Override public boolean typeEquals(Object other) { if (other instanceof FunType) { FunType fo = (FunType) other; return fo.table.path.equals(table.path) || this == other; } else { return false; } } @Override public int hashCode() { return "FunType".hashCode(); } private boolean subsumed(Type type1, Type type2) { return subsumedInner(type1, type2); } private boolean subsumedInner(Type type1, Type type2) { if (typeStack.contains(type1, type2)) { return true; } if (type1.isUnknownType() || type1 == Type.NONE || type1.equals(type2)) { return true; } if (type1 instanceof TupleType && type2 instanceof TupleType) { List<Type> elems1 = ((TupleType) type1).eltTypes; List<Type> elems2 = ((TupleType) type2).eltTypes; if (elems1.size() == elems2.size()) { for (int i = 0; i < elems1.size(); i++) { if (!subsumedInner(elems1.get(i), elems2.get(i))) { return false; } } } return true; } if (type1 instanceof ListType && type2 instanceof ListType) { return subsumedInner(((ListType) type1).toTupleType(), ((ListType) type2).toTupleType()); } return false; } private Map<Type, Type> compressArrows(Map<Type, Type> arrows) { Map<Type, Type> ret = new HashMap<>(); for (Map.Entry<Type, Type> e1 : arrows.entrySet()) { boolean subsumed = false; for (Map.Entry<Type, Type> e2 : arrows.entrySet()) { if (e1 != e2 && subsumed(e1.getKey(), e2.getKey())) { subsumed = true; break; } } if (!subsumed) { ret.put(e1.getKey(), e1.getValue()); } } return ret; } // If the self type is set, use the self type in the display // This is for display purpose only, it may not be logically // correct wrt some pathological programs private TupleType simplifySelf(TupleType from) { TupleType simplified = new TupleType(); if (from.eltTypes.size() > 0) { if (cls != null) { simplified.add(cls.getCanon()); } else { simplified.add(from.get(0)); } } for (int i = 1; i < from.eltTypes.size(); i++) { simplified.add(from.get(i)); } return simplified; } @Override protected String printType(@NotNull CyclicTypeRecorder ctr) { if (arrows.isEmpty()) { return "? -> ?"; } StringBuilder sb = new StringBuilder(); Integer num = ctr.visit(this); if (num != null) { sb.append("#").append(num); } else { int newNum = ctr.push(this); int i = 0; Set<String> seen = new HashSet<>(); for (Map.Entry<Type, Type> e : arrows.entrySet()) { Type from = e.getKey(); String as = from.printType(ctr) + " -> " + e.getValue().printType(ctr); if (!seen.contains(as)) { if (i != 0) { if (Analyzer.self.multilineFunType) { sb.append("\n| "); } else { sb.append(" ∩ "); } } sb.append(as); seen.add(as); } i++; } if (ctr.isUsed(this)) { sb.append("=#").append(newNum).append(": "); } ctr.pop(this); } return sb.toString(); } }
src/main/java/org/yinwang/pysonar/types/FunType.java
package org.yinwang.pysonar.types; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.yinwang.pysonar.Analyzer; import org.yinwang.pysonar.State; import org.yinwang.pysonar.TypeStack; import org.yinwang.pysonar.ast.FunctionDef; import org.yinwang.pysonar.hash.MyHashMap; import java.util.*; public class FunType extends Type { private static final int MAX_ARROWS = 10; @NotNull public Map<Type, Type> arrows = new MyHashMap<>(); public FunctionDef func; @Nullable public ClassType cls = null; public State env; @Nullable public Type selfType; // self's type for calls public List<Type> defaultTypes; // types for default parameters (evaluated at def time) public FunType() { } public FunType(FunctionDef func, State env) { this.func = func; this.env = env; } public FunType(Type from, Type to) { addMapping(from, to); table.addSuper(Analyzer.self.builtins.BaseFunction.table); table.setPath(Analyzer.self.builtins.BaseFunction.table.path); } public void addMapping(Type from, Type to) { // if (from instanceof TupleType) { // from = simplifySelf((TupleType) from); // } if (arrows.size() < MAX_ARROWS) { arrows.put(from, to); // Map<Type, Type> oldArrows = arrows; // arrows = compressArrows(arrows); // // if (toString().length() > 900) { // arrows = oldArrows; // } } } @Nullable public Type getMapping(@NotNull Type from) { return arrows.get(from); } public boolean oversized() { return arrows.size() >= MAX_ARROWS; } public Type getReturnType() { if (!arrows.isEmpty()) { return arrows.values().iterator().next(); } else { return Type.UNKNOWN; } } public void setCls(ClassType cls) { this.cls = cls; } public void setSelfType(Type selfType) { this.selfType = selfType; } public void setDefaultTypes(List<Type> defaultTypes) { this.defaultTypes = defaultTypes; } @Override public boolean typeEquals(Object other) { if (other instanceof FunType) { FunType fo = (FunType) other; return fo.table.path.equals(table.path) || this == other; } else { return false; } } @Override public int hashCode() { return "FunType".hashCode(); } private boolean subsumed(Type type1, Type type2) { return subsumedInner(type1, type2); } private boolean subsumedInner(Type type1, Type type2) { if (typeStack.contains(type1, type2)) { return true; } if (type1.isUnknownType() || type1 == Type.NONE || type1.equals(type2)) { return true; } if (type1 instanceof TupleType && type2 instanceof TupleType) { List<Type> elems1 = ((TupleType) type1).eltTypes; List<Type> elems2 = ((TupleType) type2).eltTypes; if (elems1.size() == elems2.size()) { for (int i = 0; i < elems1.size(); i++) { if (!subsumedInner(elems1.get(i), elems2.get(i))) { return false; } } } return true; } if (type1 instanceof ListType && type2 instanceof ListType) { return subsumedInner(((ListType) type1).toTupleType(), ((ListType) type2).toTupleType()); } return false; } private Map<Type, Type> compressArrows(Map<Type, Type> arrows) { Map<Type, Type> ret = new HashMap<>(); for (Map.Entry<Type, Type> e1 : arrows.entrySet()) { boolean subsumed = false; for (Map.Entry<Type, Type> e2 : arrows.entrySet()) { if (e1 != e2 && subsumed(e1.getKey(), e2.getKey())) { subsumed = true; break; } } if (!subsumed) { ret.put(e1.getKey(), e1.getValue()); } } return ret; } // If the self type is set, use the self type in the display // This is for display purpose only, it may not be logically // correct wrt some pathological programs private TupleType simplifySelf(TupleType from) { TupleType simplified = new TupleType(); if (from.eltTypes.size() > 0) { if (cls != null) { simplified.add(cls.getCanon()); } else { simplified.add(from.get(0)); } } for (int i = 1; i < from.eltTypes.size(); i++) { simplified.add(from.get(i)); } return simplified; } @Override protected String printType(@NotNull CyclicTypeRecorder ctr) { if (arrows.isEmpty()) { return "? -> ?"; } StringBuilder sb = new StringBuilder(); Integer num = ctr.visit(this); if (num != null) { sb.append("#").append(num); } else { int newNum = ctr.push(this); int i = 0; Set<String> seen = new HashSet<>(); for (Map.Entry<Type, Type> e : arrows.entrySet()) { Type from = e.getKey(); String as = from.printType(ctr) + " -> " + e.getValue().printType(ctr); if (!seen.contains(as)) { if (i != 0) { if (Analyzer.self.multilineFunType) { sb.append("\n| "); } else { sb.append(" | "); } } sb.append(as); seen.add(as); } i++; } if (ctr.isUsed(this)) { sb.append("=#").append(newNum).append(": "); } ctr.pop(this); } return sb.toString(); } }
use unicode ∩ for intersection types
src/main/java/org/yinwang/pysonar/types/FunType.java
use unicode ∩ for intersection types
<ide><path>rc/main/java/org/yinwang/pysonar/types/FunType.java <ide> if (Analyzer.self.multilineFunType) { <ide> sb.append("\n| "); <ide> } else { <del> sb.append(" | "); <add> sb.append(" ∩ "); <ide> } <ide> } <ide>
Java
apache-2.0
b372328369f4dac82efa905c17cb5c00fd3e00ad
0
apache/uima-sandbox,apache/uima-sandbox,apache/uima-sandbox
/** * */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.uima.aae.error; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.uima.aae.error.ErrorResultTDs.TD; import org.apache.uima.aae.error.ErrorResultTDsImpl.TDImpl; public class ErrorResultBaseImpl implements ErrorResult { private static final long serialVersionUID = -964940732231472225L; private ErrorResultComponentPath resultPath = new ErrorResultComponentPathImpl(); private ErrorResultTDs resultTDs = new ErrorResultTDsImpl(); private boolean wasTerminated = false; private boolean wasDisabled = false; private Throwable rootCause; /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#addComponentKeyPath(java.lang.String) */ public void addComponentKeyPath( String aComponentKeyPath ) { addComponentKeyPath( aComponentKeyPath, false, false); } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#addComponentKeyPath(java.lang.String) */ public void addComponentKeyPath(String aComponentKeyPath, boolean terminated, boolean disabled) { resultPath.add(aComponentKeyPath, 0); wasTerminated = terminated; wasDisabled = disabled; if ( wasTerminated || wasDisabled ) { TD td = new TDImpl(aComponentKeyPath, wasTerminated, wasDisabled ); resultTDs.add(td); } } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#getComponentKeyPath() */ public ErrorResultComponentPath getComponentKeyPath() { return resultPath; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#getRootCause() */ public Throwable getRootCause() { return rootCause; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#getTDs() */ public ErrorResultTDs getTDs() { return resultTDs; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#setDisabled() */ public void setDisabled() { wasDisabled = true; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#setRootCause(java.lang.Throwable) */ public void setRootCause(Throwable aThrowable) { Throwable t = aThrowable, prev = null; while( (t = t.getCause()) != null ) { prev = t; } rootCause = ( prev == null )? aThrowable : prev; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#setTerminated() */ public void setTerminated() { wasTerminated = true; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#wasDisabled() */ public boolean wasDisabled() { return wasDisabled; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#wasTerminated() */ public boolean wasTerminated() { return wasTerminated; } public static void main( String[] args ) { ErrorResultBaseImpl errorResult = new ErrorResultBaseImpl(); errorResult.setRootCause(new AsynchAEException(new NullPointerException())); errorResult.addComponentKeyPath("InnerMostLevel"); errorResult.addComponentKeyPath("InnerLevel", true, false); errorResult.addComponentKeyPath("TopLevel"); System.out.println("Root Cause:"+errorResult.getRootCause()); ErrorResultComponentPath ercp = errorResult.getComponentKeyPath(); Iterator it = ercp.iterator(); int inx=1; while( it.hasNext()) { System.out.print((String)it.next()); System.out.println(""); for( int i=0;i<inx; i++ ) { System.out.print("\t"); } inx++; } System.out.println(""); ErrorResultTDs tds = errorResult.getTDs(); Iterator it2 = tds.iterator(); while( it2.hasNext()) { System.out.println( ((TD)it2.next()).gatPath()); } } }
uima-as/uimaj-as-core/src/main/java/org/apache/uima/aae/error/ErrorResultBaseImpl.java
/** * */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.uima.aae.error; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.uima.aae.error.ErrorResultTDs.TD; import org.apache.uima.aae.error.ErrorResultTDsImpl.TDImpl; public class ErrorResultBaseImpl implements ErrorResult { private static final long serialVersionUID = -964940732231472225L; private ErrorResultComponentPath resultPath = new ErrorResultComponentPathImpl(); private ErrorResultTDs resultTDs = new ErrorResultTDsImpl(); private boolean wasTerminated = false; private boolean wasDisabled = false; private Throwable rootCause; /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#addComponentKeyPath(java.lang.String) */ public void addComponentKeyPath( String aComponentKeyPath ) { addComponentKeyPath( aComponentKeyPath, false, false); } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#addComponentKeyPath(java.lang.String) */ public void addComponentKeyPath(String aComponentKeyPath, boolean terminated, boolean disabled) { resultPath.add(aComponentKeyPath, 0); wasTerminated = terminated; wasDisabled = disabled; if ( wasTerminated || wasDisabled ) { TD td = ((ErrorResultTDsImpl)resultTDs).new TDImpl(aComponentKeyPath, wasTerminated, wasDisabled ); resultTDs.add(td); } } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#getComponentKeyPath() */ public ErrorResultComponentPath getComponentKeyPath() { return resultPath; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#getRootCause() */ public Throwable getRootCause() { return rootCause; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#getTDs() */ public ErrorResultTDs getTDs() { return resultTDs; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#setDisabled() */ public void setDisabled() { wasDisabled = true; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#setRootCause(java.lang.Throwable) */ public void setRootCause(Throwable aThrowable) { Throwable t = aThrowable, prev = null; while( (t = t.getCause()) != null ) { prev = t; } rootCause = ( prev == null )? aThrowable : prev; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#setTerminated() */ public void setTerminated() { wasTerminated = true; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#wasDisabled() */ public boolean wasDisabled() { return wasDisabled; } /* (non-Javadoc) * @see org.apache.uima.aae.error.ErrorResult#wasTerminated() */ public boolean wasTerminated() { return wasTerminated; } public static void main( String[] args ) { ErrorResultBaseImpl errorResult = new ErrorResultBaseImpl(); errorResult.setRootCause(new AsynchAEException(new NullPointerException())); errorResult.addComponentKeyPath("InnerMostLevel"); errorResult.addComponentKeyPath("InnerLevel", true, false); errorResult.addComponentKeyPath("TopLevel"); System.out.println("Root Cause:"+errorResult.getRootCause()); ErrorResultComponentPath ercp = errorResult.getComponentKeyPath(); Iterator it = ercp.iterator(); int inx=1; while( it.hasNext()) { System.out.print((String)it.next()); System.out.println(""); for( int i=0;i<inx; i++ ) { System.out.print("\t"); } inx++; } System.out.println(""); ErrorResultTDs tds = errorResult.getTDs(); Iterator it2 = tds.iterator(); while( it2.hasNext()) { System.out.println( ((TD)it2.next()).gatPath()); } } }
UIMA-1459 Fixed how TDImpl is instantiated after making the class static git-svn-id: dd361d0afbe84f3eb97f7061549e905c2c5df34b@800903 13f79535-47bb-0310-9956-ffa450edef68
uima-as/uimaj-as-core/src/main/java/org/apache/uima/aae/error/ErrorResultBaseImpl.java
UIMA-1459 Fixed how TDImpl is instantiated after making the class static
<ide><path>ima-as/uimaj-as-core/src/main/java/org/apache/uima/aae/error/ErrorResultBaseImpl.java <ide> wasDisabled = disabled; <ide> if ( wasTerminated || wasDisabled ) <ide> { <del> TD td = ((ErrorResultTDsImpl)resultTDs).new TDImpl(aComponentKeyPath, wasTerminated, wasDisabled ); <add> TD td = new TDImpl(aComponentKeyPath, wasTerminated, wasDisabled ); <ide> resultTDs.add(td); <ide> } <ide> }
JavaScript
mit
a98608b624004e888d58cfa0407c17b2f7c36a31
0
modmore/Scheduler,modmore/Scheduler
// --------------------------- // Create window Scheduler.window.CreateRun = function(config) { config = config || {}; this.ident = config.ident || Ext.id(); Ext.applyIf(config,{ title: _('scheduler.run_create') ,cls: 'window-with-grid' ,url: Scheduler.config.connectorUrl ,baseParams: { action: 'mgr/runs/create' } ,width: 500 ,modal: true ,defaults: { border: false } ,fields: [{ xtype: 'scheduler-combo-tasklist' ,fieldLabel: _('scheduler.task') ,anchor: '100%' ,allowBlank: false },{ layout: 'column' ,border: false ,items: [{ layout: 'form' ,columnWidth: .5 ,items: [{ xtype: 'compositefield' ,fieldLabel: _('scheduler.timing.inabout') ,anchor: '100%' ,items: [{ xtype: 'numberfield' ,name: 'timing_number' ,allowBlank: false ,allowDecimals: false ,allowNegative: false ,value: 1 ,width: 60 },{ xtype: 'modx-combo' ,store: [ ['minute', _('scheduler.time.m')] ,['hour', _('scheduler.time.h')] ,['day', _('scheduler.time.d')] ,['month', _('scheduler.time.mnt')] ,['year', _('scheduler.time.y')] ] ,name: 'timing_interval' ,hiddenName: 'timing_interval' ,allowBlank: false ,value: 'minute' ,flex: 1 }] }] },{ layout: 'form' ,columnWidth: .5 ,items: [{ xtype: 'xdatetime' ,name: 'timing' ,fieldLabel: _('scheduler.timing') ,anchor: '99%' ,allowBlank: true }] }] },{ xtype: 'label' ,html: _('scheduler.timing.desc') ,cls: 'desc-under' ,style: 'padding-top: 5px;' },{ xtype: 'scheduler-grid-future-run-localdata' ,id: 'scheduler-grid-future-run-localdata-'+this.ident ,preventRender: true ,record: config.record }] }); Scheduler.window.CreateRun.superclass.constructor.call(this,config); this.on('render', this.initWindow); this.on('beforeSubmit', this.beforeSubmit); }; Ext.extend(Scheduler.window.CreateRun, MODx.Window, { initWindow: function() { var grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = this.record && this.record.data ? Ext.util.JSON.decode(this.record.data) : false, store = grid.getStore(); if (data) { Ext.iterate(data, function(k, v) { var rec = new grid.propRecord({ key: k, value: v }); store.add(rec); }); } } ,beforeSubmit: function() { var f = this.fp.getForm(), dataProperties = [], grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = grid.getStore().data; data.each(function(item) { dataProperties.push(item.data); }); dataProperties = Ext.encode(dataProperties); Ext.apply(f.baseParams, { data: dataProperties }); } }); Ext.reg('scheduler-window-run-create', Scheduler.window.CreateRun); // --------------------------- // Update window Scheduler.window.UpdateRun = function(config) { config = config || {}; this.ident = config.ident || Ext.id(); Ext.applyIf(config,{ title: _('scheduler.run_update') ,cls: 'window-with-grid' ,url: Scheduler.config.connectorUrl ,baseParams: { action: 'mgr/runs/update' } ,width: 500 ,modal: true ,defaults: { border: false } ,fields: [{ xtype: 'hidden' ,name: 'id' },{ xtype: 'scheduler-combo-tasklist' ,fieldLabel: _('scheduler.task') ,anchor: '100%' ,allowBlank: false },{ xtype: 'xdatetime' ,name: 'timing' ,fieldLabel: _('scheduler.timing') ,anchor: '99%' ,allowBlank: true },{ xtype: 'scheduler-grid-future-run-localdata' ,id: 'scheduler-grid-future-run-localdata-'+this.ident ,preventRender: true }] }); Scheduler.window.UpdateRun.superclass.constructor.call(this,config); this.on('render', this.initWindow); this.on('beforeSubmit', this.beforeSubmit); }; Ext.extend(Scheduler.window.UpdateRun, MODx.Window, { initWindow: function() { var grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = this.record && this.record.data ? Ext.util.JSON.decode(this.record.data) : false, store = grid.getStore(); if (data) { Ext.iterate(data, function(k, v) { var rec = new grid.propRecord({ key: k, value: v }); store.add(rec); }); } } ,beforeSubmit: function() { var f = this.fp.getForm(), dataProperties = [], grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = grid.getStore().data; data.each(function(item) { dataProperties.push(item.data); }); dataProperties = Ext.encode(dataProperties); Ext.apply(f.baseParams, { data: dataProperties }); } }); Ext.reg('scheduler-window-run-update', Scheduler.window.UpdateRun); // ----------------------- // Add/update data property windows Scheduler.window.RunDataPropertyCreate = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('scheduler.data.add') ,width: 450 ,saveBtnText: _('done') ,defaults: { border: false } ,fields: [{ xtype: 'textfield' ,name: 'key' ,fieldLabel: _('scheduler.data.key') ,anchor: '100%' ,allowBlank: false },{ xtype: 'textarea' ,name: 'value' ,fieldLabel: _('scheduler.data.value') ,anchor: '100%' }] }); Scheduler.window.RunDataPropertyCreate.superclass.constructor.call(this,config); }; Ext.extend(Scheduler.window.RunDataPropertyCreate, MODx.Window, { submit: function() { var v = this.fp.getForm().getValues(); var g = this.config.grid; var opt = eval(g.encode()); Ext.apply(v,{ options: opt }); if (this.fp.getForm().isValid()) { if (this.fireEvent('success',v)) { this.fp.getForm().reset(); this.hide(); return true; } } return false; } }); Ext.reg('scheduler-window-runs-adddataproperty', Scheduler.window.RunDataPropertyCreate); Scheduler.window.RunDataPropertyUpdate = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('scheduler.data.update') ,forceLayout: true }); Scheduler.window.RunDataPropertyUpdate.superclass.constructor.call(this,config); }; Ext.extend(Scheduler.window.RunDataPropertyUpdate, Scheduler.window.RunDataPropertyCreate, {}); Ext.reg('scheduler-window-runs-updatedataproperty', Scheduler.window.RunDataPropertyUpdate);
assets/components/scheduler/js/mgr/widgets/windows.future.js
// --------------------------- // Create window Scheduler.window.CreateRun = function(config) { config = config || {}; this.ident = config.ident || Ext.id(); Ext.applyIf(config,{ title: _('scheduler.run_create') ,cls: 'window-with-grid' ,url: Scheduler.config.connectorUrl ,baseParams: { action: 'mgr/runs/create' } ,width: 500 ,modal: true ,defaults: { border: false } ,fields: [{ xtype: 'scheduler-combo-tasklist' ,fieldLabel: _('scheduler.task') ,anchor: '100%' ,allowBlank: false },{ layout: 'column' ,border: false ,items: [{ layout: 'form' ,columnWidth: .5 ,items: [{ xtype: 'compositefield' ,fieldLabel: _('scheduler.timing.inabout') ,anchor: '100%' ,items: [{ xtype: 'numberfield' ,name: 'timing_number' ,allowBlank: false ,allowDecimals: false ,allowNegative: false ,value: ((config.record.timesetup) ? config.record.timesetup.number : 1) ,width: 60 },{ xtype: 'modx-combo' ,store: [ ['minute', _('scheduler.time.m')] ,['hour', _('scheduler.time.h')] ,['day', _('scheduler.time.d')] ,['month', _('scheduler.time.mnt')] ,['year', _('scheduler.time.y')] ] ,name: 'timing_interval' ,hiddenName: 'timing_interval' ,allowBlank: false ,value: ((config.record.timesetup) ? config.record.timesetup.interval : 'minute') ,flex: 1 }] }] },{ layout: 'form' ,columnWidth: .5 ,items: [{ xtype: 'xdatetime' ,name: 'timing' ,fieldLabel: _('scheduler.timing') ,anchor: '99%' ,allowBlank: true }] }] },{ xtype: 'label' ,html: _('scheduler.timing.desc') ,cls: 'desc-under' ,style: 'padding-top: 5px;' },{ xtype: 'scheduler-grid-future-run-localdata' ,id: 'scheduler-grid-future-run-localdata-'+this.ident ,preventRender: true ,record: config.record }] }); Scheduler.window.CreateRun.superclass.constructor.call(this,config); this.on('render', this.initWindow); this.on('beforeSubmit', this.beforeSubmit); }; Ext.extend(Scheduler.window.CreateRun, MODx.Window, { initWindow: function() { var grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = this.record && this.record.data ? Ext.util.JSON.decode(this.record.data) : false, store = grid.getStore(); if (data) { Ext.iterate(data, function(k, v) { var rec = new grid.propRecord({ key: k, value: v }); store.add(rec); }); } } ,beforeSubmit: function() { var f = this.fp.getForm(), dataProperties = [], grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = grid.getStore().data; data.each(function(item) { dataProperties.push(item.data); }); dataProperties = Ext.encode(dataProperties); Ext.apply(f.baseParams, { data: dataProperties }); } }); Ext.reg('scheduler-window-run-create', Scheduler.window.CreateRun); // --------------------------- // Update window Scheduler.window.UpdateRun = function(config) { config = config || {}; this.ident = config.ident || Ext.id(); Ext.applyIf(config,{ title: _('scheduler.run_update') ,cls: 'window-with-grid' ,url: Scheduler.config.connectorUrl ,baseParams: { action: 'mgr/runs/update' } ,width: 500 ,modal: true ,defaults: { border: false } ,fields: [{ xtype: 'hidden' ,name: 'id' },{ xtype: 'scheduler-combo-tasklist' ,fieldLabel: _('scheduler.task') ,anchor: '100%' ,allowBlank: false },{ xtype: 'xdatetime' ,name: 'timing' ,fieldLabel: _('scheduler.timing') ,anchor: '99%' ,allowBlank: true },{ xtype: 'scheduler-grid-future-run-localdata' ,id: 'scheduler-grid-future-run-localdata-'+this.ident ,preventRender: true }] }); Scheduler.window.UpdateRun.superclass.constructor.call(this,config); this.on('render', this.initWindow); this.on('beforeSubmit', this.beforeSubmit); }; Ext.extend(Scheduler.window.UpdateRun, MODx.Window, { initWindow: function() { var grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = this.record && this.record.data ? Ext.util.JSON.decode(this.record.data) : false, store = grid.getStore(); if (data) { Ext.iterate(data, function(k, v) { var rec = new grid.propRecord({ key: k, value: v }); store.add(rec); }); } } ,beforeSubmit: function() { var f = this.fp.getForm(), dataProperties = [], grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = grid.getStore().data; data.each(function(item) { dataProperties.push(item.data); }); dataProperties = Ext.encode(dataProperties); Ext.apply(f.baseParams, { data: dataProperties }); } }); Ext.reg('scheduler-window-run-update', Scheduler.window.UpdateRun); // ----------------------- // Add/update data property windows Scheduler.window.RunDataPropertyCreate = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('scheduler.data.add') ,width: 450 ,saveBtnText: _('done') ,defaults: { border: false } ,fields: [{ xtype: 'textfield' ,name: 'key' ,fieldLabel: _('scheduler.data.key') ,anchor: '100%' ,allowBlank: false },{ xtype: 'textarea' ,name: 'value' ,fieldLabel: _('scheduler.data.value') ,anchor: '100%' }] }); Scheduler.window.RunDataPropertyCreate.superclass.constructor.call(this,config); }; Ext.extend(Scheduler.window.RunDataPropertyCreate, MODx.Window, { submit: function() { var v = this.fp.getForm().getValues(); var g = this.config.grid; var opt = eval(g.encode()); Ext.apply(v,{ options: opt }); if (this.fp.getForm().isValid()) { if (this.fireEvent('success',v)) { this.fp.getForm().reset(); this.hide(); return true; } } return false; } }); Ext.reg('scheduler-window-runs-adddataproperty', Scheduler.window.RunDataPropertyCreate); Scheduler.window.RunDataPropertyUpdate = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('scheduler.data.update') ,forceLayout: true }); Scheduler.window.RunDataPropertyUpdate.superclass.constructor.call(this,config); }; Ext.extend(Scheduler.window.RunDataPropertyUpdate, Scheduler.window.RunDataPropertyCreate, {}); Ext.reg('scheduler-window-runs-updatedataproperty', Scheduler.window.RunDataPropertyUpdate);
Fixed values for compositefield..
assets/components/scheduler/js/mgr/widgets/windows.future.js
Fixed values for compositefield..
<ide><path>ssets/components/scheduler/js/mgr/widgets/windows.future.js <ide> ,allowBlank: false <ide> ,allowDecimals: false <ide> ,allowNegative: false <del> ,value: ((config.record.timesetup) ? config.record.timesetup.number : 1) <add> ,value: 1 <ide> ,width: 60 <ide> },{ <ide> xtype: 'modx-combo' <ide> ,name: 'timing_interval' <ide> ,hiddenName: 'timing_interval' <ide> ,allowBlank: false <del> ,value: ((config.record.timesetup) ? config.record.timesetup.interval : 'minute') <add> ,value: 'minute' <ide> ,flex: 1 <ide> }] <ide> }]
Java
apache-2.0
a535b634519fbe72739f7c0879e95bcb4e8d119a
0
helun/Ektorp,Arcticwolf/Ektorp,YannRobert/Ektorp,Arcticwolf/Ektorp,helun/Ektorp,YannRobert/Ektorp,maoueh/Ektorp,maoueh/Ektorp
package org.ektorp.http; import java.io.InputStream; import org.apache.http.HttpEntity; import org.ektorp.util.Exceptions; /** * * @author Henrik Lundgren * */ public class RestTemplate { private final HttpClient client; public RestTemplate(HttpClient client) { this.client = client; } public <T> T get(String path, ResponseCallback<T> callback) { HttpResponse hr = client.get(path); return handleResponse(callback, hr); } public <T> T getUncached(String path, ResponseCallback<T> callback) { HttpResponse hr = client.getUncached(path); return handleResponse(callback, hr); } public HttpResponse get(String path) { return handleRawResponse(client.get(path)); } public HttpResponse getUncached(String path) { return handleRawResponse(client.getUncached(path)); } public void put(String path) { handleVoidResponse(client.put(path)); } public <T> T put(String path, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path)); } public <T> T put(String path, String content, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path, content)); } public <T> T put(String path, HttpEntity httpEntity, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path, httpEntity)); } public <T> T copy(String path, String destinationUri, ResponseCallback<T> callback) { return handleResponse(callback, client.copy(path, destinationUri)); } public void put(String path, String content) { handleVoidResponse(client.put(path, content)); } public void put(String path, HttpEntity httpEntity) { handleVoidResponse(client.put(path, httpEntity)); } public void put(String path, InputStream data, String contentType, long contentLength) { handleVoidResponse(client.put(path, data, contentType, contentLength)); } public <T> T put(String path, InputStream data, String contentType, long contentLength, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path, data, contentType, contentLength)); } public <T> T post(String path, String content, ResponseCallback<T> callback) { return handleResponse(callback, client.post(path, content)); } public <T> T post(String path, HttpEntity httpEntity, ResponseCallback<T> callback) { return handleResponse(callback, client.post(path, httpEntity)); } public <T> T post(String path, InputStream content, ResponseCallback<T> callback) { return handleResponse(callback, client.post(path, content)); } public <T> T postUncached(String path, String content, ResponseCallback<T> callback) { return handleResponse(callback, client.postUncached(path, content)); } public HttpResponse post(String path, String content ) { return handleRawResponse(client.post(path,content)); } public HttpResponse postUncached(String path, String content ) { return handleRawResponse(client.postUncached(path,content)); } public <T> T delete(String path, ResponseCallback<T> callback) { return handleResponse(callback, client.delete(path)); } public void delete(String path) { handleVoidResponse(client.delete(path)); } public <T> T head(String path, ResponseCallback<T> callback) { return handleResponse(callback, client.head(path)); } private void handleVoidResponse(HttpResponse hr) { if (hr == null) return; try { if (!hr.isSuccessful()) { new StdResponseHandler<Void>().error(hr); } } finally { hr.releaseConnection(); } } private <T> T handleResponse(ResponseCallback<T> callback, HttpResponse hr) { try { return hr.isSuccessful() ? callback.success(hr) : callback.error(hr); } catch (Exception e) { throw Exceptions.propagate(e); } finally { hr.releaseConnection(); } } private HttpResponse handleRawResponse(HttpResponse hr) { try { if (!hr.isSuccessful()) { throw StdResponseHandler.createDbAccessException(hr); } return hr; } catch (Exception e) { hr.releaseConnection(); throw Exceptions.propagate(e); } } }
org.ektorp/src/main/java/org/ektorp/http/RestTemplate.java
package org.ektorp.http; import java.io.InputStream; import org.apache.http.HttpEntity; import org.ektorp.util.Exceptions; /** * * @author Henrik Lundgren * */ public class RestTemplate { private final HttpClient client; public RestTemplate(HttpClient client) { this.client = client; } public <T> T get(String path, ResponseCallback<T> callback) { HttpResponse hr = client.get(path); return handleResponse(callback, hr); } public <T> T getUncached(String path, ResponseCallback<T> callback) { HttpResponse hr = client.getUncached(path); return handleResponse(callback, hr); } public HttpResponse get(String path) { return handleRawResponse(client.get(path)); } public HttpResponse getUncached(String path) { return handleRawResponse(client.getUncached(path)); } public void put(String path) { handleVoidResponse(client.put(path)); } public <T> T put(String path, String content, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path, content)); } public <T> T put(String path, HttpEntity httpEntity, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path, httpEntity)); } public <T> T copy(String path, String destinationUri, ResponseCallback<T> callback) { return handleResponse(callback, client.copy(path, destinationUri)); } public void put(String path, String content) { handleVoidResponse(client.put(path, content)); } public void put(String path, HttpEntity httpEntity) { handleVoidResponse(client.put(path, httpEntity)); } public void put(String path, InputStream data, String contentType, long contentLength) { handleVoidResponse(client.put(path, data, contentType, contentLength)); } public <T> T put(String path, InputStream data, String contentType, long contentLength, ResponseCallback<T> callback) { return handleResponse(callback, client.put(path, data, contentType, contentLength)); } public <T> T post(String path, String content, ResponseCallback<T> callback) { return handleResponse(callback, client.post(path, content)); } public <T> T post(String path, HttpEntity httpEntity, ResponseCallback<T> callback) { return handleResponse(callback, client.post(path, httpEntity)); } public <T> T post(String path, InputStream content, ResponseCallback<T> callback) { return handleResponse(callback, client.post(path, content)); } public <T> T postUncached(String path, String content, ResponseCallback<T> callback) { return handleResponse(callback, client.postUncached(path, content)); } public HttpResponse post(String path, String content ) { return handleRawResponse(client.post(path,content)); } public HttpResponse postUncached(String path, String content ) { return handleRawResponse(client.postUncached(path,content)); } public <T> T delete(String path, ResponseCallback<T> callback) { return handleResponse(callback, client.delete(path)); } public void delete(String path) { handleVoidResponse(client.delete(path)); } public <T> T head(String path, ResponseCallback<T> callback) { return handleResponse(callback, client.head(path)); } private void handleVoidResponse(HttpResponse hr) { if (hr == null) return; try { if (!hr.isSuccessful()) { new StdResponseHandler<Void>().error(hr); } } finally { hr.releaseConnection(); } } private <T> T handleResponse(ResponseCallback<T> callback, HttpResponse hr) { try { return hr.isSuccessful() ? callback.success(hr) : callback.error(hr); } catch (Exception e) { throw Exceptions.propagate(e); } finally { hr.releaseConnection(); } } private HttpResponse handleRawResponse(HttpResponse hr) { try { if (!hr.isSuccessful()) { throw StdResponseHandler.createDbAccessException(hr); } return hr; } catch (Exception e) { hr.releaseConnection(); throw Exceptions.propagate(e); } } }
Added missing RestTemplate.put(String path, ResponseCallback<T> callback).
org.ektorp/src/main/java/org/ektorp/http/RestTemplate.java
Added missing RestTemplate.put(String path, ResponseCallback<T> callback).
<ide><path>rg.ektorp/src/main/java/org/ektorp/http/RestTemplate.java <ide> <ide> public void put(String path) { <ide> handleVoidResponse(client.put(path)); <add> } <add> <add> public <T> T put(String path, ResponseCallback<T> callback) { <add> return handleResponse(callback, client.put(path)); <ide> } <ide> <ide> public <T> T put(String path, String content, ResponseCallback<T> callback) {
Java
mit
1cda7363978544a3988b29fcab7009b89adc4f81
0
GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus
package net.glowstone.constants; import static com.google.common.base.Preconditions.checkNotNull; import static org.bukkit.Statistic.ANIMALS_BRED; import static org.bukkit.Statistic.ARMOR_CLEANED; import static org.bukkit.Statistic.AVIATE_ONE_CM; import static org.bukkit.Statistic.BANNER_CLEANED; import static org.bukkit.Statistic.BEACON_INTERACTION; import static org.bukkit.Statistic.BOAT_ONE_CM; import static org.bukkit.Statistic.BREWINGSTAND_INTERACTION; import static org.bukkit.Statistic.CAKE_SLICES_EATEN; import static org.bukkit.Statistic.CAULDRON_FILLED; import static org.bukkit.Statistic.CAULDRON_USED; import static org.bukkit.Statistic.CHEST_OPENED; import static org.bukkit.Statistic.CLIMB_ONE_CM; import static org.bukkit.Statistic.CRAFTING_TABLE_INTERACTION; import static org.bukkit.Statistic.CROUCH_ONE_CM; import static org.bukkit.Statistic.DAMAGE_DEALT; import static org.bukkit.Statistic.DAMAGE_TAKEN; import static org.bukkit.Statistic.DEATHS; import static org.bukkit.Statistic.DISPENSER_INSPECTED; import static org.bukkit.Statistic.DIVE_ONE_CM; import static org.bukkit.Statistic.DROP; import static org.bukkit.Statistic.DROPPER_INSPECTED; import static org.bukkit.Statistic.ENDERCHEST_OPENED; import static org.bukkit.Statistic.FALL_ONE_CM; import static org.bukkit.Statistic.FISH_CAUGHT; import static org.bukkit.Statistic.FLOWER_POTTED; import static org.bukkit.Statistic.FLY_ONE_CM; import static org.bukkit.Statistic.FURNACE_INTERACTION; import static org.bukkit.Statistic.HOPPER_INSPECTED; import static org.bukkit.Statistic.HORSE_ONE_CM; import static org.bukkit.Statistic.ITEM_ENCHANTED; import static org.bukkit.Statistic.JUMP; import static org.bukkit.Statistic.LEAVE_GAME; import static org.bukkit.Statistic.MINECART_ONE_CM; import static org.bukkit.Statistic.MOB_KILLS; import static org.bukkit.Statistic.NOTEBLOCK_PLAYED; import static org.bukkit.Statistic.NOTEBLOCK_TUNED; import static org.bukkit.Statistic.PIG_ONE_CM; import static org.bukkit.Statistic.PLAYER_KILLS; import static org.bukkit.Statistic.PLAY_ONE_TICK; import static org.bukkit.Statistic.RECORD_PLAYED; import static org.bukkit.Statistic.SHULKER_BOX_OPENED; import static org.bukkit.Statistic.SLEEP_IN_BED; import static org.bukkit.Statistic.SNEAK_TIME; import static org.bukkit.Statistic.SPRINT_ONE_CM; import static org.bukkit.Statistic.SWIM_ONE_CM; import static org.bukkit.Statistic.TALKED_TO_VILLAGER; import static org.bukkit.Statistic.TIME_SINCE_DEATH; import static org.bukkit.Statistic.TRADED_WITH_VILLAGER; import static org.bukkit.Statistic.TRAPPED_CHEST_TRIGGERED; import static org.bukkit.Statistic.WALK_ONE_CM; import static org.bukkit.Statistic.values; import org.bukkit.Statistic; import org.jetbrains.annotations.NonNls; /** * Name mappings for statistics. */ public final class GlowStatistic { private static final String[] names = new String[values().length]; static { set(LEAVE_GAME, "leaveGame"); set(PLAY_ONE_TICK, "playOneMinute"); // this is correct set(WALK_ONE_CM, "walkOneCm"); set(SWIM_ONE_CM, "swimOneCm"); set(FALL_ONE_CM, "fallOneCm"); set(SNEAK_TIME, "sneakTime"); set(CLIMB_ONE_CM, "climbOneCm"); set(FLY_ONE_CM, "flyOneCm"); set(DIVE_ONE_CM, "diveOneCm"); set(MINECART_ONE_CM, "minecartOneCm"); set(BOAT_ONE_CM, "boatOneCm"); set(PIG_ONE_CM, "pigOneCm"); set(HORSE_ONE_CM, "horseOneCm"); set(JUMP, "jump"); set(DROP, "drop"); set(DAMAGE_DEALT, "damageDealt"); set(DAMAGE_TAKEN, "damageTaken"); set(DEATHS, "deaths"); set(MOB_KILLS, "mobKills"); set(ANIMALS_BRED, "animalsBred"); set(PLAYER_KILLS, "playerKills"); set(FISH_CAUGHT, "fishCaught"); set(SPRINT_ONE_CM, "sprintOneCm"); set(CROUCH_ONE_CM, "crouchOneCm"); set(AVIATE_ONE_CM, "aviateOneCm"); set(TIME_SINCE_DEATH, "timeSinceDeath"); set(TALKED_TO_VILLAGER, "talkedToVillager"); set(TRADED_WITH_VILLAGER, "tradedWithVillager"); set(CAKE_SLICES_EATEN, "cakeSlices_eaten"); set(CAULDRON_FILLED, "cauldronFilled"); set(CAULDRON_USED, "cauldronUsed"); set(ARMOR_CLEANED, "armorCleaned"); set(BANNER_CLEANED, "bannerCleaned"); set(BREWINGSTAND_INTERACTION, "brewingstandInteraction"); set(BEACON_INTERACTION, "beaconInteraction"); set(DROPPER_INSPECTED, "dropperInspected"); set(HOPPER_INSPECTED, "hopperInspected"); set(DISPENSER_INSPECTED, "dispenserInspected"); set(NOTEBLOCK_PLAYED, "noteblockPlayed"); set(NOTEBLOCK_TUNED, "noteblockTuned"); set(FLOWER_POTTED, "flowerPotted"); set(TRAPPED_CHEST_TRIGGERED, "trappedChestTriggered"); set(ENDERCHEST_OPENED, "enderchestOpened"); set(ITEM_ENCHANTED, "itemEnchanted"); set(RECORD_PLAYED, "recordPlayed"); set(FURNACE_INTERACTION, "furnaceInteraction"); set(CRAFTING_TABLE_INTERACTION, "craftingTableInteraction"); set(CHEST_OPENED, "chestOpened"); set(SLEEP_IN_BED, "sleepInBed"); set(SHULKER_BOX_OPENED, "shulkerBoxOpened"); // todo: statistics with substatistics } private GlowStatistic() { } /** * Get the statistic name for a specified Statistic. * * @param stat the Statistic. * @return the statistic name. */ public static String getName(Statistic stat) { checkNotNull(stat, "Achievement cannot be null"); return names[stat.ordinal()]; } private static void set(Statistic stat, @NonNls String key) { names[stat.ordinal()] = "stat." + key; } }
src/main/java/net/glowstone/constants/GlowStatistic.java
package net.glowstone.constants; import static com.google.common.base.Preconditions.checkNotNull; import static org.bukkit.Statistic.ANIMALS_BRED; import static org.bukkit.Statistic.ARMOR_CLEANED; import static org.bukkit.Statistic.AVIATE_ONE_CM; import static org.bukkit.Statistic.BANNER_CLEANED; import static org.bukkit.Statistic.BEACON_INTERACTION; import static org.bukkit.Statistic.BOAT_ONE_CM; import static org.bukkit.Statistic.BREWINGSTAND_INTERACTION; import static org.bukkit.Statistic.CAKE_SLICES_EATEN; import static org.bukkit.Statistic.CAULDRON_FILLED; import static org.bukkit.Statistic.CAULDRON_USED; import static org.bukkit.Statistic.CHEST_OPENED; import static org.bukkit.Statistic.CLIMB_ONE_CM; import static org.bukkit.Statistic.CRAFTING_TABLE_INTERACTION; import static org.bukkit.Statistic.CROUCH_ONE_CM; import static org.bukkit.Statistic.DAMAGE_DEALT; import static org.bukkit.Statistic.DAMAGE_TAKEN; import static org.bukkit.Statistic.DEATHS; import static org.bukkit.Statistic.DISPENSER_INSPECTED; import static org.bukkit.Statistic.DIVE_ONE_CM; import static org.bukkit.Statistic.DROP; import static org.bukkit.Statistic.DROPPER_INSPECTED; import static org.bukkit.Statistic.ENDERCHEST_OPENED; import static org.bukkit.Statistic.FALL_ONE_CM; import static org.bukkit.Statistic.FISH_CAUGHT; import static org.bukkit.Statistic.FLOWER_POTTED; import static org.bukkit.Statistic.FLY_ONE_CM; import static org.bukkit.Statistic.FURNACE_INTERACTION; import static org.bukkit.Statistic.HOPPER_INSPECTED; import static org.bukkit.Statistic.HORSE_ONE_CM; import static org.bukkit.Statistic.ITEM_ENCHANTED; import static org.bukkit.Statistic.JUMP; import static org.bukkit.Statistic.LEAVE_GAME; import static org.bukkit.Statistic.MINECART_ONE_CM; import static org.bukkit.Statistic.MOB_KILLS; import static org.bukkit.Statistic.NOTEBLOCK_PLAYED; import static org.bukkit.Statistic.NOTEBLOCK_TUNED; import static org.bukkit.Statistic.PIG_ONE_CM; import static org.bukkit.Statistic.PLAYER_KILLS; import static org.bukkit.Statistic.PLAY_ONE_TICK; import static org.bukkit.Statistic.RECORD_PLAYED; import static org.bukkit.Statistic.SHULKER_BOX_OPENED; import static org.bukkit.Statistic.SLEEP_IN_BED; import static org.bukkit.Statistic.SNEAK_TIME; import static org.bukkit.Statistic.SPRINT_ONE_CM; import static org.bukkit.Statistic.SWIM_ONE_CM; import static org.bukkit.Statistic.TALKED_TO_VILLAGER; import static org.bukkit.Statistic.TIME_SINCE_DEATH; import static org.bukkit.Statistic.TRADED_WITH_VILLAGER; import static org.bukkit.Statistic.TRAPPED_CHEST_TRIGGERED; import static org.bukkit.Statistic.WALK_ONE_CM; import static org.bukkit.Statistic.values; import org.bukkit.Statistic; /** * Name mappings for statistics. */ public final class GlowStatistic { private static final String[] names = new String[values().length]; static { set(LEAVE_GAME, "leaveGame"); set(PLAY_ONE_TICK, "playOneMinute"); // this is correct set(WALK_ONE_CM, "walkOneCm"); set(SWIM_ONE_CM, "swimOneCm"); set(FALL_ONE_CM, "fallOneCm"); set(SNEAK_TIME, "sneakTime"); set(CLIMB_ONE_CM, "climbOneCm"); set(FLY_ONE_CM, "flyOneCm"); set(DIVE_ONE_CM, "diveOneCm"); set(MINECART_ONE_CM, "minecartOneCm"); set(BOAT_ONE_CM, "boatOneCm"); set(PIG_ONE_CM, "pigOneCm"); set(HORSE_ONE_CM, "horseOneCm"); set(JUMP, "jump"); set(DROP, "drop"); set(DAMAGE_DEALT, "damageDealt"); set(DAMAGE_TAKEN, "damageTaken"); set(DEATHS, "deaths"); set(MOB_KILLS, "mobKills"); set(ANIMALS_BRED, "animalsBred"); set(PLAYER_KILLS, "playerKills"); set(FISH_CAUGHT, "fishCaught"); set(SPRINT_ONE_CM, "sprintOneCm"); set(CROUCH_ONE_CM, "crouchOneCm"); set(AVIATE_ONE_CM, "aviateOneCm"); set(TIME_SINCE_DEATH, "timeSinceDeath"); set(TALKED_TO_VILLAGER, "talkedToVillager"); set(TRADED_WITH_VILLAGER, "tradedWithVillager"); set(CAKE_SLICES_EATEN, "cakeSlices_eaten"); set(CAULDRON_FILLED, "cauldronFilled"); set(CAULDRON_USED, "cauldronUsed"); set(ARMOR_CLEANED, "armorCleaned"); set(BANNER_CLEANED, "bannerCleaned"); set(BREWINGSTAND_INTERACTION, "brewingstandInteraction"); set(BEACON_INTERACTION, "beaconInteraction"); set(DROPPER_INSPECTED, "dropperInspected"); set(HOPPER_INSPECTED, "hopperInspected"); set(DISPENSER_INSPECTED, "dispenserInspected"); set(NOTEBLOCK_PLAYED, "noteblockPlayed"); set(NOTEBLOCK_TUNED, "noteblockTuned"); set(FLOWER_POTTED, "flowerPotted"); set(TRAPPED_CHEST_TRIGGERED, "trappedChestTriggered"); set(ENDERCHEST_OPENED, "enderchestOpened"); set(ITEM_ENCHANTED, "itemEnchanted"); set(RECORD_PLAYED, "recordPlayed"); set(FURNACE_INTERACTION, "furnaceInteraction"); set(CRAFTING_TABLE_INTERACTION, "craftingTableInteraction"); set(CHEST_OPENED, "chestOpened"); set(SLEEP_IN_BED, "sleepInBed"); set(SHULKER_BOX_OPENED, "shulkerBoxOpened"); // todo: statistics with substatistics } private GlowStatistic() { } /** * Get the statistic name for a specified Statistic. * * @param stat the Statistic. * @return the statistic name. */ public static String getName(Statistic stat) { checkNotNull(stat, "Achievement cannot be null"); return names[stat.ordinal()]; } private static void set(Statistic stat, String key) { names[stat.ordinal()] = "stat." + key; } }
Statistic IDs are `@NonNls`
src/main/java/net/glowstone/constants/GlowStatistic.java
Statistic IDs are `@NonNls`
<ide><path>rc/main/java/net/glowstone/constants/GlowStatistic.java <ide> import static org.bukkit.Statistic.values; <ide> <ide> import org.bukkit.Statistic; <add>import org.jetbrains.annotations.NonNls; <ide> <ide> /** <ide> * Name mappings for statistics. <ide> return names[stat.ordinal()]; <ide> } <ide> <del> private static void set(Statistic stat, String key) { <add> private static void set(Statistic stat, @NonNls String key) { <ide> names[stat.ordinal()] = "stat." + key; <ide> } <ide>
Java
apache-2.0
5e239af731445aabba61ee83e3c2832179ca81bb
0
apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.seaborne.dboe.transaction.txn; import static org.apache.jena.query.ReadWrite.WRITE ; import static org.seaborne.dboe.transaction.txn.journal.JournalEntryType.UNDO ; import java.nio.ByteBuffer ; import java.util.ArrayList ; import java.util.Iterator ; import java.util.List ; import java.util.Objects ; import java.util.concurrent.ConcurrentHashMap ; import java.util.concurrent.Semaphore ; import java.util.concurrent.atomic.AtomicLong ; import java.util.concurrent.locks.ReadWriteLock ; import java.util.concurrent.locks.ReentrantReadWriteLock ; import org.apache.jena.atlas.logging.Log ; import org.apache.jena.query.ReadWrite ; import org.seaborne.dboe.base.file.Location ; import org.seaborne.dboe.sys.SystemBase ; import org.seaborne.dboe.transaction.txn.journal.Journal ; import org.seaborne.dboe.transaction.txn.journal.JournalEntry ; import org.slf4j.Logger ; /** * One TransactionCoordinator per group of TransactionalComponents. * TransactionalComponent can not be shared across TransactionCoordinators. * <p> * This is a general engine although tested and most used for multiple-reader * and single-writer (MR+SW). TransactionalComponentLifecycle provided the * per-threadstyle. * <p> * Contrast to MRSW: multiple-reader or single-writer * * @see Transaction * @see TransactionalComponent * @see TransactionalSystem */ final public class TransactionCoordinator { private static Logger log = SystemBase.syslog ; private final Journal journal ; private boolean coordinatorStarted = false ; private final ComponentGroup components = new ComponentGroup() ; // Components private ComponentGroup txnComponents = null ; private List<ShutdownHook> shutdownHooks ; private TxnIdGenerator txnIdGenerator = TxnIdFactory.txnIdGenSimple ; private QuorumGenerator quorumGenerator = null ; //private QuorumGenerator quorumGenerator = (m) -> components ; // Semaphore to implement "Single Active Writer" - independent of readers // This is not reentrant. private Semaphore writersWaiting = new Semaphore(1, true) ; // All transaction need a "read" lock through out their lifetime. // Do not confuse with read/write transactions. We need a // "one exclusive, or many other" lock which happens to be called ReadWriteLock // See also {@code lock} which protects the datastructures during transaction management. private ReadWriteLock exclusivitylock = new ReentrantReadWriteLock() ; // Coordinator wide lock object. private Object lock = new Object() ; @FunctionalInterface public interface ShutdownHook { void shutdown() ; } /** Create a TransactionCoordinator, initially with no associated {@link TransactionalComponent}s */ public TransactionCoordinator(Location location) { this(Journal.create(location)) ; } /** Create a TransactionCoordinator, initially with no associated {@link TransactionalComponent}s */ public TransactionCoordinator(Journal journal) { this(journal, null , new ArrayList<>()) ; } /** Create a TransactionCoordinator, initially with {@link TransactionalComponent} in the ComponentGroup */ public TransactionCoordinator(Journal journal, List<TransactionalComponent> components) { this(journal, components , new ArrayList<>()) ; } // /** Create a TransactionCoordinator, initially with no associated {@link TransactionalComponent}s */ // public TransactionCoordinator(Location journalLocation) { // this(Journal.create(journalLocation), new ArrayList<>() , new ArrayList<>()) ; // } private TransactionCoordinator(Journal journal, List<TransactionalComponent> txnComp, List<ShutdownHook> shutdownHooks) { this.journal = journal ; this.shutdownHooks = new ArrayList<>(shutdownHooks) ; if ( txnComp != null ) { //txnComp.forEach(x-> System.out.println(x.getComponentId().label()+" :: "+Bytes.asHex(x.getComponentId().bytes()) ) ) ; txnComp.forEach(components::add); } } /** Add a {@link TransactionalComponent}. * Safe to call at any time but it is good practice is to add all the * compoents before any transactions start. * Internally, the coordinator ensures the add will safely happen but it * does not add the component to existing transactions. * This must be setup before recovery is attempted. */ public TransactionCoordinator add(TransactionalComponent elt) { checkSetup() ; synchronized(lock) { components.add(elt) ; } return this ; } /** * Remove a {@link TransactionalComponent}. * @see #add */ public TransactionCoordinator remove(TransactionalComponent elt) { checkSetup() ; synchronized(lock) { components.remove(elt.getComponentId()) ; } return this ; } /** * Add a shutdown hook. Shutdown is not guaranteed to be called * and hence hooks may not get called. */ public void add(TransactionCoordinator.ShutdownHook hook) { checkSetup() ; synchronized(lock) { shutdownHooks.add(hook) ; } } /** Remove a shutdown hook */ public void remove(TransactionCoordinator.ShutdownHook hook) { checkSetup() ; synchronized(lock) { shutdownHooks.remove(hook) ; } } public void setQuorumGenerator(QuorumGenerator qGen) { checkSetup() ; this.quorumGenerator = qGen ; } public void start() { checkSetup() ; recovery() ; coordinatorStarted = true ; } private /*public*/ void recovery() { Iterator<JournalEntry> iter = journal.entries() ; if ( ! iter.hasNext() ) { components.forEachComponent(c -> c.cleanStart()) ; return ; } log.info("Journal recovery start") ; components.forEachComponent(c -> c.startRecovery()) ; // Group to commit List<JournalEntry> entries = new ArrayList<>() ; iter.forEachRemaining( entry -> { switch(entry.getType()) { case ABORT : entries.clear() ; break ; case COMMIT : recover(entries) ; entries.clear() ; break ; case REDO : case UNDO : entries.add(entry) ; break ; } }) ; components.forEachComponent(c -> c.finishRecovery()) ; journal.reset() ; log.info("Journal recovery end") ; } private void recover(List<JournalEntry> entries) { entries.forEach(e -> { if ( e.getType() == UNDO ) { Log.warn(TransactionCoordinator.this, "UNDO entry : not handled") ; return ; } ComponentId cid = e.getComponentId() ; ByteBuffer bb = e.getByteBuffer() ; // find component. TransactionalComponent c = components.findComponent(cid) ; if ( c == null ) { Log.warn(TransactionCoordinator.this, "No component for "+cid) ; return ; } c.recover(bb); }) ; } public void setTxnIdGenerator(TxnIdGenerator generator) { this.txnIdGenerator = generator ; } public Journal getJournal() { return journal ; } public TransactionCoordinatorState detach(Transaction txn) { txn.detach(); TransactionCoordinatorState coordinatorState = new TransactionCoordinatorState(txn) ; components.forEach((id, c) -> { SysTransState s = c.detach() ; coordinatorState.componentStates.put(id, s) ; } ) ; // The txn still counts as "active" for tracking purposes below. return coordinatorState ; } public void attach(TransactionCoordinatorState coordinatorState) { Transaction txn = coordinatorState.transaction ; txn.attach() ; coordinatorState.componentStates.forEach((id, obj) -> { components.findComponent(id).attach(obj); }); } public void shutdown() { if ( lock == null ) return ; components.forEach((id, c) -> c.shutdown()) ; shutdownHooks.forEach((h)-> h.shutdown()) ; lock = null ; journal.close(); } // Are we in the initialization phase? private void checkSetup() { if ( coordinatorStarted ) throw new TransactionException("TransactionCoordinator has already been started") ; } // Are we up and ruuning? private void checkActive() { if ( ! coordinatorStarted ) throw new TransactionException("TransactionCoordinator has not been started") ; checkNotShutdown(); } // Check not wrapped up private void checkNotShutdown() { if ( lock == null ) throw new TransactionException("TransactionCoordinator has been shutdown") ; } private void releaseWriterLock() { int x = writersWaiting.availablePermits() ; if ( x != 0 ) throw new TransactionException("TransactionCoordinator: Probably mismatch of enable/disableWriter calls") ; writersWaiting.release() ; } private boolean acquireWriterLock(boolean canBlock) { if ( ! canBlock ) return writersWaiting.tryAcquire() ; try { writersWaiting.acquire() ; return true; } catch (InterruptedException e) { throw new TransactionException(e) ; } } /** Enter exclusive mode. * There are no active transactions on return; new transactions will be held up in 'begin'. * Return to normal (release waiting transactions, allow new transactions) * with {@link #finishExclusiveMode}. */ public void startExclusiveMode() { startExclusiveMode(true); } /** Try to enter exclusive mode. * If return is true, then are no active transactions on return and new transactions will be held up in 'begin'. * If alse, there were in-porgress transactions. * Return to normal (release waiting transactions, allow new transactions) * with {@link #finishExclusiveMode}. */ public boolean tryExclusiveMode(boolean canBlock) { return startExclusiveMode(false); } private boolean startExclusiveMode(boolean canBlock) { if ( canBlock ) { exclusivitylock.writeLock().lock() ; return true ; } return exclusivitylock.writeLock().tryLock() ; } /** Return to normal (release waiting transactions, allow new transactions). * Must be paired with an earlier {@link #startExclusiveMode}. */ public void finishExclusiveMode() { exclusivitylock.writeLock().unlock() ; } /** Execute an action in exclusive mode. This method can block. * Equivalent to: * <pre> * startExclusiveMode() ; * try { action.run(); } * finally { finishExclusiveMode(); } * </pre> * * @param action */ public void execExclusive(Runnable action) { startExclusiveMode() ; try { action.run(); } finally { finishExclusiveMode(); } } /** Block until no writers are active. * Must call {@link #enableWriters} later. * Return 'true' if the writers semaphore was grabbed, else false. * This operation must not be nested (will block). * See {@link #tryDisableWriters}. */ public void disableWriters() { acquireWriterLock(true) ; } /** Block until no writers are active or, optionally, return if can't at the moment. * Must call {@link #enableWriters} later. * Return 'true' if the writers semaphore was grabbed, else false. */ public boolean tryDisableWriters() { return acquireWriterLock(false) ; } /** Allow writers. * This must be used in conjunction with {@link #disableWriters} */ public void enableWriters() { releaseWriterLock(); } /** Execute an action in as if a Write but no write transaction started. * This method can block. * Equivalent to: * <pre> * disableWriters() ; * try { action.run(); } * finally { enableWriters(); } * </pre> * * @param action */ public void execAsWriter(Runnable action) { disableWriters() ; try { action.run(); } finally { enableWriters(); } } /** Start a transaction. This may block. */ public Transaction begin(ReadWrite readWrite) { return begin(readWrite, true) ; } /** * Start a transaction. Returns null if this operation would block. * Readers can start at any time. * A single writer policy is currently imposed so a "begin(WRITE)" * may block. */ public Transaction begin(ReadWrite readWrite, boolean canBlock) { Objects.nonNull(readWrite) ; checkActive() ; if ( canBlock ) exclusivitylock.readLock().lock() ; else { if ( ! exclusivitylock.readLock().tryLock() ) return null ; } // Readers never block. if ( readWrite == WRITE ) { // Writers take a WRITE permit from the semaphore to ensure there // is at most one active writer, else the attempt to start the // transaction blocks. // Released by in notifyCommitFinish/notifyAbortFinish boolean b = acquireWriterLock(canBlock) ; if ( !b ) { exclusivitylock.readLock().unlock() ; return null ; } } Transaction transaction = begin$(readWrite) ; startActiveTransaction(transaction) ; transaction.begin(); return transaction; } // The epoch is the serialization point for a transaction. // All readers on the same view of the data get the same serialization point. // The serialization point (epoch for short) of the active writer // is the next // This becomes the new reader // A read transaction can be promoted if writer does not start // This TransactionCoordinator provides Serializable, Read-lock-free // execution. With no item locking, a read can only be promoted // if no writer started since the reader started. private final AtomicLong writerEpoch = new AtomicLong(0) ; // The leading edge of the epochs private final AtomicLong readerEpoch = new AtomicLong(0) ; // The trailing edge of epochs private Transaction begin$(ReadWrite readWrite) { synchronized(lock) { // Thread safe part of 'begin' // Allocate the transaction serialization point. long dataVersion = ( readWrite == WRITE ) ? writerEpoch.incrementAndGet() : readerEpoch.get() ; TxnId txnId = txnIdGenerator.generate() ; List<SysTrans> sysTransList = new ArrayList<>() ; Transaction transaction = new Transaction(this, txnId, readWrite, dataVersion, sysTransList) ; ComponentGroup txnComponents = chooseComponents(this.components, readWrite) ; try { txnComponents.forEachComponent(elt -> { SysTrans sysTrans = new SysTrans(elt, transaction, txnId) ; sysTransList.add(sysTrans) ; }) ; // Calling each component must be inside the lock // so that a transaction does not commit overlapping with setup. // If it did, different components might end up starting from // different start states of the overall system. txnComponents.forEachComponent(elt -> elt.begin(transaction)) ; } catch(Throwable ex) { // Careful about incomplete. //abort() ; //complete() ; throw ex ; } return transaction ; } } private ComponentGroup chooseComponents(ComponentGroup components, ReadWrite readWrite) { if ( quorumGenerator == null ) return components ; ComponentGroup cg = quorumGenerator.genQuorum(readWrite) ; if ( cg == null ) return components ; cg.forEach((id, c) -> { TransactionalComponent tcx = components.findComponent(id) ; if ( ! tcx.equals(c) ) log.warn("TransactionalComponent not in TransactionCoordinator's ComponentGroup") ; }) ; if ( log.isDebugEnabled() ) log.debug("Custom ComponentGroup for transaction "+readWrite+": size="+cg.size()+" of "+components.size()) ; return cg ; } /** Attempt to promote a tranasaction from READ to WRITE. * No-op for a transaction already a writer. * Throws {@link TransactionException} if the promotion * can not be done. * Current policy is to not support promotion. */ // Later ... // * Current policy if a READ transaction can be promoted if intervening // * writer has started or an existing one committed. /*package*/ boolean promoteTxn(Transaction transaction) { if ( transaction.getMode() == WRITE ) return true ; // We're a reader. Try to be a writer. synchronized(lock) { // Is there a writer active? // Was there one since we started? long dataEpoch = transaction.getDataEpoch() ; long currentEpoch = writerEpoch.get() ; // Advanced as a writer starts if ( dataEpoch != currentEpoch ) return false ; // Should not block - we checked the read/write epochs // and they said "no writer" all inside 'lock' boolean b = acquireWriterLock(false) ; if ( !b ) throw new TransactionException("Promote: Inconistent: Failed to get the writer lock"); try { transaction.promoteComponents() ; } catch (TransactionException ex) { transaction.abort(); return false ; } writerEpoch.incrementAndGet() ; } return true ; } // Called by Transaction once at the end of first // commit()/abort() or end(), if no commit()/abort() // Called by Transaction after the action of commit()/abort() or end() /*package*/ void completed(Transaction transaction) { finishActiveTransaction(transaction); journal.reset() ; } /*package*/ void executePrepare(Transaction transaction) { // Do here because it needs access to the journal. notifyPrepareStart(transaction); transaction.getComponents().forEach(sysTrans -> { TransactionalComponent c = sysTrans.getComponent() ; // XXX Pass journal to TransactionalComponent.commitPrepare? ByteBuffer data = c.commitPrepare(transaction) ; if ( data != null ) { PrepareState s = new PrepareState(c.getComponentId(), data) ; journal.write(s) ; } }) ; notifyPrepareFinish(transaction); } /*package*/ void executeCommit(Transaction transaction, Runnable commit, Runnable finish) { // This is the commit point. synchronized(lock) { // *** COMMIT POINT journal.sync() ; // *** COMMIT POINT // Now run the Transactions commit actions. commit.run() ; journal.truncate(0) ; // and tell the Transaction it's finished. finish.run() ; // Bump global serialization point if necessary. if ( transaction.getMode() == WRITE ) advanceEpoch() ; notifyCommitFinish(transaction) ; } } // Inside the global transaction start/commit lock. private void advanceEpoch() { long wEpoch = writerEpoch.get() ; // The next reader will see the committed state. readerEpoch.set(wEpoch) ; } /*package*/ void executeAbort(Transaction transaction, Runnable abort) { notifyAbortStart(transaction) ; abort.run(); notifyAbortFinish(transaction) ; } // Active transactions: this is (the missing) ConcurrentHashSet private final static Object dummy = new Object() ; private ConcurrentHashMap<Transaction, Object> activeTransactions = new ConcurrentHashMap<>() ; private AtomicLong activeTransactionCount = new AtomicLong(0) ; private AtomicLong activeReadersCount = new AtomicLong(0) ; private AtomicLong activeWritersCount = new AtomicLong(0) ; private void startActiveTransaction(Transaction transaction) { synchronized(lock) { // Use lock to ensure all the counters move together. // Thread safe - we have not let the Transaction object out yet. countBegin.incrementAndGet() ; switch(transaction.getMode()) { case READ: countBeginRead.incrementAndGet() ; activeReadersCount.incrementAndGet() ; break ; case WRITE: countBeginWrite.incrementAndGet() ; activeWritersCount.incrementAndGet() ; break ; } activeTransactionCount.incrementAndGet() ; activeTransactions.put(transaction, dummy) ; } } private void finishActiveTransaction(Transaction transaction) { synchronized(lock) { // Idempotent. Object x = activeTransactions.remove(transaction) ; if ( x == null ) return ; countFinished.incrementAndGet() ; activeTransactionCount.decrementAndGet() ; switch(transaction.getMode()) { case READ: activeReadersCount.decrementAndGet() ; break ; case WRITE: activeWritersCount.decrementAndGet() ; break ; } } exclusivitylock.readLock().unlock() ; } public long countActiveReaders() { return activeReadersCount.get() ; } public long countActiveWriter() { return activeWritersCount.get() ; } public long countActive() { return activeTransactionCount.get(); } // notify*Start/Finish called round each transaction lifecycle step // Called in cooperation between Transaction and TransactionCoordinator // depending on who is actually do the work of each step. /*package*/ void notifyPrepareStart(Transaction transaction) {} /*package*/ void notifyPrepareFinish(Transaction transaction) {} // Writers released here - can happen because of commit() or abort(). private void notifyCommitStart(Transaction transaction) {} private void notifyCommitFinish(Transaction transaction) { if ( transaction.getMode() == WRITE ) releaseWriterLock(); } private void notifyAbortStart(Transaction transaction) { } private void notifyAbortFinish(Transaction transaction) { if ( transaction.getMode() == WRITE ) releaseWriterLock(); } /*package*/ void notifyEndStart(Transaction transaction) { } /*package*/ void notifyEndFinish(Transaction transaction) {} // Called by Transaction once at the end of first commit()/abort() or end() /*package*/ void notifyCompleteStart(Transaction transaction) { } /*package*/ void notifyCompleteFinish(Transaction transaction) { } // Coordinator state. private final AtomicLong countBegin = new AtomicLong(0) ; private final AtomicLong countBeginRead = new AtomicLong(0) ; private final AtomicLong countBeginWrite = new AtomicLong(0) ; private final AtomicLong countFinished = new AtomicLong(0) ; // Access counters public long countBegin() { return countBegin.get() ; } public long countBeginRead() { return countBeginRead.get() ; } public long countBeginWrite() { return countBeginWrite.get() ; } public long countFinished() { return countFinished.get() ; } }
dboe-transaction/src/main/java/org/seaborne/dboe/transaction/txn/TransactionCoordinator.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.seaborne.dboe.transaction.txn; import static org.apache.jena.query.ReadWrite.WRITE ; import static org.seaborne.dboe.transaction.txn.journal.JournalEntryType.UNDO ; import java.nio.ByteBuffer ; import java.util.ArrayList ; import java.util.Iterator ; import java.util.List ; import java.util.Objects ; import java.util.concurrent.ConcurrentHashMap ; import java.util.concurrent.Semaphore ; import java.util.concurrent.atomic.AtomicLong ; import java.util.concurrent.locks.ReadWriteLock ; import java.util.concurrent.locks.ReentrantReadWriteLock ; import org.apache.jena.atlas.logging.Log ; import org.apache.jena.query.ReadWrite ; import org.seaborne.dboe.base.file.Location ; import org.seaborne.dboe.sys.SystemBase ; import org.seaborne.dboe.transaction.txn.journal.Journal ; import org.seaborne.dboe.transaction.txn.journal.JournalEntry ; import org.slf4j.Logger ; /** * One TransactionCoordinator per group of TransactionalComponents. * TransactionalComponent can not be shared across TransactionCoordinators. * <p> * This is a general engine although tested and most used for multiple-reader * and single-writer (MR+SW). TransactionalComponentLifecycle provided the * per-threadstyle. * <p> * Contrast to MRSW: multiple-reader or single-writer * * @see Transaction * @see TransactionalComponent * @see TransactionalSystem */ final public class TransactionCoordinator { private static Logger log = SystemBase.syslog ; private final Journal journal ; private boolean coordinatorStarted = false ; private final ComponentGroup components = new ComponentGroup() ; // Components private ComponentGroup txnComponents = null ; private List<ShutdownHook> shutdownHooks ; private TxnIdGenerator txnIdGenerator = TxnIdFactory.txnIdGenSimple ; private QuorumGenerator quorumGenerator = null ; //private QuorumGenerator quorumGenerator = (m) -> components ; // Semaphore to implement "Single Active Writer" - independent of readers // This is not reentrant. private Semaphore writersWaiting = new Semaphore(1, true) ; // All transaction need a "read" lock through out their lifetime. // Do not confuse with read/write transactions. We need a // "one exclusive, or many other" lock which happens to be called ReadWriteLock // See also {@code lock} which protects the datastructures during transaction management. private ReadWriteLock exclusivitylock = new ReentrantReadWriteLock() ; // Coordinator wide lock object. private Object lock = new Object() ; @FunctionalInterface public interface ShutdownHook { void shutdown() ; } /** Create a TransactionCoordinator, initially with no associated {@link TransactionalComponent}s */ public TransactionCoordinator(Location location) { this(Journal.create(location)) ; } /** Create a TransactionCoordinator, initially with no associated {@link TransactionalComponent}s */ public TransactionCoordinator(Journal journal) { this(journal, null , new ArrayList<>()) ; } /** Create a TransactionCoordinator, initially with {@link TransactionalComponent} in the ComponentGroup */ public TransactionCoordinator(Journal journal, List<TransactionalComponent> components) { this(journal, components , new ArrayList<>()) ; } // /** Create a TransactionCoordinator, initially with no associated {@link TransactionalComponent}s */ // public TransactionCoordinator(Location journalLocation) { // this(Journal.create(journalLocation), new ArrayList<>() , new ArrayList<>()) ; // } private TransactionCoordinator(Journal journal, List<TransactionalComponent> txnComp, List<ShutdownHook> shutdownHooks) { this.journal = journal ; this.shutdownHooks = new ArrayList<>(shutdownHooks) ; if ( txnComp != null ) { //txnComp.forEach(x-> System.out.println(x.getComponentId().label()+" :: "+Bytes.asHex(x.getComponentId().bytes()) ) ) ; txnComp.forEach(components::add); } } /** Add a {@link TransactionalComponent}. * Safe to call at any time but it is good practice is to add all the * compoents before any transactions start. * Internally, the coordinator ensures the add will safely happen but it * does not add the component to existing transactions. * This must be setup before recovery is attempted. */ public TransactionCoordinator add(TransactionalComponent elt) { checkSetup() ; synchronized(lock) { components.add(elt) ; } return this ; } /** * Remove a {@link TransactionalComponent}. * @see #add */ public TransactionCoordinator remove(TransactionalComponent elt) { checkSetup() ; synchronized(lock) { components.remove(elt.getComponentId()) ; } return this ; } /** * Add a shutdown hook. Shutdown is not guaranteed to be called * and hence hooks may not get called. */ public void add(TransactionCoordinator.ShutdownHook hook) { checkSetup() ; synchronized(lock) { shutdownHooks.add(hook) ; } } /** Remove a shutdown hook */ public void remove(TransactionCoordinator.ShutdownHook hook) { checkSetup() ; synchronized(lock) { shutdownHooks.remove(hook) ; } } public void setQuorumGenerator(QuorumGenerator qGen) { checkSetup() ; this.quorumGenerator = qGen ; } public void start() { checkSetup() ; recovery() ; coordinatorStarted = true ; } private /*public*/ void recovery() { Iterator<JournalEntry> iter = journal.entries() ; if ( ! iter.hasNext() ) { components.forEachComponent(c -> c.cleanStart()) ; return ; } log.info("Journal recovery start") ; components.forEachComponent(c -> c.startRecovery()) ; // Group to commit List<JournalEntry> entries = new ArrayList<>() ; iter.forEachRemaining( entry -> { switch(entry.getType()) { case ABORT : entries.clear() ; break ; case COMMIT : recover(entries) ; entries.clear() ; break ; case REDO : case UNDO : entries.add(entry) ; break ; } }) ; components.forEachComponent(c -> c.finishRecovery()) ; journal.reset() ; log.info("Journal recovery end") ; } private void recover(List<JournalEntry> entries) { entries.forEach(e -> { if ( e.getType() == UNDO ) { Log.warn(TransactionCoordinator.this, "UNDO entry : not handled") ; return ; } ComponentId cid = e.getComponentId() ; ByteBuffer bb = e.getByteBuffer() ; // find component. TransactionalComponent c = components.findComponent(cid) ; if ( c == null ) { Log.warn(TransactionCoordinator.this, "No component for "+cid) ; return ; } c.recover(bb); }) ; } public void setTxnIdGenerator(TxnIdGenerator generator) { this.txnIdGenerator = generator ; } public Journal getJournal() { return journal ; } public TransactionCoordinatorState detach(Transaction txn) { txn.detach(); TransactionCoordinatorState coordinatorState = new TransactionCoordinatorState(txn) ; components.forEach((id, c) -> { SysTransState s = c.detach() ; coordinatorState.componentStates.put(id, s) ; } ) ; // The txn still counts as "active" for tracking purposes below. return coordinatorState ; } public void attach(TransactionCoordinatorState coordinatorState) { Transaction txn = coordinatorState.transaction ; txn.attach() ; coordinatorState.componentStates.forEach((id, obj) -> { components.findComponent(id).attach(obj); }); } public void shutdown() { if ( lock == null ) return ; components.forEach((id, c) -> c.shutdown()) ; shutdownHooks.forEach((h)-> h.shutdown()) ; lock = null ; journal.close(); } // Are we in the initialization phase? private void checkSetup() { if ( coordinatorStarted ) throw new TransactionException("TransactionCoordinator has already been started") ; } // Are we up and ruuning? private void checkActive() { if ( ! coordinatorStarted ) throw new TransactionException("TransactionCoordinator has not been started") ; checkNotShutdown(); } // Check not wrapped up private void checkNotShutdown() { if ( lock == null ) throw new TransactionException("TransactionCoordinator has been shutdown") ; } private void releaseWriterLock() { int x = writersWaiting.availablePermits() ; if ( x != 0 ) throw new TransactionException("TransactionCoordinator: Probably mismatch of enable/disableWriter calls") ; writersWaiting.release() ; } private boolean acquireWriterLock(boolean canBlock) { if ( ! canBlock ) return writersWaiting.tryAcquire() ; try { writersWaiting.acquire() ; return true; } catch (InterruptedException e) { throw new TransactionException(e) ; } } /** Enter exclusive mode. * There are no active transactions on return; new transactions will be held up in 'begin'. * Return to normal (release waiting transactions, allow new transactions) * with {@link #finishExclusiveMode}. */ public void startExclusiveMode() { startExclusiveMode(true); } /** Try to enter exclusive mode. * If return is true, then are no active transactions on return and new transactions will be held up in 'begin'. * If alse, there were in-porgress transactions. * Return to normal (release waiting transactions, allow new transactions) * with {@link #finishExclusiveMode}. */ public boolean tryExclusiveMode(boolean canBlock) { return startExclusiveMode(false); } private boolean startExclusiveMode(boolean canBlock) { if ( canBlock ) { exclusivitylock.writeLock().lock() ; return true ; } return exclusivitylock.writeLock().tryLock() ; } /** Return to normal (release waiting transactions, allow new transactions). * Must be paired with an earlier {@link #startExclusiveMode}. */ public void finishExclusiveMode() { exclusivitylock.writeLock().unlock() ; } /** Execute an action in exclusive mode. This method can block. * Equivalent to: * <pre> * beginExclusive() ; * try { action.run(); } * finally { endExclusive(); } * </pre> * * @param action */ public void execExclusive(Runnable action) { startExclusiveMode() ; try { action.run(); } finally { finishExclusiveMode(); } } /** Block until no writers are active. * Must call {@link #enableWriters} later. * Return 'true' if the writers semaphore was grabbed, else false. * This operation must not be nested (will block). * See {@link #tryDisableWriters}. */ public void disableWriters() { acquireWriterLock(true) ; } /** Block until no writers are active or, optionally, return if can't at the moment. * Must call {@link #enableWriters} later. * Return 'true' if the writers semaphore was grabbed, else false. */ public boolean tryDisableWriters() { return acquireWriterLock(false) ; } /** Allow writers. * This must be used in conjunction with {@link #disableWriters} */ public void enableWriters() { releaseWriterLock(); } /** Execute an action in as if a Write but no write transaction started. * This method can block. * Equivalent to: * <pre> * disableWriters() ; * try { action.run(); } * finally { enableWriters(); } * </pre> * * @param action */ public void execAsWriter(Runnable action) { disableWriters() ; try { action.run(); } finally { enableWriters(); } } /** Start a transaction. This may block. */ public Transaction begin(ReadWrite readWrite) { return begin(readWrite, true) ; } /** * Start a transaction. Returns null if this operation would block. * Readers can start at any time. * A single writer policy is currently imposed so a "begin(WRITE)" * may block. */ public Transaction begin(ReadWrite readWrite, boolean canBlock) { Objects.nonNull(readWrite) ; checkActive() ; if ( canBlock ) exclusivitylock.readLock().lock() ; else { if ( ! exclusivitylock.readLock().tryLock() ) return null ; } // Readers never block. if ( readWrite == WRITE ) { // Writers take a WRITE permit from the semaphore to ensure there // is at most one active writer, else the attempt to start the // transaction blocks. // Released by in notifyCommitFinish/notifyAbortFinish boolean b = acquireWriterLock(canBlock) ; if ( !b ) { exclusivitylock.readLock().unlock() ; return null ; } } Transaction transaction = begin$(readWrite) ; startActiveTransaction(transaction) ; transaction.begin(); return transaction; } // The epoch is the serialization point for a transaction. // All readers on the same view of the data get the same serialization point. // The serialization point (epoch for short) of the active writer // is the next // This becomes the new reader // A read transaction can be promoted if writer does not start // This TransactionCoordinator provides Serializable, Read-lock-free // execution. With no item locking, a read can only be promoted // if no writer started since the reader started. private final AtomicLong writerEpoch = new AtomicLong(0) ; // The leading edge of the epochs private final AtomicLong readerEpoch = new AtomicLong(0) ; // The trailing edge of epochs private Transaction begin$(ReadWrite readWrite) { synchronized(lock) { // Thread safe part of 'begin' // Allocate the transaction serialization point. long dataVersion = ( readWrite == WRITE ) ? writerEpoch.incrementAndGet() : readerEpoch.get() ; TxnId txnId = txnIdGenerator.generate() ; List<SysTrans> sysTransList = new ArrayList<>() ; Transaction transaction = new Transaction(this, txnId, readWrite, dataVersion, sysTransList) ; ComponentGroup txnComponents = chooseComponents(this.components, readWrite) ; try { txnComponents.forEachComponent(elt -> { SysTrans sysTrans = new SysTrans(elt, transaction, txnId) ; sysTransList.add(sysTrans) ; }) ; // Calling each component must be inside the lock // so that a transaction does not commit overlapping with setup. // If it did, different components might end up starting from // different start states of the overall system. txnComponents.forEachComponent(elt -> elt.begin(transaction)) ; } catch(Throwable ex) { // Careful about incomplete. //abort() ; //complete() ; throw ex ; } return transaction ; } } private ComponentGroup chooseComponents(ComponentGroup components, ReadWrite readWrite) { if ( quorumGenerator == null ) return components ; ComponentGroup cg = quorumGenerator.genQuorum(readWrite) ; if ( cg == null ) return components ; cg.forEach((id, c) -> { TransactionalComponent tcx = components.findComponent(id) ; if ( ! tcx.equals(c) ) log.warn("TransactionalComponent not in TransactionCoordinator's ComponentGroup") ; }) ; if ( log.isDebugEnabled() ) log.debug("Custom ComponentGroup for transaction "+readWrite+": size="+cg.size()+" of "+components.size()) ; return cg ; } /** Attempt to promote a tranasaction from READ to WRITE. * No-op for a transaction already a writer. * Throws {@link TransactionException} if the promotion * can not be done. * Current policy is to not support promotion. */ // Later ... // * Current policy if a READ transaction can be promoted if intervening // * writer has started or an existing one committed. /*package*/ boolean promoteTxn(Transaction transaction) { if ( transaction.getMode() == WRITE ) return true ; // We're a reader. Try to be a writer. synchronized(lock) { // Is there a writer active? // Was there one since we started? long dataEpoch = transaction.getDataEpoch() ; long currentEpoch = writerEpoch.get() ; // Advanced as a writer starts if ( dataEpoch != currentEpoch ) return false ; // Should not block - we checked the read/write epochs // and they said "no writer" all inside 'lock' boolean b = acquireWriterLock(false) ; if ( !b ) throw new TransactionException("Promote: Inconistent: Failed to get the writer lock"); try { transaction.promoteComponents() ; } catch (TransactionException ex) { transaction.abort(); return false ; } writerEpoch.incrementAndGet() ; } return true ; } // Called by Transaction once at the end of first // commit()/abort() or end(), if no commit()/abort() // Called by Transaction after the action of commit()/abort() or end() /*package*/ void completed(Transaction transaction) { finishActiveTransaction(transaction); journal.reset() ; } /*package*/ void executePrepare(Transaction transaction) { // Do here because it needs access to the journal. notifyPrepareStart(transaction); transaction.getComponents().forEach(sysTrans -> { TransactionalComponent c = sysTrans.getComponent() ; // XXX Pass journal to TransactionalComponent.commitPrepare? ByteBuffer data = c.commitPrepare(transaction) ; if ( data != null ) { PrepareState s = new PrepareState(c.getComponentId(), data) ; journal.write(s) ; } }) ; notifyPrepareFinish(transaction); } /*package*/ void executeCommit(Transaction transaction, Runnable commit, Runnable finish) { // This is the commit point. synchronized(lock) { // *** COMMIT POINT journal.sync() ; // *** COMMIT POINT // Now run the Transactions commit actions. commit.run() ; journal.truncate(0) ; // and tell the Transaction it's finished. finish.run() ; // Bump global serialization point if necessary. if ( transaction.getMode() == WRITE ) advanceEpoch() ; notifyCommitFinish(transaction) ; } } // Inside the global transaction start/commit lock. private void advanceEpoch() { long wEpoch = writerEpoch.get() ; // The next reader will see the committed state. readerEpoch.set(wEpoch) ; } /*package*/ void executeAbort(Transaction transaction, Runnable abort) { notifyAbortStart(transaction) ; abort.run(); notifyAbortFinish(transaction) ; } // Active transactions: this is (the missing) ConcurrentHashSet private final static Object dummy = new Object() ; private ConcurrentHashMap<Transaction, Object> activeTransactions = new ConcurrentHashMap<>() ; private AtomicLong activeTransactionCount = new AtomicLong(0) ; private AtomicLong activeReadersCount = new AtomicLong(0) ; private AtomicLong activeWritersCount = new AtomicLong(0) ; private void startActiveTransaction(Transaction transaction) { synchronized(lock) { // Use lock to ensure all the counters move together. // Thread safe - we have not let the Transaction object out yet. countBegin.incrementAndGet() ; switch(transaction.getMode()) { case READ: countBeginRead.incrementAndGet() ; activeReadersCount.incrementAndGet() ; break ; case WRITE: countBeginWrite.incrementAndGet() ; activeWritersCount.incrementAndGet() ; break ; } activeTransactionCount.incrementAndGet() ; activeTransactions.put(transaction, dummy) ; } } private void finishActiveTransaction(Transaction transaction) { synchronized(lock) { // Idempotent. Object x = activeTransactions.remove(transaction) ; if ( x == null ) return ; countFinished.incrementAndGet() ; activeTransactionCount.decrementAndGet() ; switch(transaction.getMode()) { case READ: activeReadersCount.decrementAndGet() ; break ; case WRITE: activeWritersCount.decrementAndGet() ; break ; } } exclusivitylock.readLock().unlock() ; } public long countActiveReaders() { return activeReadersCount.get() ; } public long countActiveWriter() { return activeWritersCount.get() ; } public long countActive() { return activeTransactionCount.get(); } // notify*Start/Finish called round each transaction lifecycle step // Called in cooperation between Transaction and TransactionCoordinator // depending on who is actually do the work of each step. /*package*/ void notifyPrepareStart(Transaction transaction) {} /*package*/ void notifyPrepareFinish(Transaction transaction) {} // Writers released here - can happen because of commit() or abort(). private void notifyCommitStart(Transaction transaction) {} private void notifyCommitFinish(Transaction transaction) { if ( transaction.getMode() == WRITE ) releaseWriterLock(); } private void notifyAbortStart(Transaction transaction) { } private void notifyAbortFinish(Transaction transaction) { if ( transaction.getMode() == WRITE ) releaseWriterLock(); } /*package*/ void notifyEndStart(Transaction transaction) { } /*package*/ void notifyEndFinish(Transaction transaction) {} // Called by Transaction once at the end of first commit()/abort() or end() /*package*/ void notifyCompleteStart(Transaction transaction) { } /*package*/ void notifyCompleteFinish(Transaction transaction) { } // Coordinator state. private final AtomicLong countBegin = new AtomicLong(0) ; private final AtomicLong countBeginRead = new AtomicLong(0) ; private final AtomicLong countBeginWrite = new AtomicLong(0) ; private final AtomicLong countFinished = new AtomicLong(0) ; // Access counters public long countBegin() { return countBegin.get() ; } public long countBeginRead() { return countBeginRead.get() ; } public long countBeginWrite() { return countBeginWrite.get() ; } public long countFinished() { return countFinished.get() ; } }
Fix comment to reflect code.
dboe-transaction/src/main/java/org/seaborne/dboe/transaction/txn/TransactionCoordinator.java
Fix comment to reflect code.
<ide><path>boe-transaction/src/main/java/org/seaborne/dboe/transaction/txn/TransactionCoordinator.java <ide> /** Execute an action in exclusive mode. This method can block. <ide> * Equivalent to: <ide> * <pre> <del> * beginExclusive() ; <add> * startExclusiveMode() ; <ide> * try { action.run(); } <del> * finally { endExclusive(); } <add> * finally { finishExclusiveMode(); } <ide> * </pre> <ide> * <ide> * @param action
Java
apache-2.0
7c8da5cec6fc81abcecb8d4bc196ed6a7a25f812
0
khartec/waltz,davidwatkins73/waltz-dev,davidwatkins73/waltz-dev,rovats/waltz,davidwatkins73/waltz-dev,kamransaleem/waltz,rovats/waltz,davidwatkins73/waltz-dev,kamransaleem/waltz,khartec/waltz,rovats/waltz,kamransaleem/waltz,kamransaleem/waltz,khartec/waltz,khartec/waltz,rovats/waltz
package com.khartec.waltz.data.change_initiative; import com.khartec.waltz.data.entity_hierarchy.AbstractIdSelectorFactory; import com.khartec.waltz.data.orgunit.OrganisationalUnitIdSelectorFactory; import com.khartec.waltz.model.EntityKind; import com.khartec.waltz.model.EntityReference; import com.khartec.waltz.model.IdSelectionOptions; import org.jooq.DSLContext; import org.jooq.Record1; import org.jooq.Select; import org.jooq.SelectConditionStep; import org.jooq.impl.DSL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import static com.khartec.waltz.common.Checks.checkNotNull; import static com.khartec.waltz.schema.tables.ChangeInitiative.CHANGE_INITIATIVE; import static com.khartec.waltz.schema.tables.EntityRelationship.ENTITY_RELATIONSHIP; import static com.khartec.waltz.schema.tables.FlowDiagramEntity.FLOW_DIAGRAM_ENTITY; import static com.khartec.waltz.schema.tables.Involvement.INVOLVEMENT; import static com.khartec.waltz.schema.tables.Person.PERSON; import static org.jooq.impl.DSL.selectDistinct; @Service public class ChangeInitiativeIdSelectorFactory extends AbstractIdSelectorFactory { private final OrganisationalUnitIdSelectorFactory organisationalUnitIdSelectorFactory; private final DSLContext dsl; @Autowired public ChangeInitiativeIdSelectorFactory(DSLContext dsl, OrganisationalUnitIdSelectorFactory organisationalUnitIdSelectorFactory) { super(dsl, EntityKind.CHANGE_INITIATIVE); checkNotNull(organisationalUnitIdSelectorFactory, "organisationalUnitIdSelectorFactory cannot be null"); this.dsl = dsl; this.organisationalUnitIdSelectorFactory = organisationalUnitIdSelectorFactory; } @Override protected Select<Record1<Long>> mkForOptions(IdSelectionOptions options) { switch (options.entityReference().kind()) { case APP_GROUP: case APPLICATION: case MEASURABLE: return mkForRef(options); case PERSON: return mkForPerson(options); case CHANGE_INITIATIVE: return mkForChangeInitiative(options); case ORG_UNIT: return mkForOrgUnit(options); case FLOW_DIAGRAM: return mkForFlowDiagram(options); default: String msg = String.format( "Cannot create Change Initiative Id selector from kind: %s", options.entityReference().kind()); throw new UnsupportedOperationException(msg); } } private Select<Record1<Long>> mkForFlowDiagram(IdSelectionOptions options) { ensureScopeIsExact(options); return dsl.selectDistinct(FLOW_DIAGRAM_ENTITY.ENTITY_ID) .from(FLOW_DIAGRAM_ENTITY) .where(FLOW_DIAGRAM_ENTITY.ENTITY_KIND.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(FLOW_DIAGRAM_ENTITY.DIAGRAM_ID.eq(options.entityReference().id())); } private Select<Record1<Long>> mkForPerson(IdSelectionOptions options) { SelectConditionStep<Record1<String>> empIdSelector = DSL .selectDistinct(PERSON.EMPLOYEE_ID) .from(PERSON) .where(PERSON.ID.eq(options.entityReference().id())); return dsl.selectDistinct(CHANGE_INITIATIVE.ID) .from(CHANGE_INITIATIVE) .innerJoin(INVOLVEMENT) .on(INVOLVEMENT.ENTITY_ID.eq(CHANGE_INITIATIVE.ID)) .where(INVOLVEMENT.ENTITY_KIND.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(INVOLVEMENT.EMPLOYEE_ID.in(empIdSelector)); } private Select<Record1<Long>> mkForOrgUnit(IdSelectionOptions options) { Select<Record1<Long>> ouSelector = organisationalUnitIdSelectorFactory.apply(options); return dsl .selectDistinct(CHANGE_INITIATIVE.ID) .from(CHANGE_INITIATIVE) .where(CHANGE_INITIATIVE.ORGANISATIONAL_UNIT_ID.in(ouSelector)); } private Select<Record1<Long>> mkForChangeInitiative(IdSelectionOptions options) { ensureScopeIsExact(options); return DSL.select(DSL.val(options.entityReference().id())); } private Select<Record1<Long>> mkForRef(IdSelectionOptions options) { EntityReference ref = options.entityReference(); Select<Record1<Long>> aToB = selectDistinct(ENTITY_RELATIONSHIP.ID_A) .from(ENTITY_RELATIONSHIP) .where(ENTITY_RELATIONSHIP.KIND_A.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(ENTITY_RELATIONSHIP.KIND_B.eq(ref.kind().name())) .and(ENTITY_RELATIONSHIP.ID_B.eq(ref.id())); Select<Record1<Long>> bToA = selectDistinct(ENTITY_RELATIONSHIP.ID_B) .from(ENTITY_RELATIONSHIP) .where(ENTITY_RELATIONSHIP.KIND_B.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(ENTITY_RELATIONSHIP.KIND_A.eq(ref.kind().name())) .and(ENTITY_RELATIONSHIP.ID_A.eq(ref.id())); return aToB.union(bToA); } }
waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java
package com.khartec.waltz.data.change_initiative; import com.khartec.waltz.data.entity_hierarchy.AbstractIdSelectorFactory; import com.khartec.waltz.data.orgunit.OrganisationalUnitIdSelectorFactory; import com.khartec.waltz.model.EntityKind; import com.khartec.waltz.model.EntityReference; import com.khartec.waltz.model.IdSelectionOptions; import com.khartec.waltz.model.application.LifecyclePhase; import org.jooq.*; import org.jooq.impl.DSL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import static com.khartec.waltz.common.Checks.checkNotNull; import static com.khartec.waltz.common.DateTimeUtilities.nowUtc; import static com.khartec.waltz.common.DateTimeUtilities.toSqlDate; import static com.khartec.waltz.schema.tables.ChangeInitiative.CHANGE_INITIATIVE; import static com.khartec.waltz.schema.tables.EntityRelationship.ENTITY_RELATIONSHIP; import static com.khartec.waltz.schema.tables.FlowDiagramEntity.FLOW_DIAGRAM_ENTITY; import static com.khartec.waltz.schema.tables.Involvement.INVOLVEMENT; import static com.khartec.waltz.schema.tables.Person.PERSON; import static org.jooq.impl.DSL.selectDistinct; @Service public class ChangeInitiativeIdSelectorFactory extends AbstractIdSelectorFactory { private final OrganisationalUnitIdSelectorFactory organisationalUnitIdSelectorFactory; private final DSLContext dsl; private final Condition liveCis = CHANGE_INITIATIVE.START_DATE.le(toSqlDate(nowUtc().toLocalDate())) .and(CHANGE_INITIATIVE.END_DATE.ge(toSqlDate(nowUtc().toLocalDate()))) .and(CHANGE_INITIATIVE.LIFECYCLE_PHASE.notEqual(LifecyclePhase.RETIRED.name())); @Autowired public ChangeInitiativeIdSelectorFactory(DSLContext dsl, OrganisationalUnitIdSelectorFactory organisationalUnitIdSelectorFactory) { super(dsl, EntityKind.CHANGE_INITIATIVE); checkNotNull(organisationalUnitIdSelectorFactory, "organisationalUnitIdSelectorFactory cannot be null"); this.dsl = dsl; this.organisationalUnitIdSelectorFactory = organisationalUnitIdSelectorFactory; } @Override protected Select<Record1<Long>> mkForOptions(IdSelectionOptions options) { switch (options.entityReference().kind()) { case APP_GROUP: case APPLICATION: case MEASURABLE: return mkForRef(options); case PERSON: return mkForPerson(options); case CHANGE_INITIATIVE: return mkForChangeInitiative(options); case ORG_UNIT: return mkForOrgUnit(options); case FLOW_DIAGRAM: return mkForFlowDiagram(options); default: String msg = String.format( "Cannot create Change Initiative Id selector from kind: %s", options.entityReference().kind()); throw new UnsupportedOperationException(msg); } } private Select<Record1<Long>> mkForFlowDiagram(IdSelectionOptions options) { ensureScopeIsExact(options); return dsl.selectDistinct(FLOW_DIAGRAM_ENTITY.ENTITY_ID) .from(FLOW_DIAGRAM_ENTITY) .innerJoin(CHANGE_INITIATIVE).on(CHANGE_INITIATIVE.ID.eq(FLOW_DIAGRAM_ENTITY.ENTITY_ID)) .where(FLOW_DIAGRAM_ENTITY.ENTITY_KIND.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(FLOW_DIAGRAM_ENTITY.DIAGRAM_ID.eq(options.entityReference().id())); } private Select<Record1<Long>> mkForPerson(IdSelectionOptions options) { SelectConditionStep<Record1<String>> empIdSelector = DSL .selectDistinct(PERSON.EMPLOYEE_ID) .from(PERSON) .where(PERSON.ID.eq(options.entityReference().id())); return dsl.selectDistinct(CHANGE_INITIATIVE.ID) .from(CHANGE_INITIATIVE) .innerJoin(INVOLVEMENT) .on(INVOLVEMENT.ENTITY_ID.eq(CHANGE_INITIATIVE.ID)) .where(INVOLVEMENT.ENTITY_KIND.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(INVOLVEMENT.EMPLOYEE_ID.in(empIdSelector)) .and(liveCis); } private Select<Record1<Long>> mkForOrgUnit(IdSelectionOptions options) { Select<Record1<Long>> ouSelector = organisationalUnitIdSelectorFactory.apply(options); return dsl .selectDistinct(CHANGE_INITIATIVE.ID) .from(CHANGE_INITIATIVE) .where(CHANGE_INITIATIVE.ORGANISATIONAL_UNIT_ID.in(ouSelector)) .and(liveCis); } private Select<Record1<Long>> mkForChangeInitiative(IdSelectionOptions options) { ensureScopeIsExact(options); return DSL.select(DSL.val(options.entityReference().id())); } private Select<Record1<Long>> mkForRef(IdSelectionOptions options) { EntityReference ref = options.entityReference(); Select<Record1<Long>> aToB = selectDistinct(ENTITY_RELATIONSHIP.ID_A) .from(ENTITY_RELATIONSHIP) .innerJoin(CHANGE_INITIATIVE).on(CHANGE_INITIATIVE.ID.eq(ENTITY_RELATIONSHIP.ID_A)) .where(ENTITY_RELATIONSHIP.KIND_A.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(ENTITY_RELATIONSHIP.KIND_B.eq(ref.kind().name())) .and(ENTITY_RELATIONSHIP.ID_B.eq(ref.id())) .and(liveCis); Select<Record1<Long>> bToA = selectDistinct(ENTITY_RELATIONSHIP.ID_B) .from(ENTITY_RELATIONSHIP) .innerJoin(CHANGE_INITIATIVE).on(CHANGE_INITIATIVE.ID.eq(ENTITY_RELATIONSHIP.ID_B)) .where(ENTITY_RELATIONSHIP.KIND_B.eq(EntityKind.CHANGE_INITIATIVE.name())) .and(ENTITY_RELATIONSHIP.KIND_A.eq(ref.kind().name())) .and(ENTITY_RELATIONSHIP.ID_A.eq(ref.id())) .and(liveCis); return aToB.union(bToA); } }
Revert CI status filter #2797
waltz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java
Revert CI status filter
<ide><path>altz-data/src/main/java/com/khartec/waltz/data/change_initiative/ChangeInitiativeIdSelectorFactory.java <ide> import com.khartec.waltz.model.EntityKind; <ide> import com.khartec.waltz.model.EntityReference; <ide> import com.khartec.waltz.model.IdSelectionOptions; <del>import com.khartec.waltz.model.application.LifecyclePhase; <del>import org.jooq.*; <add>import org.jooq.DSLContext; <add>import org.jooq.Record1; <add>import org.jooq.Select; <add>import org.jooq.SelectConditionStep; <ide> import org.jooq.impl.DSL; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.stereotype.Service; <ide> <ide> import static com.khartec.waltz.common.Checks.checkNotNull; <del>import static com.khartec.waltz.common.DateTimeUtilities.nowUtc; <del>import static com.khartec.waltz.common.DateTimeUtilities.toSqlDate; <ide> import static com.khartec.waltz.schema.tables.ChangeInitiative.CHANGE_INITIATIVE; <ide> import static com.khartec.waltz.schema.tables.EntityRelationship.ENTITY_RELATIONSHIP; <ide> import static com.khartec.waltz.schema.tables.FlowDiagramEntity.FLOW_DIAGRAM_ENTITY; <ide> <ide> private final OrganisationalUnitIdSelectorFactory organisationalUnitIdSelectorFactory; <ide> private final DSLContext dsl; <del> <del> private final Condition liveCis = CHANGE_INITIATIVE.START_DATE.le(toSqlDate(nowUtc().toLocalDate())) <del> .and(CHANGE_INITIATIVE.END_DATE.ge(toSqlDate(nowUtc().toLocalDate()))) <del> .and(CHANGE_INITIATIVE.LIFECYCLE_PHASE.notEqual(LifecyclePhase.RETIRED.name())); <ide> <ide> <ide> @Autowired <ide> ensureScopeIsExact(options); <ide> return dsl.selectDistinct(FLOW_DIAGRAM_ENTITY.ENTITY_ID) <ide> .from(FLOW_DIAGRAM_ENTITY) <del> .innerJoin(CHANGE_INITIATIVE).on(CHANGE_INITIATIVE.ID.eq(FLOW_DIAGRAM_ENTITY.ENTITY_ID)) <ide> .where(FLOW_DIAGRAM_ENTITY.ENTITY_KIND.eq(EntityKind.CHANGE_INITIATIVE.name())) <ide> .and(FLOW_DIAGRAM_ENTITY.DIAGRAM_ID.eq(options.entityReference().id())); <ide> } <ide> .innerJoin(INVOLVEMENT) <ide> .on(INVOLVEMENT.ENTITY_ID.eq(CHANGE_INITIATIVE.ID)) <ide> .where(INVOLVEMENT.ENTITY_KIND.eq(EntityKind.CHANGE_INITIATIVE.name())) <del> .and(INVOLVEMENT.EMPLOYEE_ID.in(empIdSelector)) <del> .and(liveCis); <add> .and(INVOLVEMENT.EMPLOYEE_ID.in(empIdSelector)); <ide> } <ide> <ide> <ide> return dsl <ide> .selectDistinct(CHANGE_INITIATIVE.ID) <ide> .from(CHANGE_INITIATIVE) <del> .where(CHANGE_INITIATIVE.ORGANISATIONAL_UNIT_ID.in(ouSelector)) <del> .and(liveCis); <add> .where(CHANGE_INITIATIVE.ORGANISATIONAL_UNIT_ID.in(ouSelector)); <ide> } <ide> <ide> <ide> <ide> Select<Record1<Long>> aToB = selectDistinct(ENTITY_RELATIONSHIP.ID_A) <ide> .from(ENTITY_RELATIONSHIP) <del> .innerJoin(CHANGE_INITIATIVE).on(CHANGE_INITIATIVE.ID.eq(ENTITY_RELATIONSHIP.ID_A)) <ide> .where(ENTITY_RELATIONSHIP.KIND_A.eq(EntityKind.CHANGE_INITIATIVE.name())) <ide> .and(ENTITY_RELATIONSHIP.KIND_B.eq(ref.kind().name())) <del> .and(ENTITY_RELATIONSHIP.ID_B.eq(ref.id())) <del> .and(liveCis); <add> .and(ENTITY_RELATIONSHIP.ID_B.eq(ref.id())); <ide> <ide> Select<Record1<Long>> bToA = selectDistinct(ENTITY_RELATIONSHIP.ID_B) <ide> .from(ENTITY_RELATIONSHIP) <del> .innerJoin(CHANGE_INITIATIVE).on(CHANGE_INITIATIVE.ID.eq(ENTITY_RELATIONSHIP.ID_B)) <ide> .where(ENTITY_RELATIONSHIP.KIND_B.eq(EntityKind.CHANGE_INITIATIVE.name())) <ide> .and(ENTITY_RELATIONSHIP.KIND_A.eq(ref.kind().name())) <del> .and(ENTITY_RELATIONSHIP.ID_A.eq(ref.id())) <del> .and(liveCis); <add> .and(ENTITY_RELATIONSHIP.ID_A.eq(ref.id())); <ide> <ide> return aToB.union(bToA); <ide> }
Java
apache-2.0
e5ee067b5d8c20c5826cae63c199d698dc7b0467
0
TatsianaKasiankova/pentaho-kettle,GauravAshara/pentaho-kettle,airy-ict/pentaho-kettle,jbrant/pentaho-kettle,lgrill-pentaho/pentaho-kettle,alina-ipatina/pentaho-kettle,tmcsantos/pentaho-kettle,e-cuellar/pentaho-kettle,lgrill-pentaho/pentaho-kettle,sajeetharan/pentaho-kettle,denisprotopopov/pentaho-kettle,MikhailHubanau/pentaho-kettle,mkambol/pentaho-kettle,mkambol/pentaho-kettle,sajeetharan/pentaho-kettle,emartin-pentaho/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,codek/pentaho-kettle,zlcnju/kettle,tkafalas/pentaho-kettle,bmorrise/pentaho-kettle,tmcsantos/pentaho-kettle,brosander/pentaho-kettle,EcoleKeine/pentaho-kettle,gretchiemoran/pentaho-kettle,alina-ipatina/pentaho-kettle,zlcnju/kettle,emartin-pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,mbatchelor/pentaho-kettle,wseyler/pentaho-kettle,brosander/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,denisprotopopov/pentaho-kettle,MikhailHubanau/pentaho-kettle,drndos/pentaho-kettle,GauravAshara/pentaho-kettle,cjsonger/pentaho-kettle,nantunes/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pymjer/pentaho-kettle,nanata1115/pentaho-kettle,sajeetharan/pentaho-kettle,flbrino/pentaho-kettle,GauravAshara/pentaho-kettle,pentaho/pentaho-kettle,SergeyTravin/pentaho-kettle,cjsonger/pentaho-kettle,wseyler/pentaho-kettle,ViswesvarSekar/pentaho-kettle,Advent51/pentaho-kettle,ddiroma/pentaho-kettle,SergeyTravin/pentaho-kettle,kurtwalker/pentaho-kettle,mbatchelor/pentaho-kettle,tmcsantos/pentaho-kettle,nanata1115/pentaho-kettle,mbatchelor/pentaho-kettle,kurtwalker/pentaho-kettle,wseyler/pentaho-kettle,ddiroma/pentaho-kettle,pminutillo/pentaho-kettle,nicoben/pentaho-kettle,hudak/pentaho-kettle,ivanpogodin/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,alina-ipatina/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,eayoungs/pentaho-kettle,e-cuellar/pentaho-kettle,kurtwalker/pentaho-kettle,stepanovdg/pentaho-kettle,YuryBY/pentaho-kettle,matrix-stone/pentaho-kettle,CapeSepias/pentaho-kettle,eayoungs/pentaho-kettle,HiromuHota/pentaho-kettle,codek/pentaho-kettle,mdamour1976/pentaho-kettle,yshakhau/pentaho-kettle,matrix-stone/pentaho-kettle,matthewtckr/pentaho-kettle,ma459006574/pentaho-kettle,ccaspanello/pentaho-kettle,pminutillo/pentaho-kettle,rmansoor/pentaho-kettle,ivanpogodin/pentaho-kettle,ivanpogodin/pentaho-kettle,akhayrutdinov/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,matthewtckr/pentaho-kettle,tkafalas/pentaho-kettle,nicoben/pentaho-kettle,cjsonger/pentaho-kettle,bmorrise/pentaho-kettle,YuryBY/pentaho-kettle,pedrofvteixeira/pentaho-kettle,nanata1115/pentaho-kettle,marcoslarsen/pentaho-kettle,rmansoor/pentaho-kettle,pminutillo/pentaho-kettle,drndos/pentaho-kettle,mattyb149/pentaho-kettle,codek/pentaho-kettle,dkincade/pentaho-kettle,eayoungs/pentaho-kettle,rmansoor/pentaho-kettle,stevewillcock/pentaho-kettle,mkambol/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,jbrant/pentaho-kettle,akhayrutdinov/pentaho-kettle,HiromuHota/pentaho-kettle,bmorrise/pentaho-kettle,matthewtckr/pentaho-kettle,birdtsai/pentaho-kettle,marcoslarsen/pentaho-kettle,skofra0/pentaho-kettle,stevewillcock/pentaho-kettle,matrix-stone/pentaho-kettle,emartin-pentaho/pentaho-kettle,pentaho/pentaho-kettle,lgrill-pentaho/pentaho-kettle,rmansoor/pentaho-kettle,nantunes/pentaho-kettle,e-cuellar/pentaho-kettle,pedrofvteixeira/pentaho-kettle,yshakhau/pentaho-kettle,marcoslarsen/pentaho-kettle,ma459006574/pentaho-kettle,mbatchelor/pentaho-kettle,EcoleKeine/pentaho-kettle,SergeyTravin/pentaho-kettle,pminutillo/pentaho-kettle,akhayrutdinov/pentaho-kettle,aminmkhan/pentaho-kettle,DFieldFL/pentaho-kettle,stepanovdg/pentaho-kettle,yshakhau/pentaho-kettle,stevewillcock/pentaho-kettle,flbrino/pentaho-kettle,aminmkhan/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,airy-ict/pentaho-kettle,pavel-sakun/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ddiroma/pentaho-kettle,MikhailHubanau/pentaho-kettle,graimundo/pentaho-kettle,nantunes/pentaho-kettle,EcoleKeine/pentaho-kettle,EcoleKeine/pentaho-kettle,pedrofvteixeira/pentaho-kettle,ddiroma/pentaho-kettle,ViswesvarSekar/pentaho-kettle,ma459006574/pentaho-kettle,aminmkhan/pentaho-kettle,SergeyTravin/pentaho-kettle,CapeSepias/pentaho-kettle,DFieldFL/pentaho-kettle,birdtsai/pentaho-kettle,graimundo/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,matthewtckr/pentaho-kettle,tmcsantos/pentaho-kettle,skofra0/pentaho-kettle,tkafalas/pentaho-kettle,gretchiemoran/pentaho-kettle,pavel-sakun/pentaho-kettle,hudak/pentaho-kettle,ViswesvarSekar/pentaho-kettle,bmorrise/pentaho-kettle,marcoslarsen/pentaho-kettle,roboguy/pentaho-kettle,drndos/pentaho-kettle,dkincade/pentaho-kettle,pymjer/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,tkafalas/pentaho-kettle,roboguy/pentaho-kettle,dkincade/pentaho-kettle,pentaho/pentaho-kettle,airy-ict/pentaho-kettle,flbrino/pentaho-kettle,mdamour1976/pentaho-kettle,nicoben/pentaho-kettle,pymjer/pentaho-kettle,flbrino/pentaho-kettle,zlcnju/kettle,pavel-sakun/pentaho-kettle,CapeSepias/pentaho-kettle,HiromuHota/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,akhayrutdinov/pentaho-kettle,roboguy/pentaho-kettle,graimundo/pentaho-kettle,birdtsai/pentaho-kettle,ivanpogodin/pentaho-kettle,roboguy/pentaho-kettle,denisprotopopov/pentaho-kettle,skofra0/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,wseyler/pentaho-kettle,GauravAshara/pentaho-kettle,YuryBY/pentaho-kettle,CapeSepias/pentaho-kettle,zlcnju/kettle,stevewillcock/pentaho-kettle,DFieldFL/pentaho-kettle,drndos/pentaho-kettle,jbrant/pentaho-kettle,mattyb149/pentaho-kettle,graimundo/pentaho-kettle,gretchiemoran/pentaho-kettle,aminmkhan/pentaho-kettle,nicoben/pentaho-kettle,Advent51/pentaho-kettle,DFieldFL/pentaho-kettle,pavel-sakun/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,ccaspanello/pentaho-kettle,gretchiemoran/pentaho-kettle,eayoungs/pentaho-kettle,jbrant/pentaho-kettle,ViswesvarSekar/pentaho-kettle,hudak/pentaho-kettle,nantunes/pentaho-kettle,alina-ipatina/pentaho-kettle,birdtsai/pentaho-kettle,yshakhau/pentaho-kettle,cjsonger/pentaho-kettle,nanata1115/pentaho-kettle,mattyb149/pentaho-kettle,brosander/pentaho-kettle,airy-ict/pentaho-kettle,Advent51/pentaho-kettle,mkambol/pentaho-kettle,codek/pentaho-kettle,stepanovdg/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,matrix-stone/pentaho-kettle,HiromuHota/pentaho-kettle,ccaspanello/pentaho-kettle,mdamour1976/pentaho-kettle,pymjer/pentaho-kettle,denisprotopopov/pentaho-kettle,kurtwalker/pentaho-kettle,pentaho/pentaho-kettle,YuryBY/pentaho-kettle,hudak/pentaho-kettle,emartin-pentaho/pentaho-kettle,pedrofvteixeira/pentaho-kettle,skofra0/pentaho-kettle,mdamour1976/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,ccaspanello/pentaho-kettle,Advent51/pentaho-kettle,sajeetharan/pentaho-kettle,e-cuellar/pentaho-kettle,dkincade/pentaho-kettle,brosander/pentaho-kettle,mattyb149/pentaho-kettle,ma459006574/pentaho-kettle
package org.pentaho.di.ui.spoon.partition; import org.junit.Before; import org.junit.Test; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettlePluginException; import org.pentaho.di.core.plugins.PartitionerPluginType; import org.pentaho.di.core.plugins.PluginInterface; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepPartitioningMeta; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; /** * @author [email protected] */ public class PartitionSettingsTest { public static final String PARTITION_METHOD = "ModPartitioner"; public static final String PARTITION_METHOD_DESCRIPTION = "Remainder of division"; private static final String PARTITION_METHOD_DESCRIPTION_WRONG = "Remainder of division unrecognized"; public static final String PARTITION_SCHEMA_NAME = "State"; private TransMeta transMeta; private StepMeta stepMeta; private PartitionSettings partitionSetings; private PluginRegistry plugReg; private List<PluginInterface> plugins; private int exactSize; @Before public void setUp() throws KettleException { PartitionSchema ps1 = createPartitionSchema( PARTITION_SCHEMA_NAME, Arrays.asList( "P1", "P2" ) ); PartitionSchema ps2 = createPartitionSchema( "Test", Arrays.asList( "S1", "S2", "S3" ) ); stepMeta = createStepMeta( "MemoryGroupBy" ); stepMeta.setStepPartitioningMeta( createStepParititonMeta() ); stepMeta.getStepPartitioningMeta() .setPartitionSchema( ps1 ); transMeta = createTransMeta(); transMeta.setPartitionSchemas( Arrays.asList( ps2, ps1 ) ); KettleEnvironment.init(); plugReg = PluginRegistry.getInstance(); plugins = plugReg.getPlugins( PartitionerPluginType.class ); exactSize = getExactSize( plugins ); } @Test public void PartitionSettingsConstructor() { int actualMethodCodesLength = StepPartitioningMeta.methodCodes.length; int actualMethodDescriptionLength = StepPartitioningMeta.methodDescriptions.length; partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); String[] codes = partitionSetings.getCodes(); String[] options = partitionSetings.getOptions(); assertThat( codes.length, equalTo( actualMethodCodesLength + plugins.size() ) ); assertThat( options.length, equalTo( actualMethodDescriptionLength + plugins.size() ) ); for ( int i = 0; i < actualMethodCodesLength; i++ ) { assertThat( codes[ i ], equalTo( StepPartitioningMeta.methodCodes[ i ] ) ); } for ( int i = 0; i < actualMethodDescriptionLength; i++ ) { assertThat( options[ i ], equalTo( StepPartitioningMeta.methodDescriptions[ i ] ) ); } } @Test public void fillOptionsAndCodesByPlugins() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); List<String> codes = Arrays.asList( partitionSetings.getCodes() ); List<String> options = Arrays.asList( partitionSetings.getOptions() ); for ( PluginInterface plugin : plugins ) { for ( String id : plugin.getIds() ) { assertThat( codes.contains( id ), equalTo( true ) ); } } for ( PluginInterface plugin : plugins ) { assertThat( options.contains( plugin.getDescription() ), equalTo( true ) ); } } @Test public void getDefaultSelectedMethodIndex() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); int defaultSelectedMethod = partitionSetings.getDefaultSelectedMethodIndex(); int actualIndex = Arrays.asList( partitionSetings.getCodes() ).indexOf( stepMeta.getStepPartitioningMeta().getMethod() ); assertThat( actualIndex, equalTo( defaultSelectedMethod ) ); } @Test public void getDefaultSelectedSchemaIndex() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); int defaultSelectedSchema = partitionSetings.getDefaultSelectedSchemaIndex(); assertThat( 1, equalTo( defaultSelectedSchema ) ); } @Test public void getDefaultSelectedSchemaIndexNoAppropriateSchema() { stepMeta.getStepPartitioningMeta() .setPartitionSchema( createPartitionSchema( "State1", Arrays.asList( "P1", "P2" ) ) ); partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); int defaultSelectedSchema = partitionSetings.getDefaultSelectedSchemaIndex(); assertThat( 0, equalTo( defaultSelectedSchema ) ); } @Test public void getMethodByMethodDescription() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); String method = partitionSetings.getMethodByMethodDescription( PARTITION_METHOD_DESCRIPTION ); assertThat( PARTITION_METHOD, equalTo( method ) ); } @Test public void getMethodByMethodDescriptionUnrecognizedDescription() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); String method = partitionSetings.getMethodByMethodDescription( PARTITION_METHOD_DESCRIPTION_WRONG ); assertThat( StepPartitioningMeta.methodCodes[ StepPartitioningMeta.PARTITIONING_METHOD_NONE ], equalTo( method ) ); } @Test public void updateSchema(){ PartitionSchema sc = createPartitionSchema( "AnotherState", Arrays.asList( "ID_1", "ID_2" ) ); partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.updateSchema( sc ); assertThat( stepMeta.getStepPartitioningMeta().getPartitionSchema(), equalTo( sc ) ); } @Test public void updateSchemaNullSchemaName(){ PartitionSchema sc = createPartitionSchema( null, new ArrayList<String>( ) ); partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.updateSchema( sc ); assertThat( stepMeta.getStepPartitioningMeta().getPartitionSchema().getName(), equalTo(PARTITION_SCHEMA_NAME)); } @Test public void updateSchemaEmptySchemaName(){ PartitionSchema sc = createPartitionSchema( "", Arrays.asList( "ID_1", "ID_2" ) ); partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.updateSchema( sc ); assertThat( stepMeta.getStepPartitioningMeta().getPartitionSchema(), equalTo( sc ) ); } private TransMeta createTransMeta() { TransMeta transMeta = new TransMeta(); return transMeta; } private StepMeta createStepMeta( String stepId ) throws KettlePluginException { StepMeta stepMeta = new StepMeta(); stepMeta.setStepID( stepId ); return stepMeta; } private StepPartitioningMeta createStepParititonMeta() throws KettlePluginException { StepPartitioningMeta stepPartitionMeta = new StepPartitioningMeta(); stepPartitionMeta.setMethodType( 2 ); stepPartitionMeta.setMethod( PARTITION_METHOD ); return stepPartitionMeta; } private PartitionSchema createPartitionSchema( String name, List<String> partitionIDs ) { return new PartitionSchema( name, partitionIDs ); } private int getExactSize( List<PluginInterface> plugins ) { return StepPartitioningMeta.methodDescriptions.length + plugins.size(); } }
ui/test-src/org/pentaho/di/ui/spoon/partition/PartitionSettingsTest.java
package org.pentaho.di.ui.spoon.partition; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettlePluginException; import org.pentaho.di.core.plugins.PartitionerPluginType; import org.pentaho.di.core.plugins.Plugin; import org.pentaho.di.core.plugins.PluginInterface; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.trans.Partitioner; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepPartitioningMeta; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; /** * @author [email protected] */ public class PartitionSettingsTest { public static final String PARTITION_METHOD = "ModPartitioner"; public static final String PARTITION_METHOD_DESCRIPTION = "Remainder of division"; private static final String PARTITION_METHOD_DESCRIPTION_WRONG = "Remainder of division unrecognized"; private TransMeta transMeta; private StepMeta stepMeta; private PartitionSettings partitionSetings; private PluginRegistry plugReg; private List<PluginInterface> plugins; private int exactSize; @Before public void setUp() throws KettleException { stepMeta = createStepMeta( "MemoryGroupBy" ); stepMeta.setStepPartitioningMeta( createStepParititonMeta() ); stepMeta.getStepPartitioningMeta() .setPartitionSchema( createPartitionSchema( "State", Arrays.asList( "P1", "P2" ) ) ); transMeta = createTransMeta(); PartitionSchema ps1 = createPartitionSchema( "State", Arrays.asList( "P1", "P2" ) ); PartitionSchema ps2 = createPartitionSchema( "Test", Arrays.asList( "S1", "S2", "S3" ) ); transMeta.setPartitionSchemas( Arrays.asList( ps2, ps1 ) ); KettleEnvironment.init(); plugReg = PluginRegistry.getInstance(); plugins = plugReg.getPlugins( PartitionerPluginType.class ); exactSize = getExactSize( plugins ); } @Test public void PartitionSettingsConstructor() { int actualMethodCodesLength = StepPartitioningMeta.methodCodes.length; int actualMethodDescriptionLength = StepPartitioningMeta.methodDescriptions.length; partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); String[] codes = partitionSetings.getCodes(); String[] options = partitionSetings.getOptions(); assertThat( codes.length, equalTo( actualMethodCodesLength + plugins.size() ) ); assertThat( options.length, equalTo( actualMethodDescriptionLength + plugins.size() ) ); for ( int i = 0; i < actualMethodCodesLength; i++ ) { assertThat( codes[ i ], equalTo( StepPartitioningMeta.methodCodes[ i ] ) ); } for ( int i = 0; i < actualMethodDescriptionLength; i++ ) { assertThat( options[ i ], equalTo( StepPartitioningMeta.methodDescriptions[ i ] ) ); } } @Test public void fillOptionsAndCodesByPlugins() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); List<String> codes = Arrays.asList( partitionSetings.getCodes() ); List<String> options = Arrays.asList( partitionSetings.getOptions() ); for ( PluginInterface plugin : plugins ) { for ( String id : plugin.getIds() ) { assertThat( codes.contains( id ), equalTo( true ) ); } } for ( PluginInterface plugin : plugins ) { assertThat( options.contains( plugin.getDescription() ), equalTo( true ) ); } } @Test public void getDefaultSelectedMethodIndex() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); int defaultSelectedMethod = partitionSetings.getDefaultSelectedMethodIndex(); int actualIndex = Arrays.asList( partitionSetings.getCodes() ).indexOf( stepMeta.getStepPartitioningMeta().getMethod() ); assertThat( actualIndex, equalTo( defaultSelectedMethod ) ); } @Test public void getDefaultSelectedSchemaIndex() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); int defaultSelectedSchema = partitionSetings.getDefaultSelectedSchemaIndex(); assertThat( 1, equalTo( defaultSelectedSchema ) ); } @Test public void getDefaultSelectedSchemaIndexNoAppropriateSchema() { stepMeta.getStepPartitioningMeta() .setPartitionSchema( createPartitionSchema( "State1", Arrays.asList( "P1", "P2" ) ) ); partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); int defaultSelectedSchema = partitionSetings.getDefaultSelectedSchemaIndex(); assertThat( 0, equalTo( defaultSelectedSchema ) ); } @Test public void getMethodByMethodDescription() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); String method = partitionSetings.getMethodByMethodDescription( PARTITION_METHOD_DESCRIPTION ); assertThat( PARTITION_METHOD, equalTo( method ) ); } @Test public void getMethodByMethodDescriptionUnrecognizedDescription() { partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); partitionSetings.fillOptionsAndCodesByPlugins( plugins ); String method = partitionSetings.getMethodByMethodDescription( PARTITION_METHOD_DESCRIPTION_WRONG ); assertThat( StepPartitioningMeta.methodCodes[ StepPartitioningMeta.PARTITIONING_METHOD_NONE ], equalTo( method ) ); } private TransMeta createTransMeta() { TransMeta transMeta = new TransMeta(); return transMeta; } private StepMeta createStepMeta( String stepId ) throws KettlePluginException { StepMeta stepMeta = new StepMeta(); stepMeta.setStepID( stepId ); return stepMeta; } private StepPartitioningMeta createStepParititonMeta() throws KettlePluginException { StepPartitioningMeta stepPartitionMeta = new StepPartitioningMeta(); stepPartitionMeta.setMethodType( 2 ); stepPartitionMeta.setMethod( PARTITION_METHOD ); return stepPartitionMeta; } private Partitioner ctreatePatitioner() { return null; } private PartitionSchema createPartitionSchema( String name, List<String> partitionIDs ) { return new PartitionSchema( name, partitionIDs ); } private int getExactSize( List<PluginInterface> plugins ) { return StepPartitioningMeta.methodDescriptions.length + plugins.size(); } }
[BACKLOG-604] CLONE - Should not be able to create a partition on a step without a field
ui/test-src/org/pentaho/di/ui/spoon/partition/PartitionSettingsTest.java
[BACKLOG-604] CLONE - Should not be able to create a partition on a step without a field
<ide><path>i/test-src/org/pentaho/di/ui/spoon/partition/PartitionSettingsTest.java <ide> package org.pentaho.di.ui.spoon.partition; <ide> <del>import org.hamcrest.CoreMatchers; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.pentaho.di.core.KettleEnvironment; <ide> import org.pentaho.di.core.exception.KettleException; <ide> import org.pentaho.di.core.exception.KettlePluginException; <ide> import org.pentaho.di.core.plugins.PartitionerPluginType; <del>import org.pentaho.di.core.plugins.Plugin; <ide> import org.pentaho.di.core.plugins.PluginInterface; <ide> import org.pentaho.di.core.plugins.PluginRegistry; <ide> import org.pentaho.di.partition.PartitionSchema; <del>import org.pentaho.di.trans.Partitioner; <ide> import org.pentaho.di.trans.TransMeta; <ide> import org.pentaho.di.trans.step.StepMeta; <ide> import org.pentaho.di.trans.step.StepPartitioningMeta; <ide> <add>import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <ide> public static final String PARTITION_METHOD = "ModPartitioner"; <ide> public static final String PARTITION_METHOD_DESCRIPTION = "Remainder of division"; <ide> private static final String PARTITION_METHOD_DESCRIPTION_WRONG = "Remainder of division unrecognized"; <add> public static final String PARTITION_SCHEMA_NAME = "State"; <ide> private TransMeta transMeta; <ide> private StepMeta stepMeta; <ide> private PartitionSettings partitionSetings; <ide> <ide> @Before <ide> public void setUp() throws KettleException { <add> PartitionSchema ps1 = createPartitionSchema( PARTITION_SCHEMA_NAME, Arrays.asList( "P1", "P2" ) ); <add> PartitionSchema ps2 = createPartitionSchema( "Test", Arrays.asList( "S1", "S2", "S3" ) ); <add> <ide> stepMeta = createStepMeta( "MemoryGroupBy" ); <ide> stepMeta.setStepPartitioningMeta( createStepParititonMeta() ); <ide> stepMeta.getStepPartitioningMeta() <del> .setPartitionSchema( createPartitionSchema( "State", Arrays.asList( "P1", "P2" ) ) ); <add> .setPartitionSchema( ps1 ); <ide> <ide> transMeta = createTransMeta(); <del> PartitionSchema ps1 = createPartitionSchema( "State", Arrays.asList( "P1", "P2" ) ); <del> PartitionSchema ps2 = createPartitionSchema( "Test", Arrays.asList( "S1", "S2", "S3" ) ); <ide> transMeta.setPartitionSchemas( Arrays.asList( ps2, ps1 ) ); <ide> <ide> KettleEnvironment.init(); <ide> assertThat( StepPartitioningMeta.methodCodes[ StepPartitioningMeta.PARTITIONING_METHOD_NONE ], equalTo( method ) ); <ide> } <ide> <add> @Test <add> public void updateSchema(){ <add> PartitionSchema sc = createPartitionSchema( "AnotherState", Arrays.asList( "ID_1", "ID_2" ) ); <add> partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); <add> partitionSetings.updateSchema( sc ); <add> assertThat( stepMeta.getStepPartitioningMeta().getPartitionSchema(), equalTo( sc ) ); <add> } <add> <add> @Test <add> public void updateSchemaNullSchemaName(){ <add> PartitionSchema sc = createPartitionSchema( null, new ArrayList<String>( ) ); <add> partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); <add> partitionSetings.updateSchema( sc ); <add> assertThat( stepMeta.getStepPartitioningMeta().getPartitionSchema().getName(), equalTo(PARTITION_SCHEMA_NAME)); <add> } <add> <add> @Test <add> public void updateSchemaEmptySchemaName(){ <add> PartitionSchema sc = createPartitionSchema( "", Arrays.asList( "ID_1", "ID_2" ) ); <add> partitionSetings = new PartitionSettings( exactSize, transMeta, stepMeta ); <add> partitionSetings.updateSchema( sc ); <add> assertThat( stepMeta.getStepPartitioningMeta().getPartitionSchema(), equalTo( sc ) ); <add> } <add> <ide> private TransMeta createTransMeta() { <ide> TransMeta transMeta = new TransMeta(); <ide> return transMeta; <ide> return stepPartitionMeta; <ide> } <ide> <del> private Partitioner ctreatePatitioner() { <del> return null; <del> } <del> <ide> private PartitionSchema createPartitionSchema( String name, List<String> partitionIDs ) { <ide> return new PartitionSchema( name, partitionIDs ); <ide> }
Java
apache-2.0
1c7a82c286da97863ef158d9ddf4c412579a4d13
0
necouchman/incubator-guacamole-client,esmailpour-hosein/incubator-guacamole-client,TribeMedia/guacamole-client,flangelo/guacamole-client,softpymesJeffer/incubator-guacamole-client,noelbk/guacamole-client,AIexandr/guacamole-client,Akheon23/guacamole-client,TheAxnJaxn/guacamole-client,lato333/guacamole-client,MaxSmile/guacamole-client,DaanWillemsen/guacamole-client,TheAxnJaxn/guacamole-client,DaanWillemsen/guacamole-client,hguehl/incubator-guacamole-client,AIexandr/guacamole-client,necouchman/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,qiangyee/guacamole-client,mike-jumper/incubator-guacamole-client,Akheon23/guacamole-client,flangelo/guacamole-client,qiangyee/guacamole-client,glyptodon/guacamole-client,softpymesJeffer/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,MaxSmile/guacamole-client,glyptodon/guacamole-client,TribeMedia/guacamole-client,qiangyee/guacamole-client,lato333/guacamole-client,TribeMedia/guacamole-client,noelbk/guacamole-client,necouchman/incubator-guacamole-client,flangelo/guacamole-client,lato333/guacamole-client,MaxSmile/guacamole-client,mike-jumper/incubator-guacamole-client,TheAxnJaxn/guacamole-client,jmuehlner/incubator-guacamole-client,hguehl/incubator-guacamole-client,lato333/guacamole-client,Akheon23/guacamole-client,jmuehlner/incubator-guacamole-client,glyptodon/guacamole-client,mike-jumper/incubator-guacamole-client,hguehl/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,AIexandr/guacamole-client,glyptodon/guacamole-client,glyptodon/guacamole-client,hguehl/incubator-guacamole-client,noelbk/guacamole-client,necouchman/incubator-guacamole-client,DaanWillemsen/guacamole-client,softpymesJeffer/incubator-guacamole-client,nkoterba/guacamole-common-js
package net.sourceforge.guacamole.net.basic; import java.io.IOException; import java.util.Collection; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sourceforge.guacamole.GuacamoleException; import net.sourceforge.guacamole.net.auth.AuthenticationProvider; import net.sourceforge.guacamole.net.auth.Credentials; import net.sourceforge.guacamole.net.basic.event.SessionListenerCollection; import net.sourceforge.guacamole.net.basic.properties.BasicGuacamoleProperties; import net.sourceforge.guacamole.net.event.AuthenticationFailureEvent; import net.sourceforge.guacamole.net.event.AuthenticationSuccessEvent; import net.sourceforge.guacamole.net.event.listener.AuthenticationFailureListener; import net.sourceforge.guacamole.net.event.listener.AuthenticationSuccessListener; import net.sourceforge.guacamole.properties.GuacamoleProperties; import net.sourceforge.guacamole.protocol.GuacamoleConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract servlet which provides an authenticatedService() function that * is only called if the HTTP request is authenticated, or the current * HTTP session has already been authenticated. * * Authorized configurations are retrieved using the authentication provider * defined in guacamole.properties. The authentication provider has access * to the request and session, in addition to any submitted username and * password, in order to authenticate the user. * * All authorized configurations will be stored in the current HttpSession. * * Success and failure are logged. * * @author Michael Jumper */ public abstract class AuthenticatingHttpServlet extends HttpServlet { private Logger logger = LoggerFactory.getLogger(AuthenticatingHttpServlet.class); /** * The session attribute holding the map of configurations. */ private static final String CONFIGURATIONS_ATTRIBUTE = "GUAC_CONFIGS"; /** * The session attribute holding the credentials authorizing this session. */ private static final String CREDENTIALS_ATTRIBUTE = "GUAC_CREDS"; /** * The error message to be provided to the client user if authentication * fails for ANY REASON. */ private static final String AUTH_ERROR_MESSAGE = "User not logged in or authentication failed."; /** * The AuthenticationProvider to use to authenticate all requests. */ private AuthenticationProvider authProvider; @Override public void init() throws ServletException { // Get auth provider instance try { authProvider = GuacamoleProperties.getRequiredProperty(BasicGuacamoleProperties.AUTH_PROVIDER); } catch (GuacamoleException e) { logger.error("Error getting authentication provider from properties.", e); throw new ServletException(e); } } /** * Notifies all listeners in the given collection that authentication has * failed. * * @param listeners A collection of all listeners that should be notified. * @param credentials The credentials associated with the authentication * request that failed. */ private void notifyFailed(Collection listeners, Credentials credentials) { // Build event for auth failure AuthenticationFailureEvent event = new AuthenticationFailureEvent(credentials); // Notify all listeners for (Object listener : listeners) { try { if (listener instanceof AuthenticationFailureListener) ((AuthenticationFailureListener) listener).authenticationFailed(event); } catch (GuacamoleException e) { logger.error("Error notifying AuthenticationFailureListener.", e); } } } /** * Notifies all listeners in the given collection that authentication was * successful. * * @param listeners A collection of all listeners that should be notified. * @param credentials The credentials associated with the authentication * request that succeeded. * @return true if all listeners are allowing the authentication success, * or if there are no listeners, and false if any listener is * canceling the authentication success. Note that once one * listener cancels, no other listeners will run. * @throws GuacamoleException If any listener throws an error while being * notified. Note that if any listener throws an * error, the success is canceled, and no other * listeners will run. */ private boolean notifySuccess(Collection listeners, Credentials credentials) throws GuacamoleException { // Build event for auth success AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(credentials); // Notify all listeners for (Object listener : listeners) { if (listener instanceof AuthenticationSuccessListener) { // Cancel immediately if hook returns false if (!((AuthenticationSuccessListener) listener).authenticationSucceeded(event)) return false; } } return true; } /** * Sends a predefined, generic error message to the user, along with a * "403 - Forbidden" HTTP status code in the response. * * @param response The response to send the error within. * @throws IOException If an error occurs while sending the error. */ private void failAuthentication(HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_FORBIDDEN); } /** * Returns the credentials associated with the given session. * * @param session The session to retrieve credentials from. * @return The credentials associated with the given session. */ protected Credentials getCredentials(HttpSession session) { return (Credentials) session.getAttribute(CREDENTIALS_ATTRIBUTE); } /** * Returns the configurations associated with the given session. * * @param session The session to retrieve configurations from. * @return The configurations associated with the given session. */ protected Map<String, GuacamoleConfiguration> getConfigurations(HttpSession session) { return (Map<String, GuacamoleConfiguration>) session.getAttribute(CONFIGURATIONS_ATTRIBUTE); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession httpSession = request.getSession(true); // Try to get configs from session Map<String, GuacamoleConfiguration> configs = getConfigurations(httpSession); // If no configs, try to authenticate the user to get the configs using // this request. if (configs == null) { SessionListenerCollection listeners; try { listeners = new SessionListenerCollection(httpSession); } catch (GuacamoleException e) { logger.error("Failed to retrieve listeners. Authentication canceled.", e); failAuthentication(response); return; } // Retrieve username and password from parms String username = request.getParameter("username"); String password = request.getParameter("password"); // Build credentials object Credentials credentials = new Credentials(); credentials.setSession(httpSession); credentials.setRequest(request); credentials.setUsername(username); credentials.setPassword(password); // Get authorized configs try { configs = authProvider.getAuthorizedConfigurations(credentials); } /******** HANDLE FAILED AUTHENTICATION ********/ // If error retrieving configs, fail authentication, notify listeners catch (GuacamoleException e) { logger.error("Error retrieving configuration(s) for user \"{}\".", credentials.getUsername(), e); notifyFailed(listeners, credentials); failAuthentication(response); return; } // If no configs, fail authentication, notify listeners if (configs == null) { logger.warn("Authentication attempt from {} for user \"{}\" failed.", request.getRemoteAddr(), credentials.getUsername()); notifyFailed(listeners, credentials); failAuthentication(response); return; } /******** HANDLE SUCCESSFUL AUTHENTICATION ********/ try { // Otherwise, authentication has been succesful logger.info("User \"{}\" successfully authenticated from {}.", credentials.getUsername(), request.getRemoteAddr()); // Notify of success, cancel if requested if (!notifySuccess(listeners, credentials)) { logger.info("Successful authentication canceled by hook."); failAuthentication(response); return; } } catch (GuacamoleException e) { // Cancel authentication success if hook throws exception logger.error("Successful authentication canceled by error in hook.", e); failAuthentication(response); return; } // Associate configs and credentials with session httpSession.setAttribute(CONFIGURATIONS_ATTRIBUTE, configs); httpSession.setAttribute(CREDENTIALS_ATTRIBUTE, credentials); } // Allow servlet to run now that authentication has been validated authenticatedService(configs, request, response); } protected abstract void authenticatedService( Map<String, GuacamoleConfiguration> configs, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; }
guacamole/src/main/java/net/sourceforge/guacamole/net/basic/AuthenticatingHttpServlet.java
package net.sourceforge.guacamole.net.basic; import java.io.IOException; import java.util.Collection; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sourceforge.guacamole.GuacamoleException; import net.sourceforge.guacamole.net.auth.AuthenticationProvider; import net.sourceforge.guacamole.net.auth.Credentials; import net.sourceforge.guacamole.net.basic.event.SessionListenerCollection; import net.sourceforge.guacamole.net.basic.properties.BasicGuacamoleProperties; import net.sourceforge.guacamole.net.event.AuthenticationFailureEvent; import net.sourceforge.guacamole.net.event.AuthenticationSuccessEvent; import net.sourceforge.guacamole.net.event.listener.AuthenticationFailureListener; import net.sourceforge.guacamole.net.event.listener.AuthenticationSuccessListener; import net.sourceforge.guacamole.properties.GuacamoleProperties; import net.sourceforge.guacamole.protocol.GuacamoleConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract servlet which provides an authenticatedService() function that * is only called if the HTTP request is authenticated, or the current * HTTP session has already been authenticated. * * Authorized configurations are retrieved using the authentication provider * defined in guacamole.properties. The authentication provider has access * to the request and session, in addition to any submitted username and * password, in order to authenticate the user. * * All authorized configurations will be stored in the current HttpSession. * * Success and failure are logged. * * @author Michael Jumper */ public abstract class AuthenticatingHttpServlet extends HttpServlet { private Logger logger = LoggerFactory.getLogger(AuthenticatingHttpServlet.class); /** * The session attribute holding the map of configurations. */ private static final String CONFIGURATIONS_ATTRIBUTE = "GUAC_CONFIGS"; /** * The session attribute holding the credentials authorizing this session. */ private static final String CREDENTIALS_ATTRIBUTE = "GUAC_CREDS"; /** * The error message to be provided to the client user if authentication * fails for ANY REASON. */ private static final String AUTH_ERROR_MESSAGE = "User not logged in or authentication failed."; /** * The AuthenticationProvider to use to authenticate all requests. */ private AuthenticationProvider authProvider; @Override public void init() throws ServletException { // Get auth provider instance try { authProvider = GuacamoleProperties.getRequiredProperty(BasicGuacamoleProperties.AUTH_PROVIDER); } catch (GuacamoleException e) { logger.error("Error getting authentication provider from properties.", e); throw new ServletException(e); } } /** * Notifies all listeners in the given collection that authentication has * failed. * * @param listeners A collection of all listeners that should be notified. * @param credentials The credentials associated with the authentication * request that failed. */ private void notifyFailed(Collection listeners, Credentials credentials) { // Build event for auth failure AuthenticationFailureEvent event = new AuthenticationFailureEvent(credentials); // Notify all listeners for (Object listener : listeners) { try { if (listener instanceof AuthenticationFailureListener) ((AuthenticationFailureListener) listener).authenticationFailed(event); } catch (GuacamoleException e) { logger.error("Error notifying AuthenticationFailureListener.", e); } } } /** * Notifies all listeners in the given collection that authentication was * successful. * * @param listeners A collection of all listeners that should be notified. * @param credentials The credentials associated with the authentication * request that succeeded. * @return true if all listeners are allowing the authentication success, * or if there are no listeners, and false if any listener is * canceling the authentication success. Note that once one * listener cancels, no other listeners will run. * @throws GuacamoleException If any listener throws an error while being * notified. Note that if any listener throws an * error, the success is canceled, and no other * listeners will run. */ private boolean notifySuccess(Collection listeners, Credentials credentials) throws GuacamoleException { // Build event for auth success AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(credentials); // Notify all listeners for (Object listener : listeners) { if (listener instanceof AuthenticationSuccessListener) { // Cancel immediately if hook returns false if (!((AuthenticationSuccessListener) listener).authenticationSucceeded(event)) return false; } } return true; } /** * Sends a predefined, generic error message to the user, along with a * "403 - Forbidden" HTTP status code in the response. * * @param response The response to send the error within. * @throws IOException If an error occurs while sending the error. */ private void failAuthentication(HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_FORBIDDEN); } /** * Returns the credentials associated with the given session. * * @param session The session to retrieve credentials from. * @return The credentials associated with the given session. */ protected Credentials getCredentials(HttpSession session) { return (Credentials) session.getAttribute(CREDENTIALS_ATTRIBUTE); } /** * Returns the configurations associated with the given session. * * @param session The session to retrieve configurations from. * @return The configurations associated with the given session. */ protected Map<String, GuacamoleConfiguration> getConfigurations(HttpSession session) { return (Map<String, GuacamoleConfiguration>) session.getAttribute(CONFIGURATIONS_ATTRIBUTE); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession httpSession = request.getSession(true); // Try to get configs from session Map<String, GuacamoleConfiguration> configs = getConfigurations(httpSession); // If no configs, try to authenticate the user to get the configs using // this request. if (configs == null) { SessionListenerCollection listeners; try { listeners = new SessionListenerCollection(httpSession); } catch (GuacamoleException e) { logger.error("Failed to retrieve listeners. Authentication canceled.", e); failAuthentication(response); return; } // Retrieve username and password from parms String username = request.getParameter("username"); String password = request.getParameter("password"); // Build credentials object Credentials credentials = new Credentials(); credentials.setSession(httpSession); credentials.setRequest(request); credentials.setUsername(username); credentials.setPassword(password); // Get authorized configs try { configs = authProvider.getAuthorizedConfigurations(credentials); } /******** HANDLE FAILED AUTHENTICATION ********/ // If error retrieving configs, fail authentication, notify listeners catch (GuacamoleException e) { logger.error("Error retrieving configuration(s) for user \"{}\".", credentials.getUsername()); notifyFailed(listeners, credentials); failAuthentication(response); return; } // If no configs, fail authentication, notify listeners if (configs == null) { logger.warn("Authentication attempt from {} for user \"{}\" failed.", request.getRemoteAddr(), credentials.getUsername()); notifyFailed(listeners, credentials); failAuthentication(response); return; } /******** HANDLE SUCCESSFUL AUTHENTICATION ********/ try { // Otherwise, authentication has been succesful logger.info("User \"{}\" successfully authenticated from {}.", credentials.getUsername(), request.getRemoteAddr()); // Notify of success, cancel if requested if (!notifySuccess(listeners, credentials)) { logger.info("Successful authentication canceled by hook."); failAuthentication(response); return; } } catch (GuacamoleException e) { // Cancel authentication success if hook throws exception logger.error("Successful authentication canceled by error in hook."); failAuthentication(response); return; } // Associate configs and credentials with session httpSession.setAttribute(CONFIGURATIONS_ATTRIBUTE, configs); httpSession.setAttribute(CREDENTIALS_ATTRIBUTE, credentials); } // Allow servlet to run now that authentication has been validated authenticatedService(configs, request, response); } protected abstract void authenticatedService( Map<String, GuacamoleConfiguration> configs, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; }
Include exceptions in logger errors.
guacamole/src/main/java/net/sourceforge/guacamole/net/basic/AuthenticatingHttpServlet.java
Include exceptions in logger errors.
<ide><path>uacamole/src/main/java/net/sourceforge/guacamole/net/basic/AuthenticatingHttpServlet.java <ide> // If error retrieving configs, fail authentication, notify listeners <ide> catch (GuacamoleException e) { <ide> logger.error("Error retrieving configuration(s) for user \"{}\".", <del> credentials.getUsername()); <add> credentials.getUsername(), e); <ide> <ide> notifyFailed(listeners, credentials); <ide> failAuthentication(response); <ide> catch (GuacamoleException e) { <ide> <ide> // Cancel authentication success if hook throws exception <del> logger.error("Successful authentication canceled by error in hook."); <add> logger.error("Successful authentication canceled by error in hook.", e); <ide> failAuthentication(response); <ide> return; <ide>
Java
apache-2.0
0ccd346f71ac33bca790b595c0beba793aab548d
0
jishenghua/JSH_ERP,jishenghua/JSH_ERP,jishenghua/JSH_ERP,jishenghua/JSH_ERP,jishenghua/JSH_ERP,jishenghua/JSH_ERP
package com.jsh.erp.controller; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jsh.erp.constants.ExceptionConstants; import com.jsh.erp.datasource.entities.Function; import com.jsh.erp.datasource.entities.User; import com.jsh.erp.datasource.entities.UserBusiness; import com.jsh.erp.exception.BusinessRunTimeException; import com.jsh.erp.service.functions.FunctionService; import com.jsh.erp.service.userBusiness.UserBusinessService; import com.jsh.erp.utils.BaseResponseInfo; import com.jsh.erp.utils.StringUtil; import com.jsh.erp.utils.Tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * @author ji-sheng-hua jshERP */ @RestController @RequestMapping(value = "/function") public class FunctionController { private Logger logger = LoggerFactory.getLogger(FunctionController.class); @Resource private FunctionService functionService; @Resource private UserBusinessService userBusinessService; @PostMapping(value = "/findMenuByPNumber") public JSONArray findMenuByPNumber(@RequestBody JSONObject jsonObject, HttpServletRequest request)throws Exception { String pNumber = jsonObject.getString("pNumber"); String userId = jsonObject.getString("userId"); //存放数据json数组 JSONArray dataArray = new JSONArray(); try { Long roleId = 0L; String fc = ""; List<UserBusiness> roleList = userBusinessService.getBasicData(userId, "UserRole"); if(roleList!=null && roleList.size()>0){ String value = roleList.get(0).getValue(); if(StringUtil.isNotEmpty(value)){ String roleIdStr = value.replace("[", "").replace("]", ""); roleId = Long.parseLong(roleIdStr); } } //当前用户所拥有的功能列表,格式如:[1][2][5] List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions"); if(funList!=null && funList.size()>0){ fc = funList.get(0).getValue(); } List<Function> dataList = functionService.getRoleFunction(pNumber); if (dataList.size() != 0) { dataArray = getMenuByFunction(dataList, fc); //增加首页菜单项 JSONObject homeItem = new JSONObject(); homeItem.put("id", 0); homeItem.put("text", "首页"); homeItem.put("icon", "home"); homeItem.put("url", "/dashboard/analysis"); homeItem.put("component", "/layouts/TabLayout"); dataArray.add(0,homeItem); } } catch (DataAccessException e) { logger.error(">>>>>>>>>>>>>>>>>>>查找异常", e); } return dataArray; } public JSONArray getMenuByFunction(List<Function> dataList, String fc) throws Exception { JSONArray dataArray = new JSONArray(); for (Function function : dataList) { JSONObject item = new JSONObject(); List<Function> newList = functionService.getRoleFunction(function.getNumber()); item.put("id", function.getId()); item.put("text", function.getName()); item.put("icon", function.getIcon()); item.put("url", function.getUrl()); //if (Tools.isPluginUrl(function.getUrl())) { // item.put("path", Tools.md5Encryp(function.getUrl())); //} else { // item.put("path", function.getUrl()); //} item.put("component", function.getComponent()); if (newList.size()>0) { JSONArray childrenArr = getMenuByFunction(newList, fc); if(childrenArr.size()>0) { item.put("children", childrenArr); dataArray.add(item); } } else { if (fc.indexOf("[" + function.getId().toString() + "]") != -1) { dataArray.add(item); } } } return dataArray; } /** * 角色对应功能显示 * @param request * @return */ @GetMapping(value = "/findRoleFunction") public JSONArray findRoleFunction(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId, HttpServletRequest request)throws Exception { JSONArray arr = new JSONArray(); try { List<Function> dataListFun = functionService.findRoleFunction("0"); //开始拼接json数据 JSONObject outer = new JSONObject(); outer.put("id", 0); outer.put("key", 0); outer.put("value", 0); outer.put("title", "功能列表"); outer.put("attributes", "功能列表"); //存放数据json数组 JSONArray dataArray = new JSONArray(); if (null != dataListFun) { //根据条件从列表里面移除"系统管理" List<Function> dataList = new ArrayList<>(); for (Function fun : dataListFun) { String token = request.getHeader("X-Access-Token"); Long tenantId = Tools.getTenantIdByToken(token); if (tenantId!=0L) { if(!("系统管理").equals(fun.getName())) { dataList.add(fun); } } else { //超管 dataList.add(fun); } } dataArray = getFunctionList(dataList, type, keyId); outer.put("children", dataArray); } arr.add(outer); } catch (Exception e) { e.printStackTrace(); } return arr; } public JSONArray getFunctionList(List<Function> dataList, String type, String keyId) throws Exception { JSONArray dataArray = new JSONArray(); if (null != dataList) { for (Function function : dataList) { JSONObject item = new JSONObject(); item.put("id", function.getId()); item.put("key", function.getId()); item.put("value", function.getId()); item.put("title", function.getName()); item.put("attributes", function.getName()); Boolean flag = false; try { flag = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + function.getId().toString() + "]"); } catch (Exception e) { logger.error(">>>>>>>>>>>>>>>>>设置角色对应的功能:类型" + type + " KeyId为: " + keyId + " 存在异常!"); } if (flag == true) { item.put("checked", true); } List<Function> funList = functionService.findRoleFunction(function.getNumber()); if(funList.size()>0) { JSONArray funArr = getFunctionList(funList, type, keyId); item.put("children", funArr); dataArray.add(item); } else { dataArray.add(item); } } } return dataArray; } /** * 根据id列表查找功能信息 * @param functionsIds * @param request * @return */ @GetMapping(value = "/findByIds") public BaseResponseInfo findByIds(@RequestParam("functionsIds") String functionsIds, HttpServletRequest request)throws Exception { BaseResponseInfo res = new BaseResponseInfo(); try { List<Function> dataList = functionService.findByIds(functionsIds); JSONObject outer = new JSONObject(); outer.put("total", dataList.size()); //存放数据json数组 JSONArray dataArray = new JSONArray(); if (null != dataList) { for (Function function : dataList) { JSONObject item = new JSONObject(); item.put("Id", function.getId()); item.put("Name", function.getName()); item.put("PushBtn", function.getPushBtn()); item.put("op", 1); dataArray.add(item); } } outer.put("rows", dataArray); res.code = 200; res.data = outer; } catch (Exception e) { e.printStackTrace(); res.code = 500; res.data = "获取数据失败"; } return res; } }
jshERP-boot/src/main/java/com/jsh/erp/controller/FunctionController.java
package com.jsh.erp.controller; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jsh.erp.constants.ExceptionConstants; import com.jsh.erp.datasource.entities.Function; import com.jsh.erp.datasource.entities.User; import com.jsh.erp.datasource.entities.UserBusiness; import com.jsh.erp.exception.BusinessRunTimeException; import com.jsh.erp.service.functions.FunctionService; import com.jsh.erp.service.userBusiness.UserBusinessService; import com.jsh.erp.utils.BaseResponseInfo; import com.jsh.erp.utils.StringUtil; import com.jsh.erp.utils.Tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * @author ji-sheng-hua jshERP */ @RestController @RequestMapping(value = "/function") public class FunctionController { private Logger logger = LoggerFactory.getLogger(FunctionController.class); @Resource private FunctionService functionService; @Resource private UserBusinessService userBusinessService; public JSONArray getMenuByFunction(List<Function> dataList, String fc) throws Exception { JSONArray dataArray = new JSONArray(); for (Function function : dataList) { JSONObject item = new JSONObject(); List<Function> newList = functionService.getRoleFunction(function.getNumber()); item.put("id", function.getId()); item.put("text", function.getName()); item.put("icon", function.getIcon()); item.put("url", function.getUrl()); //if (Tools.isPluginUrl(function.getUrl())) { // item.put("path", Tools.md5Encryp(function.getUrl())); //} else { // item.put("path", function.getUrl()); //} item.put("component", function.getComponent()); if (newList.size()>0) { JSONArray childrenArr = getMenuByFunction(newList, fc); if(childrenArr.size()>0) { item.put("children", childrenArr); dataArray.add(item); } } else { if (fc.indexOf("[" + function.getId().toString() + "]") != -1) { dataArray.add(item); } } } return dataArray; } @PostMapping(value = "/findMenuByPNumber") public JSONArray findMenuByPNumber(@RequestBody JSONObject jsonObject, HttpServletRequest request)throws Exception { String pNumber = jsonObject.getString("pNumber"); String userId = jsonObject.getString("userId"); //存放数据json数组 JSONArray dataArray = new JSONArray(); try { Long roleId = 0L; String fc = ""; List<UserBusiness> roleList = userBusinessService.getBasicData(userId, "UserRole"); if(roleList!=null && roleList.size()>0){ String value = roleList.get(0).getValue(); if(StringUtil.isNotEmpty(value)){ String roleIdStr = value.replace("[", "").replace("]", ""); roleId = Long.parseLong(roleIdStr); } } //当前用户所拥有的功能列表,格式如:[1][2][5] List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions"); if(funList!=null && funList.size()>0){ fc = funList.get(0).getValue(); } List<Function> dataList = functionService.getRoleFunction(pNumber); if (dataList.size() != 0) { dataArray = getMenuByFunction(dataList, fc); //增加首页菜单项 JSONObject homeItem = new JSONObject(); homeItem.put("id", 0); homeItem.put("text", "首页"); homeItem.put("icon", "home"); homeItem.put("url", "/dashboard/analysis"); homeItem.put("component", "/layouts/TabLayout"); dataArray.add(0,homeItem); } } catch (DataAccessException e) { logger.error(">>>>>>>>>>>>>>>>>>>查找异常", e); } return dataArray; } /** * 角色对应功能显示 * @param request * @return */ @GetMapping(value = "/findRoleFunction") public JSONArray findRoleFunction(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId, HttpServletRequest request)throws Exception { JSONArray arr = new JSONArray(); try { List<Function> dataListFun = functionService.findRoleFunction("0"); //开始拼接json数据 JSONObject outer = new JSONObject(); outer.put("id", 1); outer.put("key", 1); outer.put("value", 1); outer.put("title", "功能列表"); outer.put("attributes", "功能列表"); //存放数据json数组 JSONArray dataArray = new JSONArray(); if (null != dataListFun) { //根据条件从列表里面移除"系统管理" List<Function> dataList = new ArrayList<>(); for (Function fun : dataListFun) { String token = request.getHeader("X-Access-Token"); Long tenantId = Tools.getTenantIdByToken(token); if (tenantId!=0L) { if(!("系统管理").equals(fun.getName())) { dataList.add(fun); } } else { //超管 dataList.add(fun); } } dataArray = getFunctionList(dataList, type, keyId); outer.put("children", dataArray); } arr.add(outer); } catch (Exception e) { e.printStackTrace(); } return arr; } public JSONArray getFunctionList(List<Function> dataList, String type, String keyId) throws Exception { JSONArray dataArray = new JSONArray(); if (null != dataList) { for (Function function : dataList) { JSONObject item = new JSONObject(); item.put("id", function.getId()); item.put("key", function.getId()); item.put("value", function.getId()); item.put("title", function.getName()); item.put("attributes", function.getName()); Boolean flag = false; try { flag = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + function.getId().toString() + "]"); } catch (Exception e) { logger.error(">>>>>>>>>>>>>>>>>设置角色对应的功能:类型" + type + " KeyId为: " + keyId + " 存在异常!"); } if (flag == true) { item.put("checked", true); } List<Function> funList = functionService.findRoleFunction(function.getNumber()); if(funList.size()>0) { JSONArray funArr = getFunctionList(funList, type, keyId); item.put("children", funArr); dataArray.add(item); } else { dataArray.add(item); } } } return dataArray; } /** * 根据id列表查找功能信息 * @param functionsIds * @param request * @return */ @GetMapping(value = "/findByIds") public BaseResponseInfo findByIds(@RequestParam("functionsIds") String functionsIds, HttpServletRequest request)throws Exception { BaseResponseInfo res = new BaseResponseInfo(); try { List<Function> dataList = functionService.findByIds(functionsIds); JSONObject outer = new JSONObject(); outer.put("total", dataList.size()); //存放数据json数组 JSONArray dataArray = new JSONArray(); if (null != dataList) { for (Function function : dataList) { JSONObject item = new JSONObject(); item.put("Id", function.getId()); item.put("Name", function.getName()); item.put("PushBtn", function.getPushBtn()); item.put("op", 1); dataArray.add(item); } } outer.put("rows", dataArray); res.code = 200; res.data = outer; } catch (Exception e) { e.printStackTrace(); res.code = 500; res.data = "获取数据失败"; } return res; } }
解决超管无法配权限的bug
jshERP-boot/src/main/java/com/jsh/erp/controller/FunctionController.java
解决超管无法配权限的bug
<ide><path>shERP-boot/src/main/java/com/jsh/erp/controller/FunctionController.java <ide> <ide> @Resource <ide> private UserBusinessService userBusinessService; <add> <add> @PostMapping(value = "/findMenuByPNumber") <add> public JSONArray findMenuByPNumber(@RequestBody JSONObject jsonObject, <add> HttpServletRequest request)throws Exception { <add> String pNumber = jsonObject.getString("pNumber"); <add> String userId = jsonObject.getString("userId"); <add> //存放数据json数组 <add> JSONArray dataArray = new JSONArray(); <add> try { <add> Long roleId = 0L; <add> String fc = ""; <add> List<UserBusiness> roleList = userBusinessService.getBasicData(userId, "UserRole"); <add> if(roleList!=null && roleList.size()>0){ <add> String value = roleList.get(0).getValue(); <add> if(StringUtil.isNotEmpty(value)){ <add> String roleIdStr = value.replace("[", "").replace("]", ""); <add> roleId = Long.parseLong(roleIdStr); <add> } <add> } <add> //当前用户所拥有的功能列表,格式如:[1][2][5] <add> List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions"); <add> if(funList!=null && funList.size()>0){ <add> fc = funList.get(0).getValue(); <add> } <add> List<Function> dataList = functionService.getRoleFunction(pNumber); <add> if (dataList.size() != 0) { <add> dataArray = getMenuByFunction(dataList, fc); <add> //增加首页菜单项 <add> JSONObject homeItem = new JSONObject(); <add> homeItem.put("id", 0); <add> homeItem.put("text", "首页"); <add> homeItem.put("icon", "home"); <add> homeItem.put("url", "/dashboard/analysis"); <add> homeItem.put("component", "/layouts/TabLayout"); <add> dataArray.add(0,homeItem); <add> } <add> } catch (DataAccessException e) { <add> logger.error(">>>>>>>>>>>>>>>>>>>查找异常", e); <add> } <add> return dataArray; <add> } <ide> <ide> public JSONArray getMenuByFunction(List<Function> dataList, String fc) throws Exception { <ide> JSONArray dataArray = new JSONArray(); <ide> return dataArray; <ide> } <ide> <del> @PostMapping(value = "/findMenuByPNumber") <del> public JSONArray findMenuByPNumber(@RequestBody JSONObject jsonObject, <del> HttpServletRequest request)throws Exception { <del> String pNumber = jsonObject.getString("pNumber"); <del> String userId = jsonObject.getString("userId"); <del> //存放数据json数组 <del> JSONArray dataArray = new JSONArray(); <del> try { <del> Long roleId = 0L; <del> String fc = ""; <del> List<UserBusiness> roleList = userBusinessService.getBasicData(userId, "UserRole"); <del> if(roleList!=null && roleList.size()>0){ <del> String value = roleList.get(0).getValue(); <del> if(StringUtil.isNotEmpty(value)){ <del> String roleIdStr = value.replace("[", "").replace("]", ""); <del> roleId = Long.parseLong(roleIdStr); <del> } <del> } <del> //当前用户所拥有的功能列表,格式如:[1][2][5] <del> List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions"); <del> if(funList!=null && funList.size()>0){ <del> fc = funList.get(0).getValue(); <del> } <del> List<Function> dataList = functionService.getRoleFunction(pNumber); <del> if (dataList.size() != 0) { <del> dataArray = getMenuByFunction(dataList, fc); <del> //增加首页菜单项 <del> JSONObject homeItem = new JSONObject(); <del> homeItem.put("id", 0); <del> homeItem.put("text", "首页"); <del> homeItem.put("icon", "home"); <del> homeItem.put("url", "/dashboard/analysis"); <del> homeItem.put("component", "/layouts/TabLayout"); <del> dataArray.add(0,homeItem); <del> } <del> } catch (DataAccessException e) { <del> logger.error(">>>>>>>>>>>>>>>>>>>查找异常", e); <del> } <del> return dataArray; <del> } <del> <ide> /** <ide> * 角色对应功能显示 <ide> * @param request <ide> List<Function> dataListFun = functionService.findRoleFunction("0"); <ide> //开始拼接json数据 <ide> JSONObject outer = new JSONObject(); <del> outer.put("id", 1); <del> outer.put("key", 1); <del> outer.put("value", 1); <add> outer.put("id", 0); <add> outer.put("key", 0); <add> outer.put("value", 0); <ide> outer.put("title", "功能列表"); <ide> outer.put("attributes", "功能列表"); <ide> //存放数据json数组
Java
mit
6eee62a98fa982600698bd31084d599980e4c125
0
mixolidia/narjillos,nusco/narjillos,colinrubbert/narjillos,colinrubbert/narjillos,mixolidia/narjillos
package org.nusco.narjillos; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Random; import org.nusco.narjillos.ecosystem.Ecosystem; import org.nusco.narjillos.experiment.Experiment; import org.nusco.narjillos.genomics.DNA; import org.nusco.narjillos.genomics.GenePool; import org.nusco.narjillos.serializer.JSON; import org.nusco.narjillos.shared.utilities.NumberFormat; public class Lab { private static final int PARSE_INTERVAL = 10000; private static boolean persistent = false; private final Experiment experiment; private GenePool genePool = new GenePool(); public Lab(String... args) { DNA.setObserver(genePool); experiment = initialize(args); System.out.println(getHeadersString()); System.out.println(getStatusString(experiment.getTicksChronometer().getTotalTicks())); } public Experiment getExperiment() { return experiment; } public Ecosystem getEcosystem() { return experiment.getEcosystem(); } public int getTicksInLastSecond() { return experiment.getTicksChronometer().getTicksInLastSecond(); } public long getTotalTicks() { return experiment.getTicksChronometer().getTotalTicks(); } public boolean tick() { boolean thereAreSurvivors = experiment.tick(); if (experiment.getTicksChronometer().getTotalTicks() % PARSE_INTERVAL == 0) executePerodicOperations(); if (!thereAreSurvivors) { System.out.println("*** Extinction happens. ***"); reportEndOfExperiment(); } return thereAreSurvivors; } private void executePerodicOperations() { long ticks = experiment.getTicksChronometer().getTotalTicks(); if (ticks % PARSE_INTERVAL != 0) return; if (persistent) { writeExperimentToFile(); writeGenePoolToFile(); } System.out.println(getStatusString(ticks)); } private String getHeadersString() { return alignLeft("tick") + alignLeft("time") + alignLeft("tps") + alignLeft("narj") + alignLeft("food"); } private String getStatusString(long tick) { return alignLeft(NumberFormat.format(tick)) + alignLeft(NumberFormat.format(experiment.getTotalRunningTimeInSeconds())) + alignLeft(experiment.getTicksChronometer().getTicksInLastSecond()) + alignLeft(experiment.getEcosystem().getNumberOfNarjillos()) + alignLeft(experiment.getEcosystem().getNumberOfFoodPieces()); } private String alignLeft(Object label) { final String padding = " "; String paddedLabel = padding + label.toString(); return paddedLabel.substring(paddedLabel.length() - padding.length()); } public Experiment initialize(String... args) { String gitCommit = args.length == 0 ? "unknown" : args[0]; String secondArgument = args.length < 2 ? null : args[1]; final Experiment experiment = createExperiment(gitCommit, secondArgument); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { experiment.stop(); reportEndOfExperiment(); } }); DNA.setObserver(genePool); return experiment; } private Experiment createExperiment(String gitCommit, String secondArgument) { if (secondArgument == null) { System.out.println("Starting new experiment with random seed"); persistent = true; return new Experiment(gitCommit, generateRandomSeed(), null); } else if (secondArgument.equals("no-persistence")) { System.out.println("Starting new non-persistent experiment with random seed"); return new Experiment(gitCommit, generateRandomSeed(), null); } else if (isInteger(secondArgument)) { long seed = Long.parseLong(secondArgument); System.out.println("Starting experiment " + seed + " from scratch"); persistent = true; return new Experiment(gitCommit, seed, null); } else if (secondArgument.endsWith(".nrj")) { DNA dna = readDNAFromFile(secondArgument); System.out.println("Observing DNA " + dna); persistent = true; return new Experiment(gitCommit, generateRandomSeed(), dna); } else if (secondArgument.startsWith("{")) { System.out.println("Observing DNA " + secondArgument); persistent = true; return new Experiment(gitCommit, generateRandomSeed(), new DNA(secondArgument)); } else { String experimentId = stripFileExtension(secondArgument); System.out.println("Picking up experiment from " + experimentId + ".exp"); persistent = true; genePool = readGenePoolFromFile(experimentId); return readExperimentFromFile(experimentId); } } private String stripFileExtension(String fileName) { int extensionIndex = fileName.lastIndexOf('.'); return (extensionIndex < 0) ? fileName : fileName.substring(0, extensionIndex); } private long generateRandomSeed() { return Math.abs(new Random().nextInt()); } private boolean isInteger(String argument) { try { Integer.parseInt(argument); return true; } catch (NumberFormatException e) { return false; } } private DNA readDNAFromFile(String file) { return new DNA(read(file)); } private Experiment readExperimentFromFile(String file) { return JSON.fromJson(read(file + ".exp"), Experiment.class); } private GenePool readGenePoolFromFile(String file) { Path filePath = Paths.get(file + ".gpl"); if (!Files.exists(filePath)) { System.out.println("Warning: no .gpl file found. Continuing with empty genepool."); return new GenePool(); } return JSON.fromJson(read(file + ".gpl"), GenePool.class); } private String read(String file) { try { byte[] encoded = Files.readAllBytes(Paths.get(file)); return new String(encoded, Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(e); } } private void writeExperimentToFile() { String fileName = experiment.getId() + ".exp"; String content = JSON.toJson(experiment, Experiment.class); writeToFileSafely(fileName, content); } private void writeGenePoolToFile() { String fileName = experiment.getId() + ".gpl"; String content = JSON.toJson(genePool, GenePool.class); writeToFileSafely(fileName, content); } private void writeToFileSafely(String fileName, String content) { try { String tempFileName = fileName + ".tmp"; writeToFile(tempFileName, content); moveFile(tempFileName, fileName); } catch (IOException e) { throw new RuntimeException(e); } } private void moveFile(String source, String destination) throws IOException { Path filePath = Paths.get(destination); if (Files.exists(filePath)) Files.delete(filePath); Files.move(Paths.get(source), filePath); } private void writeToFile(String fileName, String content) throws IOException, FileNotFoundException { PrintWriter out = new PrintWriter(fileName); out.print(content); out.close(); } private void reportEndOfExperiment() { System.out.println("Experiment " + experiment.getId() + " ending at " + experiment.getTotalRunningTimeInSeconds() + " seconds, " + experiment.getTicksChronometer().getTotalTicks() + " ticks"); } // arguments: [<git_commit>, <random_seed | dna_file | dna_document | // experiment_file>] public static void main(String... args) { Lab lab = new Lab(args); while (lab.tick()) ; } }
core/src/main/java/org/nusco/narjillos/Lab.java
package org.nusco.narjillos; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Random; import org.nusco.narjillos.ecosystem.Ecosystem; import org.nusco.narjillos.experiment.Experiment; import org.nusco.narjillos.genomics.DNA; import org.nusco.narjillos.genomics.GenePool; import org.nusco.narjillos.serializer.JSON; import org.nusco.narjillos.shared.utilities.NumberFormat; public class Lab { private static final int PARSE_INTERVAL = 10000; private static boolean persistent = false; private final Experiment experiment; private GenePool genePool = new GenePool(); public Lab(String... args) { DNA.setObserver(genePool); experiment = initialize(args); System.out.println(getHeadersString()); System.out.println(getStatusString(experiment.getTicksChronometer().getTotalTicks())); } public Experiment getExperiment() { return experiment; } public Ecosystem getEcosystem() { return experiment.getEcosystem(); } public int getTicksInLastSecond() { return experiment.getTicksChronometer().getTicksInLastSecond(); } public long getTotalTicks() { return experiment.getTicksChronometer().getTotalTicks(); } public boolean tick() { boolean thereAreSurvivors = experiment.tick(); if (experiment.getTicksChronometer().getTotalTicks() % PARSE_INTERVAL == 0) executePerodicOperations(); if (!thereAreSurvivors) { System.out.println("*** Extinction happens. ***"); reportEndOfExperiment(); } return thereAreSurvivors; } private void executePerodicOperations() { long ticks = experiment.getTicksChronometer().getTotalTicks(); if (ticks % PARSE_INTERVAL != 0) return; if (persistent) { writeExperimentToFile(); writeGenePoolToFile(); } System.out.println(getStatusString(ticks)); } private String getHeadersString() { return alignLeft("tick") + alignLeft("time") + alignLeft("tps") + alignLeft("narj") + alignLeft("food"); } private String getStatusString(long tick) { return alignLeft(NumberFormat.format(tick)) + alignLeft(NumberFormat.format(experiment.getTotalRunningTimeInSeconds())) + alignLeft(experiment.getTicksChronometer().getTicksInLastSecond()) + alignLeft(experiment.getEcosystem().getNumberOfNarjillos()) + alignLeft(experiment.getEcosystem().getNumberOfFoodPieces()); } private String alignLeft(Object label) { final String padding = " "; String paddedLabel = padding + label.toString(); return paddedLabel.substring(paddedLabel.length() - padding.length()); } public Experiment initialize(String... args) { String gitCommit = args.length == 0 ? "unknown" : args[0]; String secondArgument = args.length < 2 ? null : args[1]; final Experiment experiment = createExperiment(gitCommit, secondArgument); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { experiment.stop(); reportEndOfExperiment(); } }); DNA.setObserver(genePool); return experiment; } private Experiment createExperiment(String gitCommit, String secondArgument) { if (secondArgument == null) { System.out.println("Starting new experiment with random seed"); persistent = true; return new Experiment(gitCommit, generateRandomSeed(), null); } else if (secondArgument.equals("no-persistence")) { System.out.println("Starting new non-persistent experiment with random seed"); return new Experiment(gitCommit, generateRandomSeed(), null); } else if (isInteger(secondArgument)) { long seed = Long.parseLong(secondArgument); System.out.println("Starting experiment " + seed + " from scratch"); persistent = true; return new Experiment(gitCommit, seed, null); } else if (secondArgument.endsWith(".nrj")) { DNA dna = readDNAFromFile(secondArgument); System.out.println("Observing DNA " + dna); persistent = true; return new Experiment(gitCommit, generateRandomSeed(), dna); } else if (secondArgument.startsWith("{")) { System.out.println("Observing DNA " + secondArgument); persistent = true; return new Experiment(gitCommit, generateRandomSeed(), new DNA(secondArgument)); } else { String experimentId = stripFileExtension(secondArgument); System.out.println("Picking up experiment from " + experimentId + ".exp"); persistent = true; genePool = readGenePoolFromFile(experimentId); return readExperimentFromFile(experimentId); } } private String stripFileExtension(String fileName) { int extensionIndex = fileName.lastIndexOf('.'); return (extensionIndex < 0) ? fileName : fileName.substring(0, extensionIndex); } private long generateRandomSeed() { return Math.abs(new Random().nextInt()); } private boolean isInteger(String argument) { try { Integer.parseInt(argument); return true; } catch (NumberFormatException e) { return false; } } private DNA readDNAFromFile(String file) { return new DNA(read(file)); } private Experiment readExperimentFromFile(String file) { return JSON.fromJson(read(file + ".exp"), Experiment.class); } private GenePool readGenePoolFromFile(String file) { Path filePath = Paths.get(file + ".gep"); if (!Files.exists(filePath)) { System.out.println("Warning: no .gep file found. Continuing with empty genepool."); return new GenePool(); } return JSON.fromJson(read(file + ".gep"), GenePool.class); } private String read(String file) { try { byte[] encoded = Files.readAllBytes(Paths.get(file)); return new String(encoded, Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(e); } } private void writeExperimentToFile() { String fileName = experiment.getId() + ".exp"; String content = JSON.toJson(experiment, Experiment.class); writeToFileSafely(fileName, content); } private void writeGenePoolToFile() { String fileName = experiment.getId() + ".gep"; String content = JSON.toJson(genePool, GenePool.class); writeToFileSafely(fileName, content); } private void writeToFileSafely(String fileName, String content) { try { String tempFileName = fileName + ".tmp"; writeToFile(tempFileName, content); moveFile(tempFileName, fileName); } catch (IOException e) { throw new RuntimeException(e); } } private void moveFile(String source, String destination) throws IOException { Path filePath = Paths.get(destination); if (Files.exists(filePath)) Files.delete(filePath); Files.move(Paths.get(source), filePath); } private void writeToFile(String fileName, String content) throws IOException, FileNotFoundException { PrintWriter out = new PrintWriter(fileName); out.print(content); out.close(); } private void reportEndOfExperiment() { System.out.println("Experiment " + experiment.getId() + " ending at " + experiment.getTotalRunningTimeInSeconds() + " seconds, " + experiment.getTicksChronometer().getTotalTicks() + " ticks"); } // arguments: [<git_commit>, <random_seed | dna_file | dna_document | // experiment_file>] public static void main(String... args) { Lab lab = new Lab(args); while (lab.tick()) ; } }
Change .gep extension to .gpl Easier to remember.
core/src/main/java/org/nusco/narjillos/Lab.java
Change .gep extension to .gpl
<ide><path>ore/src/main/java/org/nusco/narjillos/Lab.java <ide> } <ide> <ide> private GenePool readGenePoolFromFile(String file) { <del> Path filePath = Paths.get(file + ".gep"); <add> Path filePath = Paths.get(file + ".gpl"); <ide> if (!Files.exists(filePath)) { <del> System.out.println("Warning: no .gep file found. Continuing with empty genepool."); <add> System.out.println("Warning: no .gpl file found. Continuing with empty genepool."); <ide> return new GenePool(); <ide> } <del> return JSON.fromJson(read(file + ".gep"), GenePool.class); <add> return JSON.fromJson(read(file + ".gpl"), GenePool.class); <ide> } <ide> <ide> private String read(String file) { <ide> } <ide> <ide> private void writeGenePoolToFile() { <del> String fileName = experiment.getId() + ".gep"; <add> String fileName = experiment.getId() + ".gpl"; <ide> String content = JSON.toJson(genePool, GenePool.class); <ide> writeToFileSafely(fileName, content); <ide> }
Java
mit
49ada5ac5c34dfea0a769618739b3b37e80abe3e
0
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
package ua.com.fielden.platform.entity; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import static ua.com.fielden.platform.types.Colour.BLACK; import java.math.BigDecimal; import java.util.Currency; import java.util.List; import java.util.stream.Stream; import org.junit.Test; import ua.com.fielden.platform.dao.exceptions.EntityAlreadyExists; import ua.com.fielden.platform.dao.session.TransactionalExecution; import ua.com.fielden.platform.entity.meta.PropertyDescriptor; import ua.com.fielden.platform.entity.query.EntityBatchInsertOperation; import ua.com.fielden.platform.entity.query.metadata.DomainMetadata; import ua.com.fielden.platform.sample.domain.EntityOne; import ua.com.fielden.platform.sample.domain.EntityTwo; import ua.com.fielden.platform.sample.domain.IEntityOne; import ua.com.fielden.platform.sample.domain.IEntityTwo; import ua.com.fielden.platform.sample.domain.UnionEntity; import ua.com.fielden.platform.test.entities.TgEntityWithManyPropTypes; import ua.com.fielden.platform.test.entities.TgEntityWithManyPropTypesCo; import ua.com.fielden.platform.test_config.AbstractDaoTestCase; import ua.com.fielden.platform.types.Hyperlink; import ua.com.fielden.platform.types.Money; public class EntityBatchInsertOperationTest extends AbstractDaoTestCase { private final static String ENTITY_ONE_KEY = "EO 1"; private final static Integer ENTITY_TWO_KEY = 2; @Test public void batch_insert_operation_works_for_single_enity() { final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1"); assertEquals(1, batchInserEntities(entities, 2)); assertEqualityForInsertedEntities(entities); } @Test public void batch_insert_operation_works_for_single_full_batch() { final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1", "Ent2"); assertEquals(2, batchInserEntities(entities, 2)); assertEqualityForInsertedEntities(entities); } @Test public void batch_insert_operation_works_for_two_full_batches() { final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4"); assertEquals(4, batchInserEntities(entities, 2)); assertEqualityForInsertedEntities(entities); } @Test public void batch_insert_operation_works_for_two_full_batches_with_last_batch_not_full() { final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4", "Ent5"); assertEquals(5, batchInserEntities(entities, 2)); assertEqualityForInsertedEntities(entities); } @Test public void batch_insert_operation_fails_while_trying_to_insert_persisted_entities() { batchInserEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3"), 2); try { batchInserEntities(getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()), 2); fail("Expected an exception due to an attempt to insert already persisten entity."); } catch (final EntityAlreadyExists ex) { } } @Test public void batch_insert_a_stream_ignores_persistent_entities() { final List<TgEntityWithManyPropTypes> fistBatch = createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3"); batchInserEntitiesAsStream(fistBatch.stream(), 2); final List<TgEntityWithManyPropTypes> persistedFirstBatch = getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()); final List<TgEntityWithManyPropTypes> secondBatch = createEntitiesForBatchInsert("Ent4", "Ent5"); final List<TgEntityWithManyPropTypes> firstAndSecondBatches = Stream.concat(persistedFirstBatch.stream(), secondBatch.stream()).collect(toList()); assertEquals(2, batchInserEntitiesAsStream(firstAndSecondBatches.stream(), 2)); assertEqualityForInsertedEntities(firstAndSecondBatches); } private int batchInserEntities(final List<TgEntityWithManyPropTypes> entities, final int batchSize) { final EntityBatchInsertOperation insertOp = new EntityBatchInsertOperation(getInstance(DomainMetadata.class), () -> getInstance(TransactionalExecution.class)); return insertOp.batchInsert(entities, batchSize); } private int batchInserEntitiesAsStream(final Stream<TgEntityWithManyPropTypes> entities, final int batchSize) { final EntityBatchInsertOperation insertOp = new EntityBatchInsertOperation(getInstance(DomainMetadata.class), () -> getInstance(TransactionalExecution.class)); return insertOp.batchInsert(entities, batchSize); } private void assertEqualityForInsertedEntities(final List<TgEntityWithManyPropTypes> entities) { final List<TgEntityWithManyPropTypes> savedEntities = getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()); assertEquals(entities, savedEntities); } private List<TgEntityWithManyPropTypes> createEntitiesForBatchInsert(final String ...entitiesKeys) { return asList(entitiesKeys).stream().map(e -> createEntityForBatchInsert(e)).collect(toList()); } private TgEntityWithManyPropTypes createEntityForBatchInsert(final String entityKey) { final UnionEntity unionEntityValue = co$(UnionEntity.class).new_(); unionEntityValue.setPropertyTwo(getInstance(IEntityTwo.class).findByKey(ENTITY_TWO_KEY)); return new_(TgEntityWithManyPropTypes.class, entityKey). setEntityProp(getInstance(IEntityOne.class).findByKey(ENTITY_ONE_KEY)). setStringProp("someString"). setBooleanProp(true). setBigDecimalProp(new BigDecimal("100.999")). setIntProp(20). setIntegerProp(200). setLongProp(100l). setColourProp(BLACK). setClassProperty(String.class). setDateProp(date("2022-02-02 00:00:00")). setUtcDateProp(date("2021-01-01 00:00:00")). setHyperlinkProp(new Hyperlink("https://fielden.com")). setPropertyDescriptorProp(new PropertyDescriptor<>(TgEntityWithManyPropTypes.class, "unionProp")). setMoneyUserTypeProp(new Money(new BigDecimal("100"), Currency.getInstance("USD"))). setMoneyWithTaxAmountUserTypeProp(new Money(new BigDecimal("2000"), 20, Currency.getInstance("AUD"))). setSimpleMoneyTypeProp(new Money("20")). setSimplyMoneyWithTaxAmountProp(new Money(new BigDecimal("1000"), 20, Currency.getInstance("AUD"))). setSimplyMoneyWithTaxAndExTaxAmountTypeProp(new Money(new BigDecimal("3000"), 15, Currency.getInstance("EUR"))). setUnionProp(unionEntityValue); } @Override protected void populateDomain() { super.populateDomain(); save(new_(EntityOne.class, ENTITY_ONE_KEY)); save(new_(EntityTwo.class, ENTITY_TWO_KEY)); } }
platform-dao/src/test/java/ua/com/fielden/platform/entity/EntityBatchInsertOperationTest.java
package ua.com.fielden.platform.entity; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertEquals; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import static ua.com.fielden.platform.types.Colour.BLACK; import java.math.BigDecimal; import java.util.Currency; import java.util.List; import org.junit.Test; import ua.com.fielden.platform.dao.exceptions.EntityAlreadyExists; import ua.com.fielden.platform.dao.session.TransactionalExecution; import ua.com.fielden.platform.entity.meta.PropertyDescriptor; import ua.com.fielden.platform.entity.query.EntityBatchInsertOperation; import ua.com.fielden.platform.entity.query.metadata.DomainMetadata; import ua.com.fielden.platform.sample.domain.EntityOne; import ua.com.fielden.platform.sample.domain.EntityTwo; import ua.com.fielden.platform.sample.domain.IEntityOne; import ua.com.fielden.platform.sample.domain.IEntityTwo; import ua.com.fielden.platform.sample.domain.UnionEntity; import ua.com.fielden.platform.test.entities.TgEntityWithManyPropTypes; import ua.com.fielden.platform.test.entities.TgEntityWithManyPropTypesCo; import ua.com.fielden.platform.test_config.AbstractDaoTestCase; import ua.com.fielden.platform.types.Hyperlink; import ua.com.fielden.platform.types.Money; public class EntityBatchInsertOperationTest extends AbstractDaoTestCase { private final static String ENTITY_ONE_KEY = "EO 1"; private final static Integer ENTITY_TWO_KEY = 2; @Test public void batch_insert_operation_works_for_single_enity() { testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1")); } @Test public void batch_insert_operation_works_for_single_full_batch() { testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2")); } @Test public void batch_insert_operation_works_for_two_full_batches() { testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4")); } @Test public void batch_insert_operation_works_for_two_full_batches_with_last_batch_not_full() { testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4", "Ent5")); } @Test(expected = EntityAlreadyExists.class) public void batch_insert_operation_fails_while_trying_to_insert_persisted_entities() { testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3")); testBatchInsertOfEntities(getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model())); } private void testBatchInsertOfEntities(final List<TgEntityWithManyPropTypes> entities) { final EntityBatchInsertOperation insertOp = new EntityBatchInsertOperation(getInstance(DomainMetadata.class), () -> getInstance(TransactionalExecution.class)); assertEquals(entities.size(), insertOp.batchInsert(entities, 2)); final List<TgEntityWithManyPropTypes> savedEntities = getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()); assertEquals(entities, savedEntities); } private List<TgEntityWithManyPropTypes> createEntitiesForBatchInsert(final String ...entitiesKeys) { return asList(entitiesKeys).stream().map(e -> createEntityForBatchInsert(e)).collect(toList()); } private TgEntityWithManyPropTypes createEntityForBatchInsert(final String entityKey) { final UnionEntity unionEntityValue = co$(UnionEntity.class).new_(); unionEntityValue.setPropertyTwo(getInstance(IEntityTwo.class).findByKey(ENTITY_TWO_KEY)); return new_(TgEntityWithManyPropTypes.class, entityKey). setEntityProp(getInstance(IEntityOne.class).findByKey(ENTITY_ONE_KEY)). setStringProp("someString"). setBooleanProp(true). setBigDecimalProp(new BigDecimal("100.999")). setIntProp(20). setIntegerProp(200). setLongProp(100l). setColourProp(BLACK). setClassProperty(String.class). setDateProp(date("2022-02-02 00:00:00")). setUtcDateProp(date("2021-01-01 00:00:00")). setHyperlinkProp(new Hyperlink("https://fielden.com")). setPropertyDescriptorProp(new PropertyDescriptor<>(TgEntityWithManyPropTypes.class, "unionProp")). setMoneyUserTypeProp(new Money(new BigDecimal("100"), Currency.getInstance("USD"))). setMoneyWithTaxAmountUserTypeProp(new Money(new BigDecimal("2000"), 20, Currency.getInstance("AUD"))). setSimpleMoneyTypeProp(new Money("20")). setSimplyMoneyWithTaxAmountProp(new Money(new BigDecimal("1000"), 20, Currency.getInstance("AUD"))). setSimplyMoneyWithTaxAndExTaxAmountTypeProp(new Money(new BigDecimal("3000"), 15, Currency.getInstance("EUR"))). setUnionProp(unionEntityValue); } @Override protected void populateDomain() { super.populateDomain(); save(new_(EntityOne.class, ENTITY_ONE_KEY)); save(new_(EntityTwo.class, ENTITY_TWO_KEY)); } }
#1032 Refactored and extended tests for EntityBatchUnsertOperation.
platform-dao/src/test/java/ua/com/fielden/platform/entity/EntityBatchInsertOperationTest.java
#1032 Refactored and extended tests for EntityBatchUnsertOperation.
<ide><path>latform-dao/src/test/java/ua/com/fielden/platform/entity/EntityBatchInsertOperationTest.java <ide> import static java.util.Arrays.asList; <ide> import static java.util.stream.Collectors.toList; <ide> import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.fail; <ide> import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll; <ide> import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; <ide> import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; <ide> import java.math.BigDecimal; <ide> import java.util.Currency; <ide> import java.util.List; <add>import java.util.stream.Stream; <ide> <ide> import org.junit.Test; <ide> <ide> <ide> @Test <ide> public void batch_insert_operation_works_for_single_enity() { <del> testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1")); <add> final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1"); <add> assertEquals(1, batchInserEntities(entities, 2)); <add> assertEqualityForInsertedEntities(entities); <ide> } <ide> <ide> @Test <ide> public void batch_insert_operation_works_for_single_full_batch() { <del> testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2")); <add> final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1", "Ent2"); <add> assertEquals(2, batchInserEntities(entities, 2)); <add> assertEqualityForInsertedEntities(entities); <ide> } <ide> <ide> @Test <ide> public void batch_insert_operation_works_for_two_full_batches() { <del> testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4")); <add> final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4"); <add> assertEquals(4, batchInserEntities(entities, 2)); <add> assertEqualityForInsertedEntities(entities); <ide> } <ide> <ide> @Test <ide> public void batch_insert_operation_works_for_two_full_batches_with_last_batch_not_full() { <del> testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4", "Ent5")); <add> final List<TgEntityWithManyPropTypes> entities = createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3", "Ent4", "Ent5"); <add> assertEquals(5, batchInserEntities(entities, 2)); <add> assertEqualityForInsertedEntities(entities); <ide> } <ide> <del> @Test(expected = EntityAlreadyExists.class) <add> @Test <ide> public void batch_insert_operation_fails_while_trying_to_insert_persisted_entities() { <del> testBatchInsertOfEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3")); <del> testBatchInsertOfEntities(getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model())); <add> batchInserEntities(createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3"), 2); <add> try { <add> batchInserEntities(getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()), 2); <add> fail("Expected an exception due to an attempt to insert already persisten entity."); <add> } catch (final EntityAlreadyExists ex) { <add> } <add> } <add> <add> @Test <add> public void batch_insert_a_stream_ignores_persistent_entities() { <add> final List<TgEntityWithManyPropTypes> fistBatch = createEntitiesForBatchInsert("Ent1", "Ent2", "Ent3"); <add> batchInserEntitiesAsStream(fistBatch.stream(), 2); <add> final List<TgEntityWithManyPropTypes> persistedFirstBatch = getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()); <add> final List<TgEntityWithManyPropTypes> secondBatch = createEntitiesForBatchInsert("Ent4", "Ent5"); <add> final List<TgEntityWithManyPropTypes> firstAndSecondBatches = Stream.concat(persistedFirstBatch.stream(), secondBatch.stream()).collect(toList()); <add> assertEquals(2, batchInserEntitiesAsStream(firstAndSecondBatches.stream(), 2)); <add> assertEqualityForInsertedEntities(firstAndSecondBatches); <ide> } <ide> <del> private void testBatchInsertOfEntities(final List<TgEntityWithManyPropTypes> entities) { <add> private int batchInserEntities(final List<TgEntityWithManyPropTypes> entities, final int batchSize) { <ide> final EntityBatchInsertOperation insertOp = new EntityBatchInsertOperation(getInstance(DomainMetadata.class), () -> getInstance(TransactionalExecution.class)); <del> assertEquals(entities.size(), insertOp.batchInsert(entities, 2)); <add> return insertOp.batchInsert(entities, batchSize); <add> } <add> <add> private int batchInserEntitiesAsStream(final Stream<TgEntityWithManyPropTypes> entities, final int batchSize) { <add> final EntityBatchInsertOperation insertOp = new EntityBatchInsertOperation(getInstance(DomainMetadata.class), () -> getInstance(TransactionalExecution.class)); <add> return insertOp.batchInsert(entities, batchSize); <add> } <add> <add> private void assertEqualityForInsertedEntities(final List<TgEntityWithManyPropTypes> entities) { <ide> final List<TgEntityWithManyPropTypes> savedEntities = getInstance(TgEntityWithManyPropTypesCo.class).getAllEntities(from(select(TgEntityWithManyPropTypes.class).model()).with(fetchAll(TgEntityWithManyPropTypes.class)).model()); <ide> assertEquals(entities, savedEntities); <ide> } <del> <add> <ide> private List<TgEntityWithManyPropTypes> createEntitiesForBatchInsert(final String ...entitiesKeys) { <ide> return asList(entitiesKeys).stream().map(e -> createEntityForBatchInsert(e)).collect(toList()); <ide> } <del> <add> <ide> private TgEntityWithManyPropTypes createEntityForBatchInsert(final String entityKey) { <ide> final UnionEntity unionEntityValue = co$(UnionEntity.class).new_(); <ide> unionEntityValue.setPropertyTwo(getInstance(IEntityTwo.class).findByKey(ENTITY_TWO_KEY));
Java
lgpl-2.1
ff0291311917d35f7f6eb00dc4eaca6ce7e3304c
0
nexusformat/code,chrisemblhh/nexus,chrisemblhh/nexus,nexusformat/code,chrisemblhh/nexus,nexusformat/code,nexusformat/code,chrisemblhh/nexus,nexusformat/code,chrisemblhh/nexus
package org.nexusformat; import java.util.HashMap; import java.util.Map; import java.util.Vector; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; class NXSnode implements TreeModel { private static final String PADDING = " "; private static final String SDS = "SDS"; private static final Logger LOG = Logger.getInstance(); private String name; private String nxclass; private Map<String, String> attrs; private Vector<NXSnode> children; private Vector<SVRLitem> svrl; NXSnode(final Node node) { this.nxclass = node.getNodeName(); this.attrs = new HashMap<String, String>(); this.setAttrs(node.getAttributes()); NodeList nodes = node.getChildNodes(); int size = nodes.getLength(); this.children = new Vector<NXSnode>(); for (int i = 0; i < size; i++) { this.addChild(nodes.item(i)); } this.svrl = new Vector<SVRLitem>(); } Vector<SVRLitem> addSVRL(final Node svrl) { // generate a list of xml error nodes Vector<Node> errors = new Vector<Node>(); addSVRL(svrl, errors); // convert it to java classes Vector<SVRLitem> items = new Vector<SVRLitem>(); for (Node node: errors) { items.add(new SVRLitem(node)); } // find the appropriate nodes to attach it to NXSnode nxsnode; for (SVRLitem item: items) { nxsnode = getNode(this, item.getLocationArray(), 1); nxsnode.svrl.add(item); } return items; } private static NXSnode getNode(NXSnode parent, Vector<String> location, int depth) { // chop up this part of the path to be useful if (location.size() <= depth) { return parent; } String partPath = location.get(depth); int left = partPath.indexOf("["); int right = partPath.indexOf("]", left); String name = partPath.substring(0, left); int index = Integer.parseInt(partPath.substring(left + 1, right)) - 1; LOG.debug("Looking for " + name + "[" + index + "]"); // get the options Vector<NXSnode> choices = new Vector<NXSnode>(); for (NXSnode child: parent.children) { if (equals(child.getType(), name)) { choices.add(child); } else if (equals(child.getName(), name)) { choices.add(child); } } // pick which one to return int numChoice = choices.size(); LOG.debug("Found " + numChoice + " options"); if ((numChoice <= 0) || (numChoice < index)){ return parent; } if (depth >= location.size()) { return choices.get(index); } else { return getNode(choices.get(index), location, depth + 1); } } private static boolean equals(final String left, final String right) { if (left == null) { return false; } if (right == null) { return false; } return left.equals(right); } private static void addSVRL(final Node node, final Vector<Node> errors) { if (SVRLitem.hasLocation(node)) { errors.add(node); return; } NodeList nodes = node.getChildNodes(); int size = nodes.getLength(); for (int i = 0; i < size; i++) { addSVRL(nodes.item(i), errors); } } private void setAttrs(final NamedNodeMap attrs) { if (attrs == null) { return; } int size = attrs.getLength(); Node attr; for (int i = 0; i < size; i++) { attr = attrs.item(i); this.setAttr(attr.getNodeName(), attr.getNodeValue()); } } void setAttr(final String name, final String value) { if (name.equals("name")) { this.name = value; } else if (name.equals("NAPItype")) { this.name = this.nxclass; this.nxclass = SDS; } else if (name.equals("target")) { this.name = this.nxclass; this.nxclass = null; this.attrs.put(name, value); } else { this.attrs.put(name, value); } } private void addChild(final Node node) { if (node == null) { return; } int type = node.getNodeType(); if (type != Node.ELEMENT_NODE) { return; } this.children.add(new NXSnode(node)); } String getName() { return this.name; } String getType() { return this.nxclass; } boolean hasError() { return (this.svrl.size() > 0); } public String toString() { String result = this.name + ":" + this.nxclass; if (this.hasError()) { return result + "*"; } else { return result; } } public void printTree() { this.printTree(""); } private void printTree(String padding) { System.out.println(padding + this.toString()); padding += PADDING; for (NXSnode node: this.children) { node.printTree(padding); } } public boolean equals(final Object other) { // do the simple checks if (this == other) return true; if (other == null) return false; if (!(other instanceof NXSnode)) return false; // cast and do deep comparison NXSnode temp = (NXSnode) other; if (!this.name.equals(temp.name)) return false; if (!this.nxclass.equals(temp.nxclass)) return false; if (!this.attrs.equals(temp.attrs)) return false; if (!this.children.equals(temp.children)) return false; if (!this.svrl.equals(temp.svrl)) return false; // this far must be ok return true; } private static NXSnode toNXSnode(final Object object) { if (object == null) { throw new Error("Cannot convert null object to NXSnode"); } if (!(object instanceof NXSnode)) { throw new Error("Cannot convert \"" + object + "\" to NXSnode"); } return (NXSnode) object; } // ---------------- TreeModel requirements @Override public void addTreeModelListener(TreeModelListener l) { // TODO Auto-generated method stub } public Object getChild(Object parent, int index) { NXSnode temp = toNXSnode(parent); return temp.children.get(index); } public int getChildCount(Object parent) { NXSnode temp = toNXSnode(parent); return temp.children.size(); } public int getIndexOfChild(Object parent, Object child) { if (parent == null) return -1; if (child == null) return -1; NXSnode myParent = toNXSnode(parent); NXSnode myChild = toNXSnode(child); return myParent.children.indexOf(myChild); } public Object getRoot() { return this; } public boolean isLeaf(Object node) { return (this.children.size() <= 0); } @Override public void removeTreeModelListener(TreeModelListener l) { // TODO Auto-generated method stub } @Override public void valueForPathChanged(TreePath path, Object newValue) { // TODO Auto-generated method stub } }
applications/NXconvertpy/org/nexusformat/NXSnode.java
package org.nexusformat; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; class NXSnode { private static final String PADDING = " "; private static final String SDS = "SDS"; private static final Logger LOG = Logger.getInstance(); private String name; private String nxclass; private Map<String, String> attrs; private Vector<NXSnode> children; private Vector<SVRLitem> svrl; NXSnode(final Node node) { this.nxclass = node.getNodeName(); this.attrs = new HashMap<String, String>(); this.setAttrs(node.getAttributes()); NodeList nodes = node.getChildNodes(); int size = nodes.getLength(); this.children = new Vector<NXSnode>(); for (int i = 0; i < size; i++) { this.addChild(nodes.item(i)); } this.svrl = new Vector<SVRLitem>(); } Vector<SVRLitem> addSVRL(final Node svrl) { // generate a list of xml error nodes Vector<Node> errors = new Vector<Node>(); addSVRL(svrl, errors); // convert it to java classes Vector<SVRLitem> items = new Vector<SVRLitem>(); for (Node node: errors) { items.add(new SVRLitem(node)); } // find the appropriate nodes to attach it to NXSnode nxsnode; for (SVRLitem item: items) { nxsnode = getNode(this, item.getLocationArray(), 1); nxsnode.svrl.add(item); } return items; } private static NXSnode getNode(NXSnode parent, Vector<String> location, int depth) { // chop up this part of the path to be useful if (location.size() <= depth) { return parent; } String partPath = location.get(depth); int left = partPath.indexOf("["); int right = partPath.indexOf("]", left); String name = partPath.substring(0, left); int index = Integer.parseInt(partPath.substring(left + 1, right)) - 1; LOG.debug("Looking for " + name + "[" + index + "]"); // get the options Vector<NXSnode> choices = new Vector<NXSnode>(); for (NXSnode child: parent.children) { if (equals(child.getType(), name)) { choices.add(child); } else if (equals(child.getName(), name)) { choices.add(child); } } // pick which one to return int numChoice = choices.size(); LOG.debug("Found " + numChoice + " options"); if ((numChoice <= 0) || (numChoice < index)){ return parent; } if (depth >= location.size()) { return choices.get(index); } else { return getNode(choices.get(index), location, depth + 1); } } private static boolean equals(final String left, final String right) { if (left == null) { return false; } if (right == null) { return false; } return left.equals(right); } private static void addSVRL(final Node node, final Vector<Node> errors) { if (SVRLitem.hasLocation(node)) { errors.add(node); return; } NodeList nodes = node.getChildNodes(); int size = nodes.getLength(); for (int i = 0; i < size; i++) { addSVRL(nodes.item(i), errors); } } private void setAttrs(final NamedNodeMap attrs) { if (attrs == null) { return; } int size = attrs.getLength(); Node attr; for (int i = 0; i < size; i++) { attr = attrs.item(i); this.setAttr(attr.getNodeName(), attr.getNodeValue()); } } void setAttr(final String name, final String value) { if (name.equals("name")) { this.name = value; } else if (name.equals("NAPItype")) { this.name = this.nxclass; this.nxclass = SDS; } else if (name.equals("target")) { this.name = this.nxclass; this.nxclass = null; this.attrs.put(name, value); } else { this.attrs.put(name, value); } } private void addChild(final Node node) { if (node == null) { return; } int type = node.getNodeType(); if (type != Node.ELEMENT_NODE) { return; } this.children.add(new NXSnode(node)); } String getName() { return this.name; } String getType() { return this.nxclass; } boolean hasError() { return (this.svrl.size() > 0); } public String toString() { String result = this.name + ":" + this.nxclass; if (this.hasError()) { return result + "*"; } else { return result; } } public void printTree() { this.printTree(""); } private void printTree(String padding) { System.out.println(padding + this.toString()); padding += PADDING; for (NXSnode node: this.children) { node.printTree(padding); } } }
Added TreeModel requirements. Refs #179. git-svn-id: 1001b6e0dd469eaa302a741812f7f5d223cf35f7@1356 ff5d1e40-2be0-497f-93bd-dc18237bd3c7
applications/NXconvertpy/org/nexusformat/NXSnode.java
Added TreeModel requirements. Refs #179.
<ide><path>pplications/NXconvertpy/org/nexusformat/NXSnode.java <ide> import java.util.Map; <ide> import java.util.Vector; <ide> <add>import javax.swing.event.TreeModelListener; <add>import javax.swing.tree.TreeModel; <add>import javax.swing.tree.TreePath; <add> <ide> import org.w3c.dom.NamedNodeMap; <ide> import org.w3c.dom.Node; <ide> import org.w3c.dom.NodeList; <ide> <del>class NXSnode { <add>class NXSnode implements TreeModel { <ide> private static final String PADDING = " "; <ide> private static final String SDS = "SDS"; <ide> private static final Logger LOG = Logger.getInstance(); <ide> node.printTree(padding); <ide> } <ide> } <add> <add> public boolean equals(final Object other) { <add> // do the simple checks <add> if (this == other) <add> return true; <add> if (other == null) <add> return false; <add> if (!(other instanceof NXSnode)) <add> return false; <add> <add> // cast and do deep comparison <add> NXSnode temp = (NXSnode) other; <add> if (!this.name.equals(temp.name)) <add> return false; <add> if (!this.nxclass.equals(temp.nxclass)) <add> return false; <add> if (!this.attrs.equals(temp.attrs)) <add> return false; <add> if (!this.children.equals(temp.children)) <add> return false; <add> if (!this.svrl.equals(temp.svrl)) <add> return false; <add> <add> // this far must be ok <add> return true; <add> } <add> <add> private static NXSnode toNXSnode(final Object object) { <add> if (object == null) { <add> throw new Error("Cannot convert null object to NXSnode"); <add> } <add> if (!(object instanceof NXSnode)) { <add> throw new Error("Cannot convert \"" + object + "\" to NXSnode"); <add> } <add> return (NXSnode) object; <add> } <add> <add> // ---------------- TreeModel requirements <add> @Override <add> public void addTreeModelListener(TreeModelListener l) { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> public Object getChild(Object parent, int index) { <add> NXSnode temp = toNXSnode(parent); <add> return temp.children.get(index); <add> } <add> <add> public int getChildCount(Object parent) { <add> NXSnode temp = toNXSnode(parent); <add> return temp.children.size(); <add> } <add> <add> public int getIndexOfChild(Object parent, Object child) { <add> if (parent == null) <add> return -1; <add> if (child == null) <add> return -1; <add> NXSnode myParent = toNXSnode(parent); <add> NXSnode myChild = toNXSnode(child); <add> <add> return myParent.children.indexOf(myChild); <add> } <add> <add> public Object getRoot() { <add> return this; <add> } <add> <add> public boolean isLeaf(Object node) { <add> return (this.children.size() <= 0); <add> } <add> <add> @Override <add> public void removeTreeModelListener(TreeModelListener l) { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> @Override <add> public void valueForPathChanged(TreePath path, Object newValue) { <add> // TODO Auto-generated method stub <add> <add> } <ide> }
Java
mit
b8f2f886cc9304ac2dcbe80881957068a96267ec
0
navalev/azure-sdk-for-java,pomortaz/azure-sdk-for-java,hovsepm/azure-sdk-for-java,avranju/azure-sdk-for-java,selvasingh/azure-sdk-for-java,selvasingh/azure-sdk-for-java,southworkscom/azure-sdk-for-java,oaastest/azure-sdk-for-java,herveyw/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,herveyw/azure-sdk-for-java,navalev/azure-sdk-for-java,jmspring/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,pomortaz/azure-sdk-for-java,ElliottMiller/azure-sdk-for-java,hovsepm/azure-sdk-for-java,ElliottMiller/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,jingleheimerschmidt/azure-sdk-for-java,jalves94/azure-sdk-for-java,pomortaz/azure-sdk-for-java,devigned/azure-sdk-for-java,oaastest/azure-sdk-for-java,devigned/azure-sdk-for-java,navalev/azure-sdk-for-java,navalev/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,herveyw/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,jalves94/azure-sdk-for-java,jalves94/azure-sdk-for-java,manikandan-palaniappan/azure-sdk-for-java,Azure/azure-sdk-for-java,manikandan-palaniappan/azure-sdk-for-java,hovsepm/azure-sdk-for-java,Azure/azure-sdk-for-java,hovsepm/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,jalves94/azure-sdk-for-java,jingleheimerschmidt/azure-sdk-for-java,Azure/azure-sdk-for-java,southworkscom/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,flydream2046/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,avranju/azure-sdk-for-java,hovsepm/azure-sdk-for-java,selvasingh/azure-sdk-for-java,herveyw/azure-sdk-for-java,pomortaz/azure-sdk-for-java,flydream2046/azure-sdk-for-java,jmspring/azure-sdk-for-java,navalev/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,martinsawicki/azure-sdk-for-java
/** * Copyright 2011 Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.windowsazure.services.blob.client; import java.net.URI; import java.util.Date; /** * Represents the attributes of a copy operation. * */ public final class CopyState { /** * Holds the name of the container. */ private String copyId; /** * Holds the time the copy operation completed, whether completion was due to a successful copy, abortion, or a * failure. */ private Date completionTime; /** * Holds the status of the copy operation. */ private CopyStatus status; /** * Holds the source URI of a copy operation. */ private URI source; /** * Holds the number of bytes copied in the operation so far. */ private Long bytesCopied; /** * Holds the total number of bytes in the source of the copy. */ private Long totalBytes; /** * Holds the description of the current status. */ private String statusDescription; /** * Initializes a new instance of the CopyState class. */ public CopyState() { } /** * Gets the name of the container. * * @return A string containing the name of the container. */ public String getCopyId() { return this.copyId; } /** * Gets the time that the copy operation completed. * * @return The time that the copy operation completed. */ public Date getCompletionTime() { return this.completionTime; } /** * Gets the status of the copy operation. * * @return A <code>CopyStatus</code> object representing the status of the copy operation. */ public CopyStatus getStatus() { return this.status; } /** * Gets the source URI of the copy operation. * * @return The source URI of the copy operation in a string. */ public URI getSource() { return this.source; } /** * Gets the number of bytes copied in the operation so far. * * @return The number of bytes copied so far. */ public Long getBytesCopied() { return this.bytesCopied; } public Long getTotalBytes() { return this.totalBytes; } /** * Gets the status description of the copy operation. * * @return A string containing the status description. */ public String getStatusDescription() { return this.statusDescription; } /** * Sets the name of the container. * * @param copyId * The name of the container to set. * */ public void setCopyId(final String copyId) { this.copyId = copyId; } /** * Sets the time that the copy operation completed. * * @param completionTime * The completion time to set. */ public void setCompletionTime(final Date completionTime) { this.completionTime = completionTime; } /** * Sets the status of the copy operation. * * @param status * The copy operation status to set, as a <code>CopyStatus</code> object. */ public void setStatus(final CopyStatus status) { this.status = status; } /** * Sets the source URI of the copy operation. * * @param source * The source URI to set. */ public void setSource(final URI source) { this.source = source; } /** * Sets the number of bytes copied so far. * * @param bytesCopied * The number of bytes copied to set. */ public void setBytesCopied(final Long bytesCopied) { this.bytesCopied = bytesCopied; } /** * Sets the total number of bytes in the source to copy. * * @param totalBytes * The number of bytes to set. */ public void setTotalBytes(final Long totalBytes) { this.totalBytes = totalBytes; } /** * Sets the current status of the copy operation. * * @param statusDescription * The current status to set. */ public void setStatusDescription(final String statusDescription) { this.statusDescription = statusDescription; } }
microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyState.java
/** * Copyright 2011 Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.windowsazure.services.blob.client; import java.net.URI; import java.util.Date; /** * Represents the attributes of a copy operation. * */ public final class CopyState { /** * Holds the Name of the Container */ private String copyId; /** * Holds the time the copy operation completed, whether completion was due to a successful copy, abortion, or a * failure. */ private Date completionTime; /** * Holds the status of the copy operation. */ private CopyStatus status; /** * Holds the source URI of a copy operation. */ private URI source; /** * Holds the number of bytes copied in the operation so far. */ private Long bytesCopied; /** * Holds the total number of bytes in the source of the copy. */ private Long totalBytes; /** * Holds the description of the current status. */ private String statusDescription; /** * Initializes a new instance of the CopyState class */ public CopyState() { } public String getCopyId() { return this.copyId; } public Date getCompletionTime() { return this.completionTime; } public CopyStatus getStatus() { return this.status; } public URI getSource() { return this.source; } public Long getBytesCopied() { return this.bytesCopied; } public Long getTotalBytes() { return this.totalBytes; } public String getStatusDescription() { return this.statusDescription; } public void setCopyId(final String copyId) { this.copyId = copyId; } public void setCompletionTime(final Date completionTime) { this.completionTime = completionTime; } public void setStatus(final CopyStatus status) { this.status = status; } public void setSource(final URI source) { this.source = source; } public void setBytesCopied(final Long bytesCopied) { this.bytesCopied = bytesCopied; } public void setTotalBytes(final Long totalBytes) { this.totalBytes = totalBytes; } public void setStatusDescription(final String statusDescription) { this.statusDescription = statusDescription; } }
Updated API docs
microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyState.java
Updated API docs
<ide><path>icrosoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyState.java <ide> */ <ide> public final class CopyState { <ide> /** <del> * Holds the Name of the Container <add> * Holds the name of the container. <ide> */ <ide> private String copyId; <ide> <ide> private String statusDescription; <ide> <ide> /** <del> * Initializes a new instance of the CopyState class <add> * Initializes a new instance of the CopyState class. <ide> */ <ide> public CopyState() { <ide> } <ide> <add> /** <add> * Gets the name of the container. <add> * <add> * @return A string containing the name of the container. <add> */ <ide> public String getCopyId() { <ide> return this.copyId; <ide> } <ide> <add> /** <add> * Gets the time that the copy operation completed. <add> * <add> * @return The time that the copy operation completed. <add> */ <ide> public Date getCompletionTime() { <ide> return this.completionTime; <ide> } <ide> <add> /** <add> * Gets the status of the copy operation. <add> * <add> * @return A <code>CopyStatus</code> object representing the status of the copy operation. <add> */ <ide> public CopyStatus getStatus() { <ide> return this.status; <ide> } <ide> <add> /** <add> * Gets the source URI of the copy operation. <add> * <add> * @return The source URI of the copy operation in a string. <add> */ <ide> public URI getSource() { <ide> return this.source; <ide> } <ide> <add> /** <add> * Gets the number of bytes copied in the operation so far. <add> * <add> * @return The number of bytes copied so far. <add> */ <ide> public Long getBytesCopied() { <ide> return this.bytesCopied; <ide> } <ide> return this.totalBytes; <ide> } <ide> <add> /** <add> * Gets the status description of the copy operation. <add> * <add> * @return A string containing the status description. <add> */ <ide> public String getStatusDescription() { <ide> return this.statusDescription; <ide> } <ide> <add> /** <add> * Sets the name of the container. <add> * <add> * @param copyId <add> * The name of the container to set. <add> * <add> */ <ide> public void setCopyId(final String copyId) { <ide> this.copyId = copyId; <ide> } <ide> <add> /** <add> * Sets the time that the copy operation completed. <add> * <add> * @param completionTime <add> * The completion time to set. <add> */ <ide> public void setCompletionTime(final Date completionTime) { <ide> this.completionTime = completionTime; <ide> } <ide> <add> /** <add> * Sets the status of the copy operation. <add> * <add> * @param status <add> * The copy operation status to set, as a <code>CopyStatus</code> object. <add> */ <ide> public void setStatus(final CopyStatus status) { <ide> this.status = status; <ide> } <ide> <add> /** <add> * Sets the source URI of the copy operation. <add> * <add> * @param source <add> * The source URI to set. <add> */ <ide> public void setSource(final URI source) { <ide> this.source = source; <ide> } <ide> <add> /** <add> * Sets the number of bytes copied so far. <add> * <add> * @param bytesCopied <add> * The number of bytes copied to set. <add> */ <ide> public void setBytesCopied(final Long bytesCopied) { <ide> this.bytesCopied = bytesCopied; <ide> } <ide> <add> /** <add> * Sets the total number of bytes in the source to copy. <add> * <add> * @param totalBytes <add> * The number of bytes to set. <add> */ <ide> public void setTotalBytes(final Long totalBytes) { <ide> this.totalBytes = totalBytes; <ide> } <ide> <add> /** <add> * Sets the current status of the copy operation. <add> * <add> * @param statusDescription <add> * The current status to set. <add> */ <ide> public void setStatusDescription(final String statusDescription) { <ide> this.statusDescription = statusDescription; <ide> }
JavaScript
mit
dc334131b4244778aef9583e4d10f25d874a7c06
0
stoyanova-sm/epam-calendar,stoyanova-sm/epam-calendar
import '../data/tasksObject.json'; export default class Calendar { constructor() { this.displayDate = new Date(); this.calendarMap = []; }; initialize() { //draw the calendar and add events to switch months this.setEvents(); this.draw(); }; setEvents() { //add events to switch months by clicking arrow buttons ///TODO: change <a> to <button> document.querySelector('.back').addEventListener('click', () => this.switchMonth(true)); document.querySelector('.forward').addEventListener('click', () => this.switchMonth(false)); }; switchMonth(direction) { if(direction) { this.displayDate.setMonth(this.displayDate.getMonth() - 1); } else { this.displayDate.setMonth(this.displayDate.getMonth() + 1); } this.draw(); }; draw() { this.setHeader(); this.generateDates(); this.renderTasks(); }; setHeader() { const header = document.querySelector('.calendar-header'); const options = { year: 'numeric', month: 'long' } const monthAndYear = this.displayDate.toLocaleString('en-EN', options); header.innerText = monthAndYear; }; generateDates() { const firstDateToDisplay = new Date(this.displayDate.getTime()); let firstWeekdayOfMonth; const monthLength = new Date(firstDateToDisplay.getFullYear(), firstDateToDisplay.getMonth()+1, 0).getDate(); firstDateToDisplay.setHours(0,0,0,0);// in json we get time in milliseconds for faster comparison firstDateToDisplay.setDate(1); // If Monday is the first day of the Month firstWeekdayOfMonth = firstDateToDisplay.getDay(); if (firstWeekdayOfMonth === 6 && monthLength === 31) { // If Saturday is the first date firstDateToDisplay.setDate(3); } else if (firstWeekdayOfMonth === 0 && monthLength >= 30) { // If Sunday is the first date firstDateToDisplay.setDate(2); } else if (firstWeekdayOfMonth !== 1) { // If not Monday this.setLastMondayOfPreviousMonth(firstDateToDisplay); } for(let i = 0; i < 35; i++) { const dateObj = new Date(firstDateToDisplay.getTime()); const date = dateObj.getDate(); const dateTime = dateObj.getTime();// in json we get time in milliseconds for faster comparison const tasks = []; this.calendarMap.push({dateObj, dateTime, date, tasks}); firstDateToDisplay.setDate(date + 1); } console.log(this.calendarMap) }; setLastMondayOfPreviousMonth(date) { //returns Date() with the date of last monday of previous month date.setDate(0); // last day of previous month const lastMondayOfPreviousMonth = date.getDate() - (date.getDay() - 1); date.setDate(lastMondayOfPreviousMonth); }; renderTasks() { ///TODO: add catch errors, json() fetch('/build/data/tasksObject.json') .then(response => { if(response.status === 200) { return response.json(); } }) .then(tasksList => this.updateCalendarMap(tasksList)) .then(() => this.render()); }; updateCalendarMap(tasksByDates) { for(const tasksByDate of tasksByDates) { // check if time in each day in calendar equals to time //in every object, we received from server and returns this object from calendarMap const calendarDate = this.calendarMap.find(calendarMapDay => calendarMapDay.dateTime === tasksByDate.dateTime); if (calendarDate) { calendarDate.tasks = tasksByDate.tasks; console.log(calendarDate); } } }; render() { const calendarHtml = []; const calendar = document.querySelector('.net'); for(const element of this.calendarMap) { this.calcTaskDurationForHtml(element); const template = ` <div class="day-wrapper"> <div class="day"> <div class="date">${element.date}</div> <div class="tasks">${this.getTasksHtml(element)}</div> </div> </div>`; calendarHtml.push(template); } calendar.innerHTML = calendarHtml.join(''); //combine the array of templates into a string }; calcTaskDurationForHtml(element) { if (element.tasks.length !== 0) { let taskStartDay = element.dateObj.getDay();//the day of the week the task starts if (taskStartDay === 0) taskStartDay = 7; //if sunday for (let i = element.tasks.length-1; i >= 0; i--) { // needed for proper task ordering (fist in first out) const taskSize = element.tasks[i].duration + taskStartDay;// task start day + task duration if (taskSize > 8) { const restOfTaskDuration = taskSize - 8;//the rest of the task days, that we transfer to the next week element.tasks[i].duration = element.tasks[i].duration - restOfTaskDuration; //task duration on current week const restOfTaskObj = { // object with the rest part of the task color: element.tasks[i].color, duration: restOfTaskDuration, text: element.tasks[i].text }; const elementIndex = this.calendarMap.indexOf(element); this.calendarMap[elementIndex + element.tasks[i].duration].tasks.unshift(restOfTaskObj) } } } } getTasksHtml(element) { const htmlOutput = []; const tasksLength = element.tasks.length; const task = element.tasks; if (!tasksLength) { //if no task do nothing return ''; } for (let i = 0; i < tasksLength; i++) { //go through the tasks in array if(i === 4 && tasksLength > 5) { htmlOutput.push( `<div class="task task-duration-1 task-more"> <div class="task-contents"> <a href="#">${tasksLength - 4} more items</a> </div> </div>` ); } htmlOutput.push( `<div class="task task-duration-${task[i].duration} task-color-${task[i].color}"> <div class="task-label"></div> <div class="task-contents"> <a href="#">${task[i].text}</a> </div> </div>` ); } return htmlOutput.join(''); } };
application/js/calendar.js
import '../data/tasksObject.json'; export default class Calendar { constructor() { this.displayDate = new Date(); this.calendarMap = []; }; initialize() { //draw the calendar and add events to switch months this.setEvents(); this.draw(); }; setEvents() { //add events to switch months by clicking arrow buttons ///TODO: change <a> to <button> document.querySelector('.back').addEventListener('click', () => this.switchMonth(true)); document.querySelector('.forward').addEventListener('click', () => this.switchMonth(false)); }; switchMonth(direction) { if(direction) { this.displayDate.setMonth(this.displayDate.getMonth() - 1); } else { this.displayDate.setMonth(this.displayDate.getMonth() + 1); } this.draw(); }; draw() { this.setHeader(); this.generateDates(); this.requestTasks(); }; setHeader() { const header = document.querySelector('.calendar-header'); const options = { year: 'numeric', month: 'long' } const monthAndYear = this.displayDate.toLocaleString('en-EN', options); header.innerText = monthAndYear; }; generateDates() { const firstDateToDisplay = new Date(this.displayDate.getTime()); let firstWeekdayOfMonth; const monthLength = new Date(firstDateToDisplay.getFullYear(), firstDateToDisplay.getMonth()+1, 0).getDate(); firstDateToDisplay.setHours(0,0,0,0);///TODO: think about this firstDateToDisplay.setDate(1); // If Monday is the first day of the Month firstWeekdayOfMonth = firstDateToDisplay.getDay(); if (firstWeekdayOfMonth === 6 && monthLength === 31) { // If Saturday is the first date firstDateToDisplay.setDate(3); } else if (firstWeekdayOfMonth === 0 && monthLength >= 30) { // If Sunday is the first date firstDateToDisplay.setDate(2); } else if (firstWeekdayOfMonth !== 1) { // If not Monday this.setLastMondayOfPreviousMonth(firstDateToDisplay); } for(let i = 0; i < 35; i++) { const dateObj = new Date(firstDateToDisplay.getTime()); const date = dateObj.getDate(); const dateTime = dateObj.getTime();///TODO: think about this this.calendarMap.push({dateObj, dateTime, date}); firstDateToDisplay.setDate(date + 1); } }; setLastMondayOfPreviousMonth(date) { //returns Date() with the date of last monday of previous month date.setDate(0); // last day of previous month const lastMondayOfPreviousMonth = date.getDate() - (date.getDay() - 1); date.setDate(lastMondayOfPreviousMonth); }; requestTasks() { ///TODO: add catch errors, json() fetch('/build/data/tasksObject.json') .then(response => { if(response.status === 200) { return response.json(); } }) .then(tasksList => this.updateCalendarMap(tasksList)) .then(() => this.render()); }; updateCalendarMap(tasksByDates) { for(const tasksByDate of tasksByDates) { // check if time in each day in calendar equals to time //in every object, we received from server and returns this object from calendarMap const calendarDate = this.calendarMap.find(calendarMapDay => calendarMapDay.dateTime === tasksByDate.dateTime); if (calendarDate) { calendarDate.tasks = tasksByDate.tasks; } } }; render() { const calendarHtml = []; const calendar = document.querySelector('.net'); for(const element of this.calendarMap) { const template = ` <div class="day-wrapper"> <div class="day"> <div class="date">${element.date}</div> <div class="tasks">${this.getTasksHtml(element)}</div> </div> </div>`; calendarHtml.push(template); } calendar.innerHTML = calendarHtml.join(''); //combine the array of templates into a string }; getTasksHtml(element) { const htmlOutput = []; if (!element.tasks) { //if no task do nothing return ''; } const tasksLength = element.tasks.length; const task = element.tasks; for (let i = 0; i < tasksLength; i++) { //go through the tasks in array if(i === 4 && tasksLength > 5) { htmlOutput.push( `<div class="task task-duration-1 task-more"> <div class="task-contents"> <a href="#">${tasksLength - 4} more items</a> </div> </div>` ); } htmlOutput.push( `<div class="task task-duration-${task[i].duration} task-color-${task[i].color}"> <div class="task-label"></div> <div class="task-contents"> <a href="#">${task[i].text}</a> </div> </div>` ); } this.calcDurationHtml(); return htmlOutput.join(''); } calcDurationHtml() { console.log(this.calendarMap); for(let i = 0; i < 35; i++) { let a = this.calendarMap[1].dateObj.getDay(); console.log(a); for (const tasks of this.calendarMap) { } } } };
added a function to transfer tasks for the next week
application/js/calendar.js
added a function to transfer tasks for the next week
<ide><path>pplication/js/calendar.js <ide> draw() { <ide> this.setHeader(); <ide> this.generateDates(); <del> this.requestTasks(); <add> this.renderTasks(); <ide> }; <ide> <ide> setHeader() { <ide> let firstWeekdayOfMonth; <ide> const monthLength = new Date(firstDateToDisplay.getFullYear(), firstDateToDisplay.getMonth()+1, 0).getDate(); <ide> <del> firstDateToDisplay.setHours(0,0,0,0);///TODO: think about this <add> firstDateToDisplay.setHours(0,0,0,0);// in json we get time in milliseconds for faster comparison <ide> firstDateToDisplay.setDate(1); // If Monday is the first day of the Month <ide> firstWeekdayOfMonth = firstDateToDisplay.getDay(); <ide> <ide> for(let i = 0; i < 35; i++) { <ide> const dateObj = new Date(firstDateToDisplay.getTime()); <ide> const date = dateObj.getDate(); <del> const dateTime = dateObj.getTime();///TODO: think about this <add> const dateTime = dateObj.getTime();// in json we get time in milliseconds for faster comparison <add> const tasks = []; <ide> <del> this.calendarMap.push({dateObj, dateTime, date}); <add> this.calendarMap.push({dateObj, dateTime, date, tasks}); <ide> firstDateToDisplay.setDate(date + 1); <ide> } <add> console.log(this.calendarMap) <ide> }; <ide> <ide> setLastMondayOfPreviousMonth(date) { //returns Date() with the date of last monday of previous month <ide> date.setDate(lastMondayOfPreviousMonth); <ide> }; <ide> <del> requestTasks() { ///TODO: add catch errors, json() <add> renderTasks() { ///TODO: add catch errors, json() <ide> fetch('/build/data/tasksObject.json') <ide> .then(response => { <ide> if(response.status === 200) { <ide> const calendarDate = this.calendarMap.find(calendarMapDay => calendarMapDay.dateTime === tasksByDate.dateTime); <ide> if (calendarDate) { <ide> calendarDate.tasks = tasksByDate.tasks; <add> console.log(calendarDate); <ide> } <ide> } <ide> }; <ide> const calendar = document.querySelector('.net'); <ide> <ide> for(const element of this.calendarMap) { <add> this.calcTaskDurationForHtml(element); <add> <ide> const template = ` <ide> <div class="day-wrapper"> <ide> <div class="day"> <ide> calendar.innerHTML = calendarHtml.join(''); //combine the array of templates into a string <ide> }; <ide> <add> calcTaskDurationForHtml(element) { <add> if (element.tasks.length !== 0) { <add> let taskStartDay = element.dateObj.getDay();//the day of the week the task starts <add> if (taskStartDay === 0) taskStartDay = 7; //if sunday <add> <add> for (let i = element.tasks.length-1; i >= 0; i--) { // needed for proper task ordering (fist in first out) <add> const taskSize = element.tasks[i].duration + taskStartDay;// task start day + task duration <add> if (taskSize > 8) { <add> const restOfTaskDuration = taskSize - 8;//the rest of the task days, that we transfer to the next week <add> element.tasks[i].duration = element.tasks[i].duration - restOfTaskDuration; //task duration on current week <add> <add> const restOfTaskObj = { // object with the rest part of the task <add> color: element.tasks[i].color, <add> duration: restOfTaskDuration, <add> text: element.tasks[i].text <add> }; <add> const elementIndex = this.calendarMap.indexOf(element); <add> this.calendarMap[elementIndex + element.tasks[i].duration].tasks.unshift(restOfTaskObj) <add> } <add> } <add> } <add> } <add> <ide> getTasksHtml(element) { <add> <ide> const htmlOutput = []; <add> const tasksLength = element.tasks.length; <add> const task = element.tasks; <ide> <del> if (!element.tasks) { //if no task do nothing <add> if (!tasksLength) { //if no task do nothing <ide> return ''; <ide> } <ide> <del> const tasksLength = element.tasks.length; <del> const task = element.tasks; <ide> for (let i = 0; i < tasksLength; i++) { //go through the tasks in array <ide> if(i === 4 && tasksLength > 5) { <ide> htmlOutput.push( <ide> </div>` <ide> ); <ide> } <del> this.calcDurationHtml(); <add> <ide> return htmlOutput.join(''); <del> } <del> <del> calcDurationHtml() { <del> console.log(this.calendarMap); <del> for(let i = 0; i < 35; i++) { <del> let a = this.calendarMap[1].dateObj.getDay(); <del> console.log(a); <del> for (const tasks of this.calendarMap) { <del> <del> } <del> } <del> <ide> } <ide> }; <ide>
JavaScript
mit
c5a12a8b46cc2323dd81d2881a50d81ae720cac7
0
yaoshanliang/TypiCMS,omusico/TypiCMS,sdebacker/TypiCMS,sachintaware/TypiCMS,sdebacker/TypiCMS,yaoshanliang/TypiCMS,omusico/TypiCMS,yaoshanliang/TypiCMS,sachintaware/TypiCMS,elk1997/TypiCMS,omusico/TypiCMS,elk1997/TypiCMS,sdebacker/TypiCMS,sachintaware/TypiCMS
function enableSortable() { // Sorting avec imbrication var sortableList = $('.sortable'), maxLevels = 1, isTree = false, handle = 'div', placeholder = 'placeholder', toleranceElement = '> div', items = 'li', url = document.URL.split('?')[0] + '/sort'; if (sortableList.hasClass('nested')) { maxLevels = 3; isTree = true; sortableList.find('li > div').prepend('<span class="disclose"></span>'); } if (sortableList.hasClass('sortable-thumbnails')) { handle = 'img'; items = 'a'; placeholder = false; toleranceElement = false; url = '/admin/files/sort'; } var sortableOptions = { forcePlaceholderSize: true, handle: handle, cancel: 'input, .label, .attachments a, .mjs-nestedSortable-branch .disclose', helper: 'clone', // distance: 2, items: items, opacity: .6, placeholder: placeholder, revert: 250, tabSize: 25, tolerance: 'pointer', toleranceElement: toleranceElement, maxLevels: maxLevels, listType: 'ul', isTree: isTree, expandOnHover: 700, startCollapsed: false, update: function(event, ui) { var serializedDatas = sortableList.sortable('serialize'), elementId = ui.item.attr('id').split(/[_]+/).pop(); if (isTree) { serializedDatas += '&nested=true&moved=' + elementId; } // console.log(serializedDatas); $.ajax({ type: 'POST', url: url, data: serializedDatas }).fail(function () { alertify.error(translate('An error occurred')); }); } }; if (isTree) { sortableList.nestedSortable(sortableOptions); } else { sortableList.sortable(sortableOptions); } } /** * Ajaxifier les listes (delete, online, offline) */ function initListForm() { // console.log('initListForm'); // Set buttons var listForm = $('.list-form'), contentLocale = listForm.attr('lang'), switches = $('.list-form').find('.switch').css('cursor', 'pointer'), btnToolbar = listForm.children('.btn-toolbar'), buttonGroup = $('<div>', { class: 'btn-group' }); buttonGroup.prependTo(btnToolbar); btnToolbar.append('<div class="btn-group"><button class="btn btn-danger btn-xs" id="btnDelete">Supprimer</button></div>'); if ($('.list-form .switch').length) { buttonGroup.append('<button class="btn btn-default btn-xs" id="btnOnline">En ligne</button>'); buttonGroup.append('<button class="btn btn-default btn-xs" id="btnOffline">Hors ligne</button>'); }; var btnDelete = $('#btnDelete'), btnOnline = $('#btnOnline'), btnOffline = $('#btnOffline'), nbElementItem = $('#nb_elements'); // Enable delete button btnDelete.click(function(){ var checkedCheckboxes = listForm.find(':checkbox:checked'), nombreElementsTraites = 0, nombreElementsSelectionnes = checkedCheckboxes.length; // Build confirm string confirmString = translate('Delete') + ' ' + nombreElementsSelectionnes.toString() + ' ' + translate('item'); if (nombreElementsSelectionnes > 1) confirmString += 's'; confirmString += '?'; if (confirm(confirmString)) { checkedCheckboxes.each(function(){ var id = $(this).val(); $.ajax({ type: 'DELETE', url: document.URL.split('?')[0] + '/' + id }).done(function(){ $('#item_' + id).slideUp('fast', function () { var nbElements = nbElementItem.html(); nbElementItem.html(nbElements-1); $(this).remove(); nombreElementsTraites++; if (nombreElementsSelectionnes == nombreElementsTraites) { alertify.success(nombreElementsSelectionnes + ' items deleted.'); } }); }).fail(function(){ alertify.error(translate('An error occurred')); }); }); } }); // Enable online button switches.click(function(){ var item = $(this).closest('li'), status = item.hasClass('online') ? 'online' : 'offline' , newStatus = item.hasClass('online') ? 'offline' : 'online' , newStatusValue = item.hasClass('online') ? 0 : 1 , id = $(this).parent().children(':checkbox').val(), data = {}; data['id'] = id; data[contentLocale] = {'status' : newStatusValue}; $('#item_' + id).removeClass(status).addClass(newStatus); $.ajax({ type: 'PATCH', url: document.URL.split('?')[0] + '/' + id, data: data }).done(function(){ alertify.success('Item set ' + newStatus + '.'); }).fail(function(){ alertify.error('Item couldn’t be set ' + newStatus + '.'); }); }); // Enable online button btnOnline.click(function(){ var checkedCheckboxes = listForm.find(':checkbox:checked'), nombreElementsTraites = 0, nombreElementsSelectionnes = checkedCheckboxes.length; checkedCheckboxes.each(function(){ var id = $(this).val(), data = {}; data['id'] = id; data[contentLocale] = {'status' : 1}; $.ajax({ type: 'PATCH', url: document.URL.split('?')[0] + '/' + id, data: data }).done(function(){ $('#item_' + id).removeClass('offline').addClass('online').find(':checkbox').prop({'checked':false}); nombreElementsTraites++; if (nombreElementsSelectionnes == nombreElementsTraites) { alertify.success(nombreElementsSelectionnes + ' items set online.'); } }).fail(function(){ alertify.error('Item couldn’t be set online.'); }); }); }); // Enable offline button btnOffline.click(function(){ var checkedCheckboxes = listForm.find(':checkbox:checked'), nombreElementsTraites = 0, nombreElementsSelectionnes = checkedCheckboxes.length; checkedCheckboxes.each(function(){ var id = $(this).val(), data = {}; data['id'] = id; data[contentLocale] = {'status' : 0}; $.ajax({ type: 'PATCH', url: document.URL.split('?')[0] + '/' + id, data: data }).done(function(){ $('#item_' + id).removeClass('online').addClass('offline').find(':checkbox').prop({'checked':false}); nombreElementsTraites++; if (nombreElementsSelectionnes == nombreElementsTraites) { alertify.success(nombreElementsSelectionnes + ' items set offline.'); } }).fail(function(){ alertify.error('Item couldn’t be set offline.'); }); }); }); } !function( $ ){ "use strict"; $(function () { enableSortable(); $('.list-main.nested').nestedCookie(); initListForm(); $('.list-form').listEnhancer({ done: function(data) { reloadPage(); }, error: function() { reloadPage(); } }); }); }( window.jQuery || window.ender );
public/js/list.js
function enableSortable() { // Sorting avec imbrication var sortableList = $('.sortable'), maxLevels = 1, isTree = false, handle = 'div', placeholder = 'placeholder', toleranceElement = '> div', items = 'li', url = document.URL.split('?')[0] + '/sort'; if (sortableList.hasClass('nested')) { maxLevels = 3; isTree = true; sortableList.find('li div').prepend('<span class="disclose"></span>'); } if (sortableList.hasClass('sortable-thumbnails')) { handle = 'img'; items = 'a'; placeholder = false; toleranceElement = false; url = '/admin/files/sort'; } var sortableOptions = { forcePlaceholderSize: true, handle: handle, cancel: 'input, .label, .attachments a, .mjs-nestedSortable-branch .disclose', helper: 'clone', // distance: 2, items: items, opacity: .6, placeholder: placeholder, revert: 250, tabSize: 25, tolerance: 'pointer', toleranceElement: toleranceElement, maxLevels: maxLevels, listType: 'ul', isTree: isTree, expandOnHover: 700, startCollapsed: false, update: function(event, ui) { var serializedDatas = sortableList.sortable('serialize'), elementId = ui.item.attr('id').split(/[_]+/).pop(); if (isTree) { serializedDatas += '&nested=true&moved=' + elementId; } // console.log(serializedDatas); $.ajax({ type: 'POST', url: url, data: serializedDatas }).fail(function () { alertify.error(translate('An error occurred')); }); } }; if (isTree) { sortableList.nestedSortable(sortableOptions); } else { sortableList.sortable(sortableOptions); } } /** * Ajaxifier les listes (delete, online, offline) */ function initListForm() { // console.log('initListForm'); // Set buttons var listForm = $('.list-form'), contentLocale = listForm.attr('lang'), switches = $('.list-form').find('.switch').css('cursor', 'pointer'), btnToolbar = listForm.children('.btn-toolbar'), buttonGroup = $('<div>', { class: 'btn-group' }); buttonGroup.prependTo(btnToolbar); btnToolbar.append('<div class="btn-group"><button class="btn btn-danger btn-xs" id="btnDelete">Supprimer</button></div>'); if ($('.list-form .switch').length) { buttonGroup.append('<button class="btn btn-default btn-xs" id="btnOnline">En ligne</button>'); buttonGroup.append('<button class="btn btn-default btn-xs" id="btnOffline">Hors ligne</button>'); }; var btnDelete = $('#btnDelete'), btnOnline = $('#btnOnline'), btnOffline = $('#btnOffline'), nbElementItem = $('#nb_elements'); // Enable delete button btnDelete.click(function(){ var checkedCheckboxes = listForm.find(':checkbox:checked'), nombreElementsTraites = 0, nombreElementsSelectionnes = checkedCheckboxes.length; // Build confirm string confirmString = translate('Delete') + ' ' + nombreElementsSelectionnes.toString() + ' ' + translate('item'); if (nombreElementsSelectionnes > 1) confirmString += 's'; confirmString += '?'; if (confirm(confirmString)) { checkedCheckboxes.each(function(){ var id = $(this).val(); $.ajax({ type: 'DELETE', url: document.URL.split('?')[0] + '/' + id }).done(function(){ $('#item_' + id).slideUp('fast', function () { var nbElements = nbElementItem.html(); nbElementItem.html(nbElements-1); $(this).remove(); nombreElementsTraites++; if (nombreElementsSelectionnes == nombreElementsTraites) { alertify.success(nombreElementsSelectionnes + ' items deleted.'); } }); }).fail(function(){ alertify.error(translate('An error occurred')); }); }); } }); // Enable online button switches.click(function(){ var item = $(this).closest('li'), status = item.hasClass('online') ? 'online' : 'offline' , newStatus = item.hasClass('online') ? 'offline' : 'online' , newStatusValue = item.hasClass('online') ? 0 : 1 , id = $(this).parent().children(':checkbox').val(), data = {}; data['id'] = id; data[contentLocale] = {'status' : newStatusValue}; $('#item_' + id).removeClass(status).addClass(newStatus); $.ajax({ type: 'PATCH', url: document.URL.split('?')[0] + '/' + id, data: data }).done(function(){ alertify.success('Item set ' + newStatus + '.'); }).fail(function(){ alertify.error('Item couldn’t be set ' + newStatus + '.'); }); }); // Enable online button btnOnline.click(function(){ var checkedCheckboxes = listForm.find(':checkbox:checked'), nombreElementsTraites = 0, nombreElementsSelectionnes = checkedCheckboxes.length; checkedCheckboxes.each(function(){ var id = $(this).val(), data = {}; data['id'] = id; data[contentLocale] = {'status' : 1}; $.ajax({ type: 'PATCH', url: document.URL.split('?')[0] + '/' + id, data: data }).done(function(){ $('#item_' + id).removeClass('offline').addClass('online').find(':checkbox').prop({'checked':false}); nombreElementsTraites++; if (nombreElementsSelectionnes == nombreElementsTraites) { alertify.success(nombreElementsSelectionnes + ' items set online.'); } }).fail(function(){ alertify.error('Item couldn’t be set online.'); }); }); }); // Enable offline button btnOffline.click(function(){ var checkedCheckboxes = listForm.find(':checkbox:checked'), nombreElementsTraites = 0, nombreElementsSelectionnes = checkedCheckboxes.length; checkedCheckboxes.each(function(){ var id = $(this).val(), data = {}; data['id'] = id; data[contentLocale] = {'status' : 0}; $.ajax({ type: 'PATCH', url: document.URL.split('?')[0] + '/' + id, data: data }).done(function(){ $('#item_' + id).removeClass('online').addClass('offline').find(':checkbox').prop({'checked':false}); nombreElementsTraites++; if (nombreElementsSelectionnes == nombreElementsTraites) { alertify.success(nombreElementsSelectionnes + ' items set offline.'); } }).fail(function(){ alertify.error('Item couldn’t be set offline.'); }); }); }); } !function( $ ){ "use strict"; $(function () { enableSortable(); $('.list-main.nested').nestedCookie(); initListForm(); $('.list-form').listEnhancer({ done: function(data) { reloadPage(); }, error: function() { reloadPage(); } }); }); }( window.jQuery || window.ender );
disclose button
public/js/list.js
disclose button
<ide><path>ublic/js/list.js <ide> if (sortableList.hasClass('nested')) { <ide> maxLevels = 3; <ide> isTree = true; <del> sortableList.find('li div').prepend('<span class="disclose"></span>'); <add> sortableList.find('li > div').prepend('<span class="disclose"></span>'); <ide> } <ide> if (sortableList.hasClass('sortable-thumbnails')) { <ide> handle = 'img';