conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
import jenkins.util.SystemProperties;
=======
import java.util.Arrays;
>>>>>>>
import jenkins.util.SystemProperties;
import java.util.Arrays; |
<<<<<<<
return el.canSpawn(worldServer) &&
SpawnRestriction.canSpawn(el.getType(),el.getEntityWorld(), SpawnType.NATURAL, el.getSenseCenterPos(), el.getEntityWorld().random) &&
=======
return el.canSpawn(worldServer) && el.canSpawn(worldServer, SpawnType.NATURAL) &&
SpawnRestriction.canSpawn(el.getType(),el.getEntityWorld(), SpawnType.NATURAL, el.getBlockPos(), el.getEntityWorld().random) &&
>>>>>>>
return el.canSpawn(worldServer) && el.canSpawn(worldServer, SpawnType.NATURAL) &&
SpawnRestriction.canSpawn(el.getType(),el.getEntityWorld(), SpawnType.NATURAL, el.getSenseCenterPos(), el.getEntityWorld().random) && |
<<<<<<<
import hudson.AbortException;
=======
import hudson.model.*;
import hudson.remoting.ChannelBuilder;
import hudson.util.IOException2;
import hudson.util.IOUtils;
import hudson.util.io.ReopenableRotatingFileOutputStream;
import jenkins.model.Jenkins.MasterComputer;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Callable;
import hudson.util.StreamTaskListener;
import hudson.util.NullStream;
import hudson.util.RingBufferLogHandler;
import hudson.util.Futures;
>>>>>>>
import hudson.AbortException;
import hudson.remoting.ChannelBuilder;
import hudson.util.IOUtils;
<<<<<<<
import static hudson.slaves.SlaveComputer.LogHolder.*;
=======
import jenkins.security.ChannelConfigurator;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.JnlpSlaveAgentProtocol;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
>>>>>>>
import static hudson.slaves.SlaveComputer.LogHolder.*;
import jenkins.security.ChannelConfigurator;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.JnlpSlaveAgentProtocol;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpRedirect;
<<<<<<<
/**
* Helper method for Jelly.
*/
public static List<SlaveSystemInfo> getSystemInfoExtensions() {
return SlaveSystemInfo.all();
}
private static class SlaveLogFetcher implements Callable<List<LogRecord>,RuntimeException> {
=======
private static class SlaveLogFetcher extends MasterToSlaveCallable<List<LogRecord>,RuntimeException> {
>>>>>>>
/**
* Helper method for Jelly.
*/
public static List<SlaveSystemInfo> getSystemInfoExtensions() {
return SlaveSystemInfo.all();
}
private static class SlaveLogFetcher extends MasterToSlaveCallable<List<LogRecord>,RuntimeException> { |
<<<<<<<
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
=======
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
import com.sun.jna.Native;
>>>>>>>
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
<<<<<<<
import hudson.model.TaskListener;
import hudson.org.apache.tools.tar.TarInputStream;
import hudson.os.PosixAPI;
import hudson.os.PosixException;
=======
import hudson.model.TaskListener;
import hudson.org.apache.tools.tar.TarInputStream;
import hudson.os.PosixException;
>>>>>>>
import hudson.model.TaskListener;
import hudson.org.apache.tools.tar.TarInputStream;
import hudson.os.PosixAPI;
import hudson.os.PosixException;
<<<<<<<
import hudson.remoting.RemoteInputStream;
=======
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteInputStream.Flag;
>>>>>>>
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteInputStream.Flag;
<<<<<<<
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.FileVisitor;
=======
import hudson.util.FileVisitor;
>>>>>>>
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.FileVisitor;
<<<<<<<
import hudson.util.HeadBufferingStream;
=======
import hudson.util.HeadBufferingStream;
import hudson.util.IOException2;
>>>>>>>
import hudson.util.HeadBufferingStream;
<<<<<<<
import hudson.util.NamingThreadFactory;
=======
>>>>>>>
import hudson.util.NamingThreadFactory;
<<<<<<<
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
=======
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;
>>>>>>>
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.security.MasterToSlaveCallable;
<<<<<<<
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
=======
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.jenkinsci.remoting.RoleChecker;
import org.jenkinsci.remoting.RoleSensitive;
>>>>>>>
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
<<<<<<<
import javax.annotation.CheckForNull;
=======
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
>>>>>>>
import javax.annotation.CheckForNull;
import org.jenkinsci.remoting.RoleChecker;
import org.jenkinsci.remoting.RoleSensitive;
import javax.annotation.Nullable;
<<<<<<<
import static hudson.FilePath.TarCompression.*;
import static hudson.Util.*;
import javax.annotation.Nonnull;
=======
import static hudson.FilePath.TarCompression.*;
import static hudson.Util.*;
import static hudson.util.jna.GNUCLibrary.*;
>>>>>>>
import static hudson.FilePath.TarCompression.*;
import static hudson.Util.*;
import javax.annotation.Nonnull;
<<<<<<<
InputStream input = zip.getInputStream(e);
try {
IOUtils.copy(input, f);
} finally {
input.close();
}
=======
IOUtils.copy(zip.getInputStream(e), writing(f));
>>>>>>>
InputStream input = zip.getInputStream(e);
try {
IOUtils.copy(input, writing(f));
} finally {
input.close();
}
<<<<<<<
throw new IOException("remote file operation failed: "+remote+" at "+channel,e);
=======
throw new IOException("remote file operation failed: " + remote + " at " + channel + ": " + e, e);
>>>>>>>
throw new IOException("remote file operation failed: " + remote + " at " + channel + ": " + e, e);
<<<<<<<
for(File child : tmp.listFiles()) {
=======
for(File child : reading(f).listFiles()) {
>>>>>>>
for(File child : reading(tmp).listFiles()) {
<<<<<<<
tmp.delete();
=======
deleting(f).delete();
>>>>>>>
deleting(tmp).delete();
<<<<<<<
IOUtils.mkdirs(target.getParentFile());
Util.copyFile(f, target);
=======
mkdirs(target.getParentFile());
Util.copyFile(f, writing(target));
>>>>>>>
mkdirsE(target.getParentFile());
Util.copyFile(f, writing(target));
<<<<<<<
IOUtils.mkdirs(new File(dest, relativePath).getParentFile());
=======
writing(new File(dest, target));
>>>>>>>
mkdirsE(new File(dest, relativePath).getParentFile());
writing(new File(dest, target));
<<<<<<<
private static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "FilePath.localPool"))
));
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
=======
/**
* Pass through 'f' after ensuring that we can create that file/dir.
*/
private File creating(File f) {
filterNonNull().create(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can write to that file.
*/
private File writing(File f) {
FilePathFilter filter = filterNonNull();
if (!f.exists())
filter.create(f);
filter.write(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can delete that file.
*/
private File deleting(File f) {
filterNonNull().delete(f);
return f;
}
private boolean mkdirs(File dir) {
if (dir.exists()) return false;
filterNonNull().mkdirs(dir);
return dir.mkdirs();
}
>>>>>>>
private static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "FilePath.localPool"))
));
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
/**
* Pass through 'f' after ensuring that we can create that file/dir.
*/
private File creating(File f) {
filterNonNull().create(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can write to that file.
*/
private File writing(File f) {
FilePathFilter filter = filterNonNull();
if (!f.exists())
filter.create(f);
filter.write(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can delete that file.
*/
private File deleting(File f) {
filterNonNull().delete(f);
return f;
}
private boolean mkdirs(File dir) {
if (dir.exists()) return false;
filterNonNull().mkdirs(dir);
return dir.mkdirs();
}
private File mkdirsE(File dir) throws IOException {
if (dir.exists()) {
return dir;
}
filterNonNull().mkdirs(dir);
return IOUtils.mkdirs(dir);
} |
<<<<<<<
import net.minecraft.loot.context.LootContext;
import net.minecraft.loot.context.LootContextParameters;
=======
import net.minecraft.world.gen.ChunkRandom;
import net.minecraft.world.loot.context.LootContext;
import net.minecraft.world.loot.context.LootContextParameters;
>>>>>>>
import net.minecraft.world.gen.ChunkRandom;
import net.minecraft.loot.context.LootContext;
import net.minecraft.loot.context.LootContextParameters; |
<<<<<<<
import com.google.inject.AbstractModule;
import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.Scopes;
import com.google.inject.name.Names;
=======
import com.google.common.collect.ImmutableList;
import hudson.init.InitMilestone;
import hudson.model.Hudson;
import jenkins.model.Jenkins;
>>>>>>>
import com.google.inject.AbstractModule;
import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.Scopes;
import com.google.inject.name.Names;
import com.google.common.collect.ImmutableList;
import hudson.init.InitMilestone;
import hudson.model.Hudson;
import jenkins.model.Jenkins; |
<<<<<<<
=======
import org.apache.commons.lang.StringUtils;
import org.hamcrest.collection.IsEmptyCollection;
import org.hamcrest.core.IsEqual;
import org.hamcrest.core.StringEndsWith;
import org.junit.Assert;
>>>>>>> |
<<<<<<<
private final Jenkins jenkins;
public LocalPluginManager(Jenkins jenkins) {
super(jenkins.servletContext, new File(jenkins.getRootDir(),"plugins"));
this.jenkins = jenkins;
=======
public LocalPluginManager(Hudson hudson) {
super(hudson.servletContext, new File(hudson.getRootDir(),"plugins"));
}
public LocalPluginManager(File rootDir) {
super(null, new File(rootDir,"plugins"));
>>>>>>>
public LocalPluginManager(Jenkins jenkins) {
super(jenkins.servletContext, new File(jenkins.getRootDir(),"plugins"));
}
public LocalPluginManager(File rootDir) {
super(null, new File(rootDir,"plugins"));
<<<<<<<
for( String path : Util.fixNull((Set<String>) jenkins.servletContext.getResourcePaths("/WEB-INF/plugins"))) {
=======
ServletContext context = Hudson.getInstance().servletContext;
for( String path : Util.fixNull((Set<String>)context.getResourcePaths("/WEB-INF/plugins"))) {
>>>>>>>
ServletContext context = Jenkins.getInstance().servletContext;
for( String path : Util.fixNull((Set<String>)context.getResourcePaths("/WEB-INF/plugins"))) {
<<<<<<<
URL url = jenkins.servletContext.getResource(path);
=======
URL url = context.getResource(path);
>>>>>>>
URL url = context.getResource(path); |
<<<<<<<
Object o = Jenkins.XSTREAM.unmarshal(XStream2.getDefaultDriver().createReader(in), this);
=======
ViewGroup oldOwner = owner; // oddly, this field is not transient
Object o = Jenkins.XSTREAM2.unmarshal(new Xpp3Driver().createReader(in), this, null, true);
>>>>>>>
ViewGroup oldOwner = owner; // oddly, this field is not transient
Object o = Jenkins.XSTREAM.unmarshal(XStream2.getDefaultDriver().createReader(in), this, null, true); |
<<<<<<<
=======
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.PacketByteBuf;
>>>>>>>
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.PacketByteBuf; |
<<<<<<<
Jenkins h = Jenkins.getActiveInstance();
Secret userName = Secret.decrypt(props.getProperty(getPropertyKey()));
if (userName==null) return Jenkins.ANONYMOUS; // failed to decrypt
=======
Jenkins h = Jenkins.getInstance();
String val = props.getProperty(getPropertyKey());
if (val == null) {
LOGGER.finer("No stored CLI authentication");
return Jenkins.ANONYMOUS;
}
Secret oldSecret = Secret.decrypt(val);
if (oldSecret != null) {
LOGGER.log(Level.FINE, "Ignoring insecure stored CLI authentication for {0}", oldSecret.getPlainText());
return Jenkins.ANONYMOUS;
}
int idx = val.lastIndexOf(':');
if (idx == -1) {
LOGGER.log(Level.FINE, "Ignoring malformed stored CLI authentication: {0}", val);
return Jenkins.ANONYMOUS;
}
String username = val.substring(0, idx);
if (!MAC.checkMac(username, val.substring(idx + 1))) {
LOGGER.log(Level.FINE, "Ignoring stored CLI authentication due to MAC mismatch: {0}", val);
return Jenkins.ANONYMOUS;
}
>>>>>>>
Jenkins h = Jenkins.getActiveInstance();
String val = props.getProperty(getPropertyKey());
if (val == null) {
LOGGER.finer("No stored CLI authentication");
return Jenkins.ANONYMOUS;
}
Secret oldSecret = Secret.decrypt(val);
if (oldSecret != null) {
LOGGER.log(Level.FINE, "Ignoring insecure stored CLI authentication for {0}", oldSecret.getPlainText());
return Jenkins.ANONYMOUS;
}
int idx = val.lastIndexOf(':');
if (idx == -1) {
LOGGER.log(Level.FINE, "Ignoring malformed stored CLI authentication: {0}", val);
return Jenkins.ANONYMOUS;
}
String username = val.substring(0, idx);
if (!MAC.checkMac(username, val.substring(idx + 1))) {
LOGGER.log(Level.FINE, "Ignoring stored CLI authentication due to MAC mismatch: {0}", val);
return Jenkins.ANONYMOUS;
}
<<<<<<<
private String getPropertyKey() {
String url = Jenkins.getActiveInstance().getRootUrl();
=======
@VisibleForTesting
String getPropertyKey() {
String url = Jenkins.getInstance().getRootUrl();
>>>>>>>
@VisibleForTesting
String getPropertyKey() {
String url = Jenkins.getActiveInstance().getRootUrl(); |
<<<<<<<
import hudson.Util;
=======
import hudson.Functions;
>>>>>>>
import hudson.Util;
import hudson.Functions; |
<<<<<<<
source.sendFeedback(Messenger.c(fields),source.getMinecraftServer() != null && source.getMinecraftServer().getWorld(World.field_25179) != null); //OW
=======
if (source != null)
source.sendFeedback(Messenger.c(fields),source.getMinecraftServer() != null && source.getMinecraftServer().getWorld(DimensionType.OVERWORLD) != null);
>>>>>>>
if (source != null)
source.sendFeedback(Messenger.c(fields),source.getMinecraftServer() != null && source.getMinecraftServer().getWorld(World.field_25179) != null); //OW |
<<<<<<<
=======
import static hudson.util.TimeUnit2.DAYS;
import org.apache.commons.io.IOUtils;
>>>>>>> |
<<<<<<<
import org.jvnet.hudson.test.recipes.LocalData;
=======
import org.jvnet.hudson.test.TestExtension;
>>>>>>>
import org.jvnet.hudson.test.recipes.LocalData;
import org.jvnet.hudson.test.TestExtension;
<<<<<<<
@Test public void waitForStartAndCancelBeforeStart() throws Exception {
final OneShotEvent ev = new OneShotEvent();
FreeStyleProject p = r.createFreeStyleProject();
QueueTaskFuture<FreeStyleBuild> f = p.scheduleBuild2(10);
final Queue.Item item = Queue.getInstance().getItem(p);
assertNotNull(item);
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.schedule(new Runnable() {
@Override
public void run() {
try {
Queue.getInstance().doCancelItem(item.getId());
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
}, 2, TimeUnit.SECONDS);
try {
f.waitForStart();
fail("Expected an CancellationException to be thrown");
} catch (CancellationException e) {}
}
@Issue("JENKINS-27871")
@Test public void testBlockBuildWhenUpstreamBuildingLock() throws Exception {
final String prefix = "JENKINS-27871";
r.getInstance().setNumExecutors(4);
r.getInstance().save();
final FreeStyleProject projectA = r.createFreeStyleProject(prefix+"A");
projectA.getBuildersList().add(new SleepBuilder(5000));
final FreeStyleProject projectB = r.createFreeStyleProject(prefix+"B");
projectB.getBuildersList().add(new SleepBuilder(10000));
projectB.setBlockBuildWhenUpstreamBuilding(true);
final FreeStyleProject projectC = r.createFreeStyleProject(prefix+"C");
projectC.getBuildersList().add(new SleepBuilder(10000));
projectC.setBlockBuildWhenUpstreamBuilding(true);
projectA.getPublishersList().add(new BuildTrigger(Arrays.asList(projectB), Result.SUCCESS));
projectB.getPublishersList().add(new BuildTrigger(Arrays.asList(projectC), Result.SUCCESS));
final QueueTaskFuture<FreeStyleBuild> taskA = projectA.scheduleBuild2(0, new TimerTriggerCause());
Thread.sleep(1000);
final QueueTaskFuture<FreeStyleBuild> taskB = projectB.scheduleBuild2(0, new TimerTriggerCause());
final QueueTaskFuture<FreeStyleBuild> taskC = projectC.scheduleBuild2(0, new TimerTriggerCause());
final FreeStyleBuild buildA = taskA.get(60, TimeUnit.SECONDS);
final FreeStyleBuild buildB = taskB.get(60, TimeUnit.SECONDS);
final FreeStyleBuild buildC = taskC.get(60, TimeUnit.SECONDS);
long buildBEndTime = buildB.getStartTimeInMillis() + buildB.getDuration();
assertTrue("Project B build should be finished before the build of project C starts. " +
"B finished at " + buildBEndTime + ", C started at " + buildC.getStartTimeInMillis(),
buildC.getStartTimeInMillis() >= buildBEndTime);
}
=======
@Test
public void queueApiOutputShouldBeFilteredByUserPermission() throws Exception {
r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
ProjectMatrixAuthorizationStrategy str = new ProjectMatrixAuthorizationStrategy();
str.add(Jenkins.READ, "bob");
str.add(Jenkins.READ, "alice");
str.add(Jenkins.READ, "james");
r.jenkins.setAuthorizationStrategy(str);
FreeStyleProject project = r.createFreeStyleProject("project");
Map<Permission, Set<String>> permissions = new HashMap<Permission, Set<String>>();
permissions.put(Item.READ, Collections.singleton("bob"));
permissions.put(Item.DISCOVER, Collections.singleton("james"));
AuthorizationMatrixProperty prop1 = new AuthorizationMatrixProperty(permissions);
project.addProperty(prop1);
project.getBuildersList().add(new SleepBuilder(10));
project.scheduleBuild2(0);
JenkinsRule.WebClient webClient = r.createWebClient();
webClient.login("bob", "bob");
XmlPage p = webClient.goToXml("/queue/api/xml");
//bob has permission on the project and will be able to see it in the queue together with information such as the URL and the name.
for (DomNode element: p.getFirstChild().getFirstChild().getChildNodes()){
if(element.getNodeName().equals("task")){
assertEquals(((DomElement)element).getElementsByTagName("name").size(),1);
assertEquals(((DomElement) element).getElementsByTagName("name").item(0).getFirstChild().toString(), "project");
assertEquals(((DomElement)element).getElementsByTagName("url").size(),1);
}
}
webClient = r.createWebClient();
webClient.login("alice");
XmlPage p2 = webClient.goToXml("/queue/api/xml");
//alice does not have permission on the project and will not see it in the queue.
assertEquals("<queue></queue>", p2.getContent());
webClient = r.createWebClient();
webClient.login("james");
XmlPage p3 = webClient.goToXml("/queue/api/xml");
//james has DISCOVER permission on the project and will only be able to see the task name.
assertEquals("<queue><discoverableItem><task><name>project</name></task></discoverableItem></queue>",
p3.getContent());
}
//we force the project not to be executed so that it stays in the queue
@TestExtension("queueApiOutputShouldBeFilteredByUserPermission")
public static class MyQueueTaskDispatcher extends QueueTaskDispatcher {
@Override
public CauseOfBlockage canTake(Node node, Queue.BuildableItem item) {
return new CauseOfBlockage() {
@Override
public String getShortDescription() {
return "blocked by canTake";
}
};
}
}
>>>>>>>
@Test public void waitForStartAndCancelBeforeStart() throws Exception {
final OneShotEvent ev = new OneShotEvent();
FreeStyleProject p = r.createFreeStyleProject();
QueueTaskFuture<FreeStyleBuild> f = p.scheduleBuild2(10);
final Queue.Item item = Queue.getInstance().getItem(p);
assertNotNull(item);
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.schedule(new Runnable() {
@Override
public void run() {
try {
Queue.getInstance().doCancelItem(item.getId());
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
}, 2, TimeUnit.SECONDS);
try {
f.waitForStart();
fail("Expected an CancellationException to be thrown");
} catch (CancellationException e) {}
}
@Issue("JENKINS-27871")
@Test public void testBlockBuildWhenUpstreamBuildingLock() throws Exception {
final String prefix = "JENKINS-27871";
r.getInstance().setNumExecutors(4);
r.getInstance().save();
final FreeStyleProject projectA = r.createFreeStyleProject(prefix+"A");
projectA.getBuildersList().add(new SleepBuilder(5000));
final FreeStyleProject projectB = r.createFreeStyleProject(prefix+"B");
projectB.getBuildersList().add(new SleepBuilder(10000));
projectB.setBlockBuildWhenUpstreamBuilding(true);
final FreeStyleProject projectC = r.createFreeStyleProject(prefix+"C");
projectC.getBuildersList().add(new SleepBuilder(10000));
projectC.setBlockBuildWhenUpstreamBuilding(true);
projectA.getPublishersList().add(new BuildTrigger(Arrays.asList(projectB), Result.SUCCESS));
projectB.getPublishersList().add(new BuildTrigger(Arrays.asList(projectC), Result.SUCCESS));
final QueueTaskFuture<FreeStyleBuild> taskA = projectA.scheduleBuild2(0, new TimerTriggerCause());
Thread.sleep(1000);
final QueueTaskFuture<FreeStyleBuild> taskB = projectB.scheduleBuild2(0, new TimerTriggerCause());
final QueueTaskFuture<FreeStyleBuild> taskC = projectC.scheduleBuild2(0, new TimerTriggerCause());
final FreeStyleBuild buildA = taskA.get(60, TimeUnit.SECONDS);
final FreeStyleBuild buildB = taskB.get(60, TimeUnit.SECONDS);
final FreeStyleBuild buildC = taskC.get(60, TimeUnit.SECONDS);
long buildBEndTime = buildB.getStartTimeInMillis() + buildB.getDuration();
assertTrue("Project B build should be finished before the build of project C starts. " +
"B finished at " + buildBEndTime + ", C started at " + buildC.getStartTimeInMillis(),
buildC.getStartTimeInMillis() >= buildBEndTime);
}
@Test
public void queueApiOutputShouldBeFilteredByUserPermission() throws Exception {
r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
ProjectMatrixAuthorizationStrategy str = new ProjectMatrixAuthorizationStrategy();
str.add(Jenkins.READ, "bob");
str.add(Jenkins.READ, "alice");
str.add(Jenkins.READ, "james");
r.jenkins.setAuthorizationStrategy(str);
FreeStyleProject project = r.createFreeStyleProject("project");
Map<Permission, Set<String>> permissions = new HashMap<Permission, Set<String>>();
permissions.put(Item.READ, Collections.singleton("bob"));
permissions.put(Item.DISCOVER, Collections.singleton("james"));
AuthorizationMatrixProperty prop1 = new AuthorizationMatrixProperty(permissions);
project.addProperty(prop1);
project.getBuildersList().add(new SleepBuilder(10));
project.scheduleBuild2(0);
JenkinsRule.WebClient webClient = r.createWebClient();
webClient.login("bob", "bob");
XmlPage p = webClient.goToXml("/queue/api/xml");
//bob has permission on the project and will be able to see it in the queue together with information such as the URL and the name.
for (DomNode element: p.getFirstChild().getFirstChild().getChildNodes()){
if(element.getNodeName().equals("task")){
assertEquals(((DomElement)element).getElementsByTagName("name").size(),1);
assertEquals(((DomElement) element).getElementsByTagName("name").item(0).getFirstChild().toString(), "project");
assertEquals(((DomElement)element).getElementsByTagName("url").size(),1);
}
}
webClient = r.createWebClient();
webClient.login("alice");
XmlPage p2 = webClient.goToXml("/queue/api/xml");
//alice does not have permission on the project and will not see it in the queue.
assertEquals("<queue></queue>", p2.getContent());
webClient = r.createWebClient();
webClient.login("james");
XmlPage p3 = webClient.goToXml("/queue/api/xml");
//james has DISCOVER permission on the project and will only be able to see the task name.
assertEquals("<queue><discoverableItem><task><name>project</name></task></discoverableItem></queue>",
p3.getContent());
}
//we force the project not to be executed so that it stays in the queue
@TestExtension("queueApiOutputShouldBeFilteredByUserPermission")
public static class MyQueueTaskDispatcher extends QueueTaskDispatcher {
@Override
public CauseOfBlockage canTake(Node node, Queue.BuildableItem item) {
return new CauseOfBlockage() {
@Override
public String getShortDescription() {
return "blocked by canTake";
}
};
}
} |
<<<<<<<
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
=======
import net.minecraft.util.PacketByteBuf;
>>>>>>>
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.util.PacketByteBuf;
<<<<<<<
{
CompoundTag boxData = (CompoundTag)t;
CarpetClient.shapes.addShape(
boxData.getString("type"),
RegistryKey.of(Registry.DIMENSION, new Identifier(boxData.getString("dim"))),
boxData
);
}
=======
CarpetClient.shapes.addShape((CompoundTag)t);
>>>>>>>
CarpetClient.shapes.addShape((CompoundTag)t); |
<<<<<<<
import net.minecraft.entity.ai.brain.Brain;
import net.minecraft.entity.ai.brain.Memory;
=======
import net.minecraft.entity.EntityCategory;
import net.minecraft.entity.EntityGroup;
>>>>>>>
import net.minecraft.entity.ai.brain.Brain;
import net.minecraft.entity.ai.brain.Memory;
import net.minecraft.entity.EntityCategory;
import net.minecraft.entity.EntityGroup; |
<<<<<<<
ScriptHost host = getHost(context);
BlockBox area = new BlockBox(a, b);
=======
CarpetScriptHost host = getHost(context);
MutableIntBoundingBox area = new MutableIntBoundingBox(a, b);
>>>>>>>
CarpetScriptHost host = getHost(context);
BlockBox area = new BlockBox(a, b);
<<<<<<<
ScriptHost host = getHost(context);
BlockBox area = new BlockBox(a, b);
=======
CarpetScriptHost host = getHost(context);
MutableIntBoundingBox area = new MutableIntBoundingBox(a, b);
>>>>>>>
CarpetScriptHost host = getHost(context);
BlockBox area = new BlockBox(a, b); |
<<<<<<<
for (RuntimeException e1: owner.getTerminatedBy()) LOGGER.log(Level.WARNING, String.format("%s termination trace", getName()), e1);
if (causeOfDeath==null)
// let this thread die and be replaced by a fresh unstarted instance
owner.removeExecutor(this);
=======
if (asynchronousExecution == null) {
finish2();
}
}
}
private void finish1(@CheckForNull Throwable problems) {
if (problems != null) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", problems);
workUnit.context.abort(problems);
}
long time = System.currentTimeMillis() - startTime;
LOGGER.log(FINE, "{0} completed {1} in {2}ms", new Object[] {getName(), executable, time});
try {
workUnit.context.synchronizeEnd(this, executable, problems, time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
} finally {
workUnit.setExecutor(null);
}
}
>>>>>>>
if (asynchronousExecution == null) {
finish2();
}
}
}
private void finish1(@CheckForNull Throwable problems) {
if (problems != null) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", problems);
workUnit.context.abort(problems);
}
long time = System.currentTimeMillis() - startTime;
LOGGER.log(FINE, "{0} completed {1} in {2}ms", new Object[]{getName(), executable, time});
try {
workUnit.context.synchronizeEnd(this, executable, problems, time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
} finally {
workUnit.setExecutor(null);
}
}
<<<<<<<
lock.readLock().lock();
try {
return !started || isAlive();
} finally {
lock.readLock().unlock();
}
=======
return !started || asynchronousExecution != null || isAlive();
}
/**
* If currently running in asynchronous mode, returns that handle.
* @since TODO
*/
public @CheckForNull AsynchronousExecution getAsynchronousExecution() {
return asynchronousExecution;
>>>>>>>
lock.readLock().lock();
try {
return !started || asynchronousExecution != null || isAlive();
} finally {
lock.readLock().unlock();
}
}
/**
* If currently running in asynchronous mode, returns that handle.
* @since TODO
*/
public @CheckForNull AsynchronousExecution getAsynchronousExecution() {
lock.readLock().lock();
try {
return asynchronousExecution;
} finally {
lock.readLock().unlock();
} |
<<<<<<<
import org.junit.Assert;
=======
>>>>>>> |
<<<<<<<
BlockBox area = new BlockBox(a, b);
CarpetExpression cexpr = new CarpetExpression(expr, source, origin);
=======
MutableIntBoundingBox area = new MutableIntBoundingBox(a, b);
CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
>>>>>>>
BlockBox area = new BlockBox(a, b);
CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
<<<<<<<
BlockBox area = new BlockBox(a, b);
CarpetExpression cexpr = new CarpetExpression(expr, source, origin);
=======
MutableIntBoundingBox area = new MutableIntBoundingBox(a, b);
CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
>>>>>>>
BlockBox area = new BlockBox(a, b);
CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); |
<<<<<<<
/**
*
* @return A long value representing the time the file was last modified, measured in milliseconds since
* the epoch (00:00:00 GMT, January 1, 1970), or 0L if is not possible to obtain the times.
* @since TODO
*/
public long getLastModified() {
return lastModified;
}
/**
*
* @return A Calendar representing the time the file was last modified, it lastModified is 0L
* it will return 00:00:00 GMT, January 1, 1970.
* @since TODO
*/
@Restricted(NoExternalUse.class)
public Calendar getLastModifiedAsCalendar() {
final Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(lastModified);
return cal;
}
=======
public static Path createNotReadableVersionOf(Path that){
return new Path(that.href, that.title, that.isFolder, that.size, false);
}
>>>>>>>
/**
*
* @return A long value representing the time the file was last modified, measured in milliseconds since
* the epoch (00:00:00 GMT, January 1, 1970), or 0L if is not possible to obtain the times.
* @since TODO
*/
public long getLastModified() {
return lastModified;
}
/**
*
* @return A Calendar representing the time the file was last modified, it lastModified is 0L
* it will return 00:00:00 GMT, January 1, 1970.
* @since TODO
*/
@Restricted(NoExternalUse.class)
public Calendar getLastModifiedAsCalendar() {
final Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(lastModified);
return cal;
}
public static Path createNotReadableVersionOf(Path that){
return new Path(that.href, that.title, that.isFolder, that.size, false);
} |
<<<<<<<
Jenkins h = Jenkins.getInstanceOrNull(); // guard against repeated concurrent calls to restart
if (h != null)
h.cleanUp();
=======
Jenkins jenkins = Jenkins.getInstance();
try {
if (jenkins != null) {
jenkins.cleanUp();
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Failed to clean up. Restart will continue.", e);
}
>>>>>>>
Jenkins h = Jenkins.getInstanceOrNull(); // guard against repeated concurrent calls to restart
try {
if (jenkins != null) {
jenkins.cleanUp();
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Failed to clean up. Restart will continue.", e);
} |
<<<<<<<
} else {
=======
else if(!containsOnlyAcceptableCharacters(si.username))
if(ID_REGEX == null){
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharacters();
}else{
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharactersCustom(ID_REGEX);
}
else {
>>>>>>>
} else if(!containsOnlyAcceptableCharacters(si.username)) {
if (ID_REGEX == null) {
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharacters();
} else {
si.errorMessage = Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharactersCustom(ID_REGEX);
}
} else {
<<<<<<<
=======
private boolean containsOnlyAcceptableCharacters(@Nonnull String value){
if(ID_REGEX == null){
return value.matches(DEFAULT_ID_REGEX);
}else{
return value.matches(ID_REGEX);
}
}
>>>>>>>
private boolean containsOnlyAcceptableCharacters(@Nonnull String value){
if(ID_REGEX == null){
return value.matches(DEFAULT_ID_REGEX);
}else{
return value.matches(ID_REGEX);
}
} |
<<<<<<<
int r = writeToTar(new File(remote), scanner, TarCompression.GZIP.compress(pipe.getOut()));
=======
Future<Integer> future2 = actAsync(new FileCallable<Integer>() {
private static final long serialVersionUID = 1L;
@Override public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return writeToTar(new File(remote),fileMask,excludes,TarCompression.GZIP.compress(pipe.getOut()));
}
});
>>>>>>>
Future<Integer> future2 = actAsync(new FileCallable<Integer>() {
private static final long serialVersionUID = 1L;
@Override public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return writeToTar(new File(remote), scanner, TarCompression.GZIP.compress(pipe.getOut()));
}
}); |
<<<<<<<
=======
import hudson.slaves.ComputerConnector;
import hudson.tasks.Builder;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Publisher;
import hudson.tools.ToolProperty;
import hudson.remoting.Which;
import hudson.Launcher.LocalLauncher;
import hudson.matrix.MatrixProject;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenEmbedder;
import hudson.model.Node.Mode;
>>>>>>>
<<<<<<<
=======
import net.sf.json.JSONObject;
>>>>>>>
import net.sf.json.JSONObject; |
<<<<<<<
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
=======
@edu.umd.cs.findbugs.annotations.SuppressWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
@RequirePOST
>>>>>>>
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
@RequirePOST |
<<<<<<<
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
=======
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
>>>>>>>
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
<<<<<<<
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
=======
>>>>>>>
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
<<<<<<<
import org.jvnet.hudson.test.JenkinsRule.WebClient;
=======
import org.jvnet.hudson.test.recipes.LocalData;
>>>>>>>
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.recipes.LocalData;
<<<<<<<
/**
* Verify we can't rename a node over an existing node.
*/
@Issue("JENKINS-31321")
@Test
public void testProhibitRenameOverExistingNode() throws Exception {
final String NOTE = "Rename node to name of another node should fail.";
Node nodeA = j.createSlave("nodeA", null, null);
Node nodeB = j.createSlave("nodeB", null, null);
WebClient wc = j.createWebClient();
HtmlForm form = wc.getPage(nodeB, "configure").getFormByName("config");
form.getInputByName("_.name").setValueAttribute("nodeA");
try {
j.submit(form);
fail(NOTE);
} catch (FailingHttpStatusCodeException e) {
assertThat(NOTE, e.getStatusCode(), equalTo(400));
assertThat(NOTE, e.getResponse().getContentAsString(),
containsString("Slave called ‘nodeA’ already exists"));
}
}
=======
@Test
public void doNotShowUserDetailsInOfflineCause() throws Exception {
DumbSlave slave = j.createOnlineSlave();
final Computer computer = slave.toComputer();
computer.setTemporarilyOffline(true, new OfflineCause.UserCause(User.get("username"), "msg"));
verifyOfflineCause(computer);
}
@Test @LocalData
public void removeUserDetailsFromOfflineCause() throws Exception {
Computer computer = j.jenkins.getComputer("deserialized");
verifyOfflineCause(computer);
}
private void verifyOfflineCause(Computer computer) throws Exception {
XmlPage page = j.createWebClient().goToXml("computer/" + computer.getName() + "/config.xml");
String content = page.getWebResponse().getContentAsString("UTF-8");
assertThat(content, containsString("temporaryOfflineCause"));
assertThat(content, containsString("<userId>username</userId>"));
assertThat(content, not(containsString("ApiTokenProperty")));
assertThat(content, not(containsString("apiToken")));
}
>>>>>>>
/**
* Verify we can't rename a node over an existing node.
*/
@Issue("JENKINS-31321")
@Test
public void testProhibitRenameOverExistingNode() throws Exception {
final String NOTE = "Rename node to name of another node should fail.";
Node nodeA = j.createSlave("nodeA", null, null);
Node nodeB = j.createSlave("nodeB", null, null);
WebClient wc = j.createWebClient();
HtmlForm form = wc.getPage(nodeB, "configure").getFormByName("config");
form.getInputByName("_.name").setValueAttribute("nodeA");
try {
j.submit(form);
fail(NOTE);
} catch (FailingHttpStatusCodeException e) {
assertThat(NOTE, e.getStatusCode(), equalTo(400));
assertThat(NOTE, e.getResponse().getContentAsString(),
containsString("Slave called ‘nodeA’ already exists"));
}
}
@Test
public void doNotShowUserDetailsInOfflineCause() throws Exception {
DumbSlave slave = j.createOnlineSlave();
final Computer computer = slave.toComputer();
computer.setTemporarilyOffline(true, new OfflineCause.UserCause(User.get("username"), "msg"));
verifyOfflineCause(computer);
}
@Test @LocalData
public void removeUserDetailsFromOfflineCause() throws Exception {
Computer computer = j.jenkins.getComputer("deserialized");
verifyOfflineCause(computer);
}
private void verifyOfflineCause(Computer computer) throws Exception {
XmlPage page = j.createWebClient().goToXml("computer/" + computer.getName() + "/config.xml");
String content = page.getWebResponse().getContentAsString("UTF-8");
assertThat(content, containsString("temporaryOfflineCause"));
assertThat(content, containsString("<userId>username</userId>"));
assertThat(content, not(containsString("ApiTokenProperty")));
assertThat(content, not(containsString("apiToken")));
} |
<<<<<<<
import hudson.FilePath.FileCallable;
=======
import jenkins.MasterToSlaveFileCallable;
import hudson.Functions;
>>>>>>>
import jenkins.MasterToSlaveFileCallable;
<<<<<<<
protected static final class GetTempSpace implements FileCallable<DiskSpace> {
=======
protected static final class GetTempSpace extends MasterToSlaveFileCallable<DiskSpace> {
@IgnoreJRERequirement
>>>>>>>
protected static final class GetTempSpace extends MasterToSlaveFileCallable<DiskSpace> { |
<<<<<<<
import javax.annotation.Nonnull;
import jenkins.security.NonSerializableSecurityContext;
=======
import hudson.remoting.Callable;
import jenkins.security.NonSerializableSecurityContext;
>>>>>>>
import javax.annotation.Nonnull;
import hudson.remoting.Callable;
import jenkins.security.NonSerializableSecurityContext;
<<<<<<<
=======
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
>>>>>>>
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
<<<<<<<
/**
* Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
* @param auth authentication, such as {@link #SYSTEM}
* @param body an action to run with this alternate authentication in effect
* @since 1.509
*/
public static void impersonate(@Nonnull Authentication auth, @Nonnull Runnable body) {
SecurityContext old = impersonate(auth);
try {
body.run();
} finally {
SecurityContextHolder.setContext(old);
}
}
=======
/**
* Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
* @param auth authentication, such as {@link #SYSTEM}
* @param body an action to run with this alternate authentication in effect
* @since 1.509
*/
public static void impersonate(Authentication auth, Runnable body) {
SecurityContext old = impersonate(auth);
try {
body.run();
} finally {
SecurityContextHolder.setContext(old);
}
}
/**
* Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
* @param auth authentication, such as {@link #SYSTEM}
* @param body an action to run with this alternate authentication in effect
*/
// TODO: this line should be removed in the master branch once this commit is merged to mainline releases
@Restricted(NoExternalUse.class)
public static <V,T extends Exception> V impersonate(Authentication auth, Callable<V,T> body) throws T {
SecurityContext old = impersonate(auth);
try {
return body.call();
} finally {
SecurityContextHolder.setContext(old);
}
}
>>>>>>>
/**
* Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
* @param auth authentication, such as {@link #SYSTEM}
* @param body an action to run with this alternate authentication in effect
* @since 1.509
*/
public static void impersonate(@Nonnull Authentication auth, @Nonnull Runnable body) {
SecurityContext old = impersonate(auth);
try {
body.run();
} finally {
SecurityContextHolder.setContext(old);
}
}
/**
* Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
* @param auth authentication, such as {@link #SYSTEM}
* @param body an action to run with this alternate authentication in effect
*/
@Restricted(NoExternalUse.class)
public static <V,T extends Exception> V impersonate(Authentication auth, Callable<V,T> body) throws T {
SecurityContext old = impersonate(auth);
try {
return body.call();
} finally {
SecurityContextHolder.setContext(old);
}
} |
<<<<<<<
=======
>>>>>>>
<<<<<<<
public View getView(String name) {
//Top level views returned first if match
List<View> views = views();
for (View v : views) {
if (v.getViewName().equals(name)) {
=======
/**
* Gets a view by the specified name.
* The method iterates through {@link ViewGroup}s if required.
* @param name Name of the view
* @return View instance or {@code null} if it is missing
*/
@CheckForNull
public View getView(@CheckForNull String name) {
if (name == null) {
return null;
}
for (View v : views()) {
if(v.getViewName().equals(name))
>>>>>>>
/**
* Gets a view by the specified name.
* The method iterates through {@link ViewGroup}s if required.
* @param name Name of the view
* @return View instance or {@code null} if it is missing
*/
@CheckForNull
public View getView(@CheckForNull String name) {
if (name == null) {
return null;
}
//Top level views returned first if match
List<View> views = views();
for (View v : views) {
if (v.getViewName().equals(name)) { |
<<<<<<<
import hudson.util.SequentialExecutionQueue;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jelly.XMLOutput;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.DataBoundConstructor;
=======
>>>>>>>
import org.apache.commons.io.FileUtils;
import org.apache.commons.jelly.XMLOutput;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.DataBoundConstructor;
<<<<<<<
import static java.util.logging.Level.*;
import jenkins.model.RunAction2;
import javax.annotation.Nonnull;
=======
>>>>>>>
import static java.util.logging.Level.*;
import jenkins.model.RunAction2;
import javax.annotation.Nonnull;
<<<<<<<
public void onLoad(@Nonnull AbstractBuild<?, ?> build) {
this.build = build;
}
@Override
public void onAddedTo(AbstractBuild build) {
this.build = build;
=======
public void onAddedTo(Run build) {
>>>>>>>
public void onLoad(Run run) {
this.run = run;
}
@Override
public void onAddedTo(Run build) {
this.run = build; |
<<<<<<<
import jenkins.security.ApiTokenProperty;
import jenkins.security.SecurityListener;
import org.acegisecurity.Authentication;
=======
import jenkins.security.BasicApiTokenHelper;
>>>>>>>
import jenkins.security.ApiTokenProperty;
import jenkins.security.SecurityListener;
import org.acegisecurity.Authentication;
import jenkins.security.BasicApiTokenHelper;
<<<<<<<
{// attempt to authenticate as API token
// create is true as the user may not have been saved and the default api token may be in use.
// validation of the user will be performed against the underlying realm in impersonate.
User u = User.getById(username, true);
ApiTokenProperty t = u.getProperty(ApiTokenProperty.class);
if (t!=null && t.matchesPassword(password)) {
UserDetails userDetails = u.getUserDetailsForImpersonation();
Authentication auth = u.impersonate(userDetails);
SecurityListener.fireAuthenticated(userDetails);
SecurityContextHolder.getContext().setAuthentication(auth);
=======
{
User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password);
if(u != null){
SecurityContextHolder.getContext().setAuthentication(u.impersonate());
>>>>>>>
{
User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password);
if(u != null){
UserDetails userDetails = u.getUserDetailsForImpersonation();
Authentication auth = u.impersonate(userDetails);
SecurityListener.fireAuthenticated(userDetails);
SecurityContextHolder.getContext().setAuthentication(auth); |
<<<<<<<
import org.amahi.anywhere.activity.NavigationActivity;
=======
import org.amahi.anywhere.activity.ServerActivity;
import org.amahi.anywhere.activity.ServerAppActivity;
>>>>>>>
import org.amahi.anywhere.activity.NavigationActivity;
import org.amahi.anywhere.activity.ServerAppActivity;
<<<<<<<
NavigationActivity.class,
=======
ServerActivity.class,
ServerAppActivity.class,
>>>>>>>
NavigationActivity.class,
ServerAppActivity.class, |
<<<<<<<
import java.io.File;
=======
>>>>>>>
import java.io.File;
<<<<<<<
import jenkins.model.IdStrategy;
=======
>>>>>>>
import jenkins.model.IdStrategy;
<<<<<<<
import static org.junit.Assume.*;
=======
>>>>>>>
import static org.junit.Assume.*;
<<<<<<<
=======
@Test
// @Issue("SECURITY-180")
public void security180() throws Exception {
final GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false));
User alice = User.get("alice");
User bob = User.get("bob");
User anonymous = User.get("anonymous");
User admin = User.get("admin");
auth.add(Jenkins.READ, alice.getId());
auth.add(Jenkins.READ, bob.getId());
auth.add(Jenkins.ADMINISTER, admin.getId());
SecurityContextHolder.getContext().setAuthentication(admin.impersonate());
// Change token by admin
admin.getProperty(ApiTokenProperty.class).changeApiToken();
alice.getProperty(ApiTokenProperty.class).changeApiToken();
SecurityContextHolder.getContext().setAuthentication(bob.impersonate());
// Change own token
bob.getProperty(ApiTokenProperty.class).changeApiToken();
try {
alice.getProperty(ApiTokenProperty.class).changeApiToken();
fail("Bob should not be authorized to change alice's token");
} catch (AccessDeniedException expected) { }
try {
anonymous.getProperty(ApiTokenProperty.class).changeApiToken();
fail("Anonymous should not be authorized to change alice's token");
} catch (AccessDeniedException expected) { }
}
@Test
public void testGetDynamic() {
}
>>>>>>>
@Test
// @Issue("SECURITY-180")
public void security180() throws Exception {
final GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false));
User alice = User.get("alice");
User bob = User.get("bob");
User anonymous = User.get("anonymous");
User admin = User.get("admin");
auth.add(Jenkins.READ, alice.getId());
auth.add(Jenkins.READ, bob.getId());
auth.add(Jenkins.ADMINISTER, admin.getId());
SecurityContextHolder.getContext().setAuthentication(admin.impersonate());
// Change token by admin
admin.getProperty(ApiTokenProperty.class).changeApiToken();
alice.getProperty(ApiTokenProperty.class).changeApiToken();
SecurityContextHolder.getContext().setAuthentication(bob.impersonate());
// Change own token
bob.getProperty(ApiTokenProperty.class).changeApiToken();
try {
alice.getProperty(ApiTokenProperty.class).changeApiToken();
fail("Bob should not be authorized to change alice's token");
} catch (AccessDeniedException expected) { }
try {
anonymous.getProperty(ApiTokenProperty.class).changeApiToken();
fail("Anonymous should not be authorized to change alice's token");
} catch (AccessDeniedException expected) { }
} |
<<<<<<<
import static hudson.util.TimeUnit2.DAYS;
=======
>>>>>>>
import static hudson.util.TimeUnit2.DAYS;
<<<<<<<
import org.apache.commons.io.IOUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
=======
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
>>>>>>>
import org.apache.commons.io.IOUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
<<<<<<<
if (!DownloadSettings.get().isUseBrowser()) {
return "";
}
=======
if (!DownloadSettings.usePostBack()) {
return "";
}
>>>>>>>
if (!DownloadSettings.usePostBack()) {
return "";
}
<<<<<<<
* Loads JSON from a JSONP URL.
* Metadata for downloadables and update centers is offered in two formats, both designed for download from the browser (predating {@link DownloadSettings}):
* HTML using {@code postMessage} for newer browsers, and JSONP as a fallback.
* Confusingly, the JSONP files are given the {@code *.json} file extension, when they are really JavaScript and should be {@code *.js}.
* This method extracts the JSON from a JSONP URL, since that is what we actually want when we download from the server.
* (Currently the true JSON is not published separately, and extracting from the {@code *.json.html} is more work.)
* @param src a URL to a JSONP file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
*/
@Restricted(NoExternalUse.class)
public static String loadJSON(URL src) throws IOException {
InputStream is = ProxyConfiguration.open(src).getInputStream();
try {
String jsonp = IOUtils.toString(is, "UTF-8");
int start = jsonp.indexOf('{');
int end = jsonp.lastIndexOf('}');
if (start >= 0 && end > start) {
return jsonp.substring(start, end + 1);
} else {
throw new IOException("Could not find JSON in " + src);
}
} finally {
is.close();
}
}
/**
=======
* Loads JSON from a JSONP URL.
* Metadata for downloadables and update centers is offered in two formats, both designed for download from the browser (predating {@link DownloadSettings}):
* HTML using {@code postMessage} for newer browsers, and JSONP as a fallback.
* Confusingly, the JSONP files are given the {@code *.json} file extension, when they are really JavaScript and should be {@code *.js}.
* This method extracts the JSON from a JSONP URL, since that is what we actually want when we download from the server.
* (Currently the true JSON is not published separately, and extracting from the {@code *.json.html} is more work.)
* @param src a URL to a JSONP file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
*/
@Restricted(NoExternalUse.class)
public static String loadJSON(URL src) throws IOException {
InputStream is = ProxyConfiguration.open(src).getInputStream();
try {
String jsonp = IOUtils.toString(is, "UTF-8");
int start = jsonp.indexOf('{');
int end = jsonp.lastIndexOf('}');
if (start >= 0 && end > start) {
return jsonp.substring(start, end + 1);
} else {
throw new IOException("Could not find JSON in " + src);
}
} finally {
is.close();
}
}
/**
* Loads JSON from a JSON-with-{@code postMessage} URL.
* @param src a URL to a JSON HTML file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
*/
@Restricted(NoExternalUse.class)
public static String loadJSONHTML(URL src) throws IOException {
InputStream is = ProxyConfiguration.open(src).getInputStream();
try {
String jsonp = IOUtils.toString(is, "UTF-8");
String preamble = "window.parent.postMessage(JSON.stringify(";
int start = jsonp.indexOf(preamble);
int end = jsonp.lastIndexOf("),'*');");
if (start >= 0 && end > start) {
return jsonp.substring(start + preamble.length(), end).trim();
} else {
throw new IOException("Could not find JSON in " + src);
}
} finally {
is.close();
}
}
/**
>>>>>>>
* Loads JSON from a JSONP URL.
* Metadata for downloadables and update centers is offered in two formats, both designed for download from the browser (predating {@link DownloadSettings}):
* HTML using {@code postMessage} for newer browsers, and JSONP as a fallback.
* Confusingly, the JSONP files are given the {@code *.json} file extension, when they are really JavaScript and should be {@code *.js}.
* This method extracts the JSON from a JSONP URL, since that is what we actually want when we download from the server.
* (Currently the true JSON is not published separately, and extracting from the {@code *.json.html} is more work.)
* @param src a URL to a JSONP file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
*/
@Restricted(NoExternalUse.class)
public static String loadJSON(URL src) throws IOException {
InputStream is = ProxyConfiguration.open(src).getInputStream();
try {
String jsonp = IOUtils.toString(is, "UTF-8");
int start = jsonp.indexOf('{');
int end = jsonp.lastIndexOf('}');
if (start >= 0 && end > start) {
return jsonp.substring(start, end + 1);
} else {
throw new IOException("Could not find JSON in " + src);
}
} finally {
is.close();
}
}
/**
* Loads JSON from a JSON-with-{@code postMessage} URL.
* @param src a URL to a JSON HTML file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
*/
@Restricted(NoExternalUse.class)
public static String loadJSONHTML(URL src) throws IOException {
InputStream is = ProxyConfiguration.open(src).getInputStream();
try {
String jsonp = IOUtils.toString(is, "UTF-8");
String preamble = "window.parent.postMessage(JSON.stringify(";
int start = jsonp.indexOf(preamble);
int end = jsonp.lastIndexOf("),'*');");
if (start >= 0 && end > start) {
return jsonp.substring(start + preamble.length(), end).trim();
} else {
throw new IOException("Could not find JSON in " + src);
}
} finally {
is.close();
}
}
/**
<<<<<<<
if (!DownloadSettings.get().isUseBrowser()) {
throw new IOException("not allowed");
}
=======
DownloadSettings.checkPostBackAccess();
>>>>>>>
DownloadSettings.checkPostBackAccess();
<<<<<<<
@Restricted(NoExternalUse.class)
public FormValidation updateNow() throws IOException {
return load(loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))), System.currentTimeMillis());
=======
@Restricted(NoExternalUse.class)
public FormValidation updateNow() throws IOException {
return load(loadJSONHTML(new URL(getUrl() + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))), System.currentTimeMillis());
>>>>>>>
@Restricted(NoExternalUse.class)
public FormValidation updateNow() throws IOException {
return load(loadJSONHTML(new URL(getUrl() + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))), System.currentTimeMillis()); |
<<<<<<<
super(CRUMB_SALT.get(), SystemProperties.getString("hudson.security.csrf.requestfield", ".crumb"));
=======
super(CRUMB_SALT.get(), System.getProperty("hudson.security.csrf.requestfield", CrumbIssuer.DEFAULT_CRUMB_NAME));
>>>>>>>
super(CRUMB_SALT.get(), SystemProperties.getString("hudson.security.csrf.requestfield", CrumbIssuer.DEFAULT_CRUMB_NAME)); |
<<<<<<<
import javax.annotation.Nonnull;
=======
import javax.annotation.Nonnull;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
>>>>>>>
import javax.annotation.Nonnull;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
<<<<<<<
public @CheckForNull BuildPtr getOriginal() {
return original;
=======
public BuildPtr getOriginal() {
if (original != null && original.hasPermissionToDiscoverBuild()) {
return original;
}
return null;
>>>>>>>
public @CheckForNull BuildPtr getOriginal() {
if (original != null && original.hasPermissionToDiscoverBuild()) {
return original;
}
return null; |
<<<<<<<
import hudson.FilePath;
=======
import hudson.maven.reporters.MavenArtifactRecord;
import hudson.maven.reporters.SurefireArchiver;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
>>>>>>>
import hudson.FilePath;
import hudson.maven.reporters.MavenArtifactRecord;
import hudson.maven.reporters.SurefireArchiver;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
<<<<<<<
import hudson.util.ReflectionUtils;
=======
import org.apache.maven.BuildFailureException;
import org.apache.maven.artifact.versioning.ComparableVersion;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ReactorManager;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.monitor.event.EventDispatcher;
import org.apache.maven.project.MavenProject;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
>>>>>>>
import hudson.util.ReflectionUtils;
import org.apache.maven.BuildFailureException;
import org.apache.maven.artifact.versioning.ComparableVersion;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ReactorManager;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.monitor.event.EventDispatcher;
import org.apache.maven.project.MavenProject;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported; |
<<<<<<<
import hudson.views.ViewsTabBar;
=======
import com.gargoylesoftware.htmlunit.util.NameValuePair;
>>>>>>>
import hudson.views.ViewsTabBar;
<<<<<<<
import java.util.Collection;
=======
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.HashMap;
>>>>>>>
import java.util.Collection;
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.HashMap;
<<<<<<<
import static java.util.Arrays.asList;
=======
import static org.hamcrest.Matchers.*;
>>>>>>>
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.*;
<<<<<<<
=======
@Issue("JENKINS-21017")
@Test public void doConfigDotXmlReset() throws Exception {
ListView view = listView("v");
view.description = "one";
WebClient wc = j.createWebClient();
String xml = wc.goToXml("view/v/config.xml").getWebResponse().getContentAsString();
assertThat(xml, containsString("<description>one</description>"));
xml = xml.replace("<description>one</description>", "");
WebRequest req = new WebRequest(wc.createCrumbedUrl("view/v/config.xml"), HttpMethod.POST);
req.setRequestBody(xml);
req.setEncodingType(null);
wc.getPage(req);
assertEquals(null, view.getDescription()); // did not work
xml = new XmlFile(Jenkins.XSTREAM, new File(j.jenkins.getRootDir(), "config.xml")).asString();
assertThat(xml, not(containsString("<description>"))); // did not work
assertEquals(j.jenkins, view.getOwner());
}
>>>>>>>
@Issue("JENKINS-21017")
@Test public void doConfigDotXmlReset() throws Exception {
ListView view = listView("v");
view.description = "one";
WebClient wc = j.createWebClient();
String xml = wc.goToXml("view/v/config.xml").getWebResponse().getContentAsString();
assertThat(xml, containsString("<description>one</description>"));
xml = xml.replace("<description>one</description>", "");
WebRequest req = new WebRequest(wc.createCrumbedUrl("view/v/config.xml"), HttpMethod.POST);
req.setRequestBody(xml);
req.setEncodingType(null);
wc.getPage(req);
assertEquals(null, view.getDescription()); // did not work
xml = new XmlFile(Jenkins.XSTREAM, new File(j.jenkins.getRootDir(), "config.xml")).asString();
assertThat(xml, not(containsString("<description>"))); // did not work
assertEquals(j.jenkins, view.getOwner());
} |
<<<<<<<
=======
import hudson.remoting.Callable;
import java.io.ByteArrayOutputStream;
import jenkins.security.MasterToSlaveCallable;
>>>>>>>
import hudson.remoting.Callable;
import jenkins.security.MasterToSlaveCallable; |
<<<<<<<
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
=======
>>>>>>>
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
<<<<<<<
synchronized (this) { // could just make performDelete synchronized but overriders might not honor that
performDelete();
} // JENKINS-19446: leave synch block, but JENKINS-22001: still notify synchronously
invokeOnDeleted();
Jenkins.getInstance().rebuildDependencyGraphAsync();
=======
performDelete();
try {
invokeOnDeleted();
} catch (AbstractMethodError e) {
// ignore
}
Jenkins.getInstance().rebuildDependencyGraphAsync();
>>>>>>>
synchronized (this) { // could just make performDelete synchronized but overriders might not honor that
performDelete();
} // JENKINS-19446: leave synch block, but JENKINS-22001: still notify synchronously
invokeOnDeleted();
Jenkins.getInstance().rebuildDependencyGraphAsync();
<<<<<<<
new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
Items.whileUpdatingByXml(new Callable<Void,IOException>() {
@Override public Void call() throws IOException {
onLoad(getParent(), getRootDir().getName());
return null;
}
});
Jenkins.getInstance().rebuildDependencyGraphAsync();
=======
Object o = new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
if (o!=this) {
// ensure that we've got the same job type. extending this code to support updating
// to different job type requires destroying & creating a new job type
throw new IOException("Expecting "+this.getClass()+" but got "+o.getClass()+" instead");
}
Items.updatingByXml.set(true);
try {
onLoad(getParent(), getRootDir().getName());
} finally {
Items.updatingByXml.set(false);
}
Jenkins.getInstance().rebuildDependencyGraphAsync();
>>>>>>>
Object o = new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
if (o!=this) {
// ensure that we've got the same job type. extending this code to support updating
// to different job type requires destroying & creating a new job type
throw new IOException("Expecting "+this.getClass()+" but got "+o.getClass()+" instead");
}
Items.whileUpdatingByXml(new Callable<Void,IOException>() {
@Override public Void call() throws IOException {
onLoad(getParent(), getRootDir().getName());
return null;
}
});
Jenkins.getInstance().rebuildDependencyGraphAsync(); |
<<<<<<<
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit.DAYS.toMillis(365));
=======
webApp.setClassLoader(pluginManager.uberClassLoader);
webApp.setJsonInErrorMessageSanitizer(RedactSecretJsonInErrorMessageSanitizer.INSTANCE);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
>>>>>>>
webApp.setClassLoader(pluginManager.uberClassLoader);
webApp.setJsonInErrorMessageSanitizer(RedactSecretJsonInErrorMessageSanitizer.INSTANCE);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit.DAYS.toMillis(365)); |
<<<<<<<
terminated = true;
Jenkins instance = Jenkins.getInstanceOrNull();
if(instance!=null)
instance.cleanUp();
Thread t = initThread;
if (t != null && t.isAlive()) {
LOGGER.log(Level.INFO, "Shutting down a Jenkins instance that was still starting up", new Throwable("reason"));
t.interrupt();
}
=======
try {
terminated = true;
Jenkins instance = Jenkins.getInstance();
if(instance!=null)
instance.cleanUp();
Thread t = initThread;
if (t != null && t.isAlive()) {
LOGGER.log(Level.INFO, "Shutting down a Jenkins instance that was still starting up", new Throwable("reason"));
t.interrupt();
}
>>>>>>>
try {
terminated = true;
Jenkins instance = Jenkins.getInstanceOrNull();
if(instance!=null)
instance.cleanUp();
Thread t = initThread;
if (t != null && t.isAlive()) {
LOGGER.log(Level.INFO, "Shutting down a Jenkins instance that was still starting up", new Throwable("reason"));
t.interrupt();
} |
<<<<<<<
=======
import jenkins.SoloFilePathFilter;
import jenkins.model.Jenkins;
>>>>>>>
import jenkins.SoloFilePathFilter;
<<<<<<<
private File mkdirsE(File dir) throws IOException {
if (dir.exists()) {
return dir;
}
filterNonNull().mkdirs(dir);
return IOUtils.mkdirs(dir);
}
}
=======
private static final SoloFilePathFilter UNRESTRICTED = SoloFilePathFilter.wrap(FilePathFilter.UNRESTRICTED);
}
>>>>>>>
private File mkdirsE(File dir) throws IOException {
if (dir.exists()) {
return dir;
}
filterNonNull().mkdirs(dir);
return IOUtils.mkdirs(dir);
}
private static final SoloFilePathFilter UNRESTRICTED = SoloFilePathFilter.wrap(FilePathFilter.UNRESTRICTED);
} |
<<<<<<<
import jenkins.model.Jenkins;
=======
import jenkins.security.MasterToSlaveCallable;
>>>>>>>
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;
<<<<<<<
store = (channel==null ? FilePath.localChannel : channel).call(new Callable<FilePath, IOException>() {
=======
store = (channel==null ? MasterComputer.localChannel : channel).call(new MasterToSlaveCallable<FilePath, IOException>() {
>>>>>>>
store = (channel==null ? FilePath.localChannel : channel).call(new MasterToSlaveCallable<FilePath, IOException>() { |
<<<<<<<
import hudson.util.IOException2;
=======
import hudson.model.UnprotectedRootAction;
>>>>>>>
import hudson.util.IOException2;
import hudson.model.UnprotectedRootAction;
<<<<<<<
public class CLIAction implements RootAction, StaplerProxy {
=======
public class CLIAction implements UnprotectedRootAction {
>>>>>>>
public class CLIAction implements UnprotectedRootAction, StaplerProxy { |
<<<<<<<
import hudson.remoting.Callable;
=======
import jenkins.model.Jenkins;
>>>>>>>
<<<<<<<
import java.io.Console;
import java.io.IOException;
import jenkins.model.Jenkins;
import jenkins.security.ImpersonatingUserDetailsService;
import jenkins.security.SecurityListener;
=======
import jenkins.security.MasterToSlaveCallable;
>>>>>>>
import java.io.Console;
import java.io.IOException;
import jenkins.model.Jenkins;
import jenkins.security.ImpersonatingUserDetailsService;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
<<<<<<<
private static class InteractivelyAskForPassword implements Callable<String,IOException> {
=======
private static class InteractivelyAskForPassword extends MasterToSlaveCallable<String,IOException> {
@IgnoreJRERequirement
>>>>>>>
private static class InteractivelyAskForPassword extends MasterToSlaveCallable<String,IOException> { |
<<<<<<<
public AttributeEditor<?> createEditor(final Composite parent, final String functionId,
final FunctionParameterDefinition parameter, final ParameterValue initialValue) {
List<ParameterEditorFactory> factories = getFactories(new FactoryFilter<EditorFactory, ParameterEditorFactory>() {
@Override
public boolean acceptFactory(ParameterEditorFactory factory) {
return factory.getParameterName().equals(parameter.getName())
&& factory.getFunctionId().equals(functionId);
}
@Override
public boolean acceptCollection(
ExtensionObjectFactoryCollection<EditorFactory, ParameterEditorFactory> collection) {
return true;
}
});
=======
public Editor<?> createEditor(final Composite parent, final String functionId,
final FunctionParameter parameter, final ParameterValue initialValue) {
List<ParameterEditorFactory> factories = getFactories(
new FactoryFilter<EditorFactory, ParameterEditorFactory>() {
@Override
public boolean acceptFactory(ParameterEditorFactory factory) {
return factory.getParameterName().equals(parameter.getName())
&& factory.getFunctionId().equals(functionId);
}
@Override
public boolean acceptCollection(
ExtensionObjectFactoryCollection<EditorFactory, ParameterEditorFactory> collection) {
return true;
}
});
>>>>>>>
public AttributeEditor<?> createEditor(final Composite parent, final String functionId,
final FunctionParameterDefinition parameter, final ParameterValue initialValue) {
List<ParameterEditorFactory> factories = getFactories(
new FactoryFilter<EditorFactory, ParameterEditorFactory>() {
@Override
public boolean acceptFactory(ParameterEditorFactory factory) {
return factory.getParameterName().equals(parameter.getName())
&& factory.getFunctionId().equals(functionId);
}
@Override
public boolean acceptCollection(
ExtensionObjectFactoryCollection<EditorFactory, ParameterEditorFactory> collection) {
return true;
}
}); |
<<<<<<<
import eu.esdihumboldt.hale.common.align.service.FunctionService;
import eu.esdihumboldt.hale.common.align.service.TransformationFunctionService;
import eu.esdihumboldt.hale.common.align.service.impl.AlignmentFunctionService;
import eu.esdihumboldt.hale.common.align.service.impl.AlignmentTransformationFunctionService;
=======
import eu.esdihumboldt.hale.common.align.transformation.service.TransformationSchemas;
>>>>>>>
import eu.esdihumboldt.hale.common.align.service.FunctionService;
import eu.esdihumboldt.hale.common.align.service.TransformationFunctionService;
import eu.esdihumboldt.hale.common.align.service.impl.AlignmentFunctionService;
import eu.esdihumboldt.hale.common.align.service.impl.AlignmentTransformationFunctionService;
import eu.esdihumboldt.hale.common.align.transformation.service.TransformationSchemas;
<<<<<<<
addService(FunctionService.class, new AlignmentFunctionService(alignment));
addService(TransformationFunctionService.class,
new AlignmentTransformationFunctionService(alignment));
=======
// make TransformationSchemas service available
addService(TransformationSchemas.class, new TransformationSchemas() {
@Override
public SchemaSpace getSchemas(SchemaSpaceID spaceID) {
switch (spaceID) {
case SOURCE:
return sourceSchema;
case TARGET:
return targetSchema;
default:
return null;
}
}
});
>>>>>>>
addService(FunctionService.class, new AlignmentFunctionService(alignment));
addService(TransformationFunctionService.class,
new AlignmentTransformationFunctionService(alignment));
// make TransformationSchemas service available
addService(TransformationSchemas.class, new TransformationSchemas() {
@Override
public SchemaSpace getSchemas(SchemaSpaceID spaceID) {
switch (spaceID) {
case SOURCE:
return sourceSchema;
case TARGET:
return targetSchema;
default:
return null;
}
}
}); |
<<<<<<<
import eu.esdihumboldt.hale.common.headless.transform.filter.InstanceFilterDefinition;
=======
import eu.esdihumboldt.hale.common.headless.transform.validate.impl.DefaultTransformedInstanceValidator;
>>>>>>>
import eu.esdihumboldt.hale.common.headless.transform.filter.InstanceFilterDefinition;
import eu.esdihumboldt.hale.common.headless.transform.validate.impl.DefaultTransformedInstanceValidator; |
<<<<<<<
import eu.esdihumboldt.hale.ui.common.editors.AbstractAttributeEditor;
=======
import eu.esdihumboldt.hale.common.core.HalePlatform;
import eu.esdihumboldt.hale.ui.common.editors.AbstractEditor;
>>>>>>>
import eu.esdihumboldt.hale.common.core.HalePlatform;
import eu.esdihumboldt.hale.ui.common.editors.AbstractAttributeEditor; |
<<<<<<<
private Class<? extends ConnectionHelper> helperClass;
private ConnectionHelper helper = null;
=======
private final boolean isFileBased;
>>>>>>>
private Class<? extends ConnectionHelper> helperClass;
private ConnectionHelper helper = null;
private final boolean isFileBased;
<<<<<<<
try {
helperClass = (Class<? extends ConnectionHelper>) ExtensionUtil.loadClass(element,
"connectionHelper");
} catch (NullPointerException ex) {
// connectionHelper element is optional in driver configuration
helperClass = null;
}
=======
isFileBased = Boolean.valueOf(element.getAttribute("isFileBased"));
>>>>>>>
try {
helperClass = (Class<? extends ConnectionHelper>) ExtensionUtil.loadClass(element,
"connectionHelper");
} catch (NullPointerException ex) {
// connectionHelper element is optional in driver configuration
helperClass = null;
}
isFileBased = Boolean.valueOf(element.getAttribute("isFileBased"));
<<<<<<<
/**
* Get the Connection Helper associated with the driver configuration.
*
* @return the Connection Helper
*/
public ConnectionHelper getConnectionHelper() {
if (helperClass != null) {
try {
helper = helperClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
Throwables.propagate(e);
}
}
return helper;
}
=======
/**
* @return isFileBased
*/
public boolean isFileBased() {
return isFileBased;
}
>>>>>>>
/**
* Get the Connection Helper associated with the driver configuration.
*
* @return the Connection Helper
*/
public ConnectionHelper getConnectionHelper() {
if (helperClass != null) {
try {
helper = helperClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
Throwables.propagate(e);
}
}
return helper;
}
public boolean isFileBased() {
return isFileBased;
} |
<<<<<<<
* Indicates whether the path must be absolute;
* <code>false</code> by default.
*/
private boolean enforceAbsolute = false;
/**
* Indicates whether specifying an URI is allowed
*/
private boolean allowUri = false;
=======
* Indicates whether the path must be absolute; <code>false</code> by
* default.
*/
private boolean enforceAbsolute = false;
>>>>>>>
* Indicates whether specifying an URI is allowed
*/
private boolean allowUri = false;
/**
* Indicates whether the path must be absolute; <code>false</code> by
* default.
*/
private boolean enforceAbsolute = false;
<<<<<<<
} else {
File file = null;
if (allowUri) {
// check if string is an uri
try {
URI uri = new URI(path);
// check if the URI references a file
try {
file = new File(uri);
// is a file, just continue with normal validity check
} catch (IllegalArgumentException e) {
// no file
return isValid(uri);
}
} catch (URISyntaxException e) {
// ignore - no URI, try file
}
}
if (file == null) {
file = new File(path);
}
if (isValid(file)) {
if (enforceAbsolute && !file.isAbsolute()) {
msg = JFaceResources
.getString("FileFieldEditor.errorMessage2");//$NON-NLS-1$
=======
}
else {
File file = new File(path);
if (isValid(file)) {
if (enforceAbsolute && !file.isAbsolute()) {
msg = JFaceResources.getString("FileFieldEditor.errorMessage2");//$NON-NLS-1$
>>>>>>>
} else {
File file = null;
if (allowUri) {
// check if string is an uri
try {
URI uri = new URI(path);
// check if the URI references a file
try {
file = new File(uri);
// is a file, just continue with normal validity check
} catch (IllegalArgumentException e) {
// no file
return isValid(uri);
}
} catch (URISyntaxException e) {
// ignore - no URI, try file
}
}
if (file == null) {
file = new File(path);
}
if (isValid(file)) {
if (enforceAbsolute && !file.isAbsolute()) {
msg = JFaceResources.getString("FileFieldEditor.errorMessage2");//$NON-NLS-1$ |
<<<<<<<
=======
// texture chooser
textureInput.setCallback(new FileChooserField.FileSelected() {
@Override
public void selected(FileHandle fileHandle) {
if (fileHandle.exists()) {
if (modelInput.getFile() != null && modelInput.getFile().exists()) {
loadAndShowPreview(modelInput.getFile(), textureInput.getFile());
}
}
}
});
>>>>>>>
<<<<<<<
if(fileHandle.exists()) {
loadAndShowPreview(modelInput.getFile());
=======
if (fileHandle.exists()) {
if (textureInput.getFile() != null && textureInput.getFile().exists()) {
loadAndShowPreview(modelInput.getFile(), textureInput.getFile());
}
>>>>>>>
if(fileHandle.exists()) {
loadAndShowPreview(modelInput.getFile());
<<<<<<<
if(previewModel != null && previewInstance != null) {
EditorAssetManager assetManager = projectManager.current().assetManager;
=======
if (previewModel != null && previewInstance != null && name.getText().length() > 0) {
>>>>>>>
if (previewModel != null && previewInstance != null) {
EditorAssetManager assetManager = projectManager.current().assetManager; |
<<<<<<<
import edu.hm.hafner.analysis.Severity;
import io.jenkins.plugins.analysis.core.model.AnalysisResult;
=======
>>>>>>>
import edu.hm.hafner.analysis.Severity;
<<<<<<<
public HealthReport computeHealth(final AnalysisResult result) {
int relevantIssuesSize = 0;
=======
public HealthReport computeHealth(final Map<Priority, Integer> sizePerPriority) {
int size = 0;
>>>>>>>
public HealthReport computeHealth(final Map<Severity, Integer> sizePerPriority) {
int relevantIssuesSize = 0;
<<<<<<<
relevantIssuesSize += result.getTotalSize(Severity.of(priority));
=======
size += sizePerPriority.get(priority);
>>>>>>>
relevantIssuesSize += sizePerPriority.get(priority);
<<<<<<<
if (relevantIssuesSize < healthy) {
=======
if (size < healthy) {
>>>>>>>
if (relevantIssuesSize < healthy) {
<<<<<<<
if (relevantIssuesSize > unHealthy) {
=======
if (size > unHealthy) {
>>>>>>>
if (relevantIssuesSize > unHealthy) {
<<<<<<<
percentage = 100 - ((relevantIssuesSize - healthy) * 100 / (unHealthy - healthy));
=======
percentage = 100 - ((size - healthy) * 100 / (unHealthy - healthy));
>>>>>>>
percentage = 100 - ((relevantIssuesSize - healthy) * 100 / (unHealthy - healthy)); |
<<<<<<<
boolean showRelevance();
=======
void registerPopup( ListPopup popup );
>>>>>>>
boolean showRelevance();
void registerPopup( ListPopup popup ); |
<<<<<<<
public boolean onSingleTapConfirmed(MotionEvent e) {
// if minimalistic mode is enabled,
// and we want to display history on touch
if (isMinimalisticModeEnabled() && prefs.getBoolean("history-onclick", false)) {
// and we're currently in minimalistic mode with no results,
// and we're not looking at the app list
if (mainActivity.isViewingSearchResults() && mainActivity.searchEditText.getText().toString().isEmpty()) {
if (mainActivity.list.getAdapter() == null || mainActivity.list.getAdapter().isEmpty()) {
mainActivity.runTask(new HistorySearcher(mainActivity));
mainActivity.clearButton.setVisibility(View.VISIBLE);
mainActivity.menuButton.setVisibility(View.INVISIBLE);
}
}
}
if (isMinimalisticModeEnabledForFavorites()) {
mainActivity.favoritesBar.setVisibility(View.VISIBLE);
=======
public boolean onSingleTapUp(MotionEvent e) {
if(prefs.getBoolean("history-onclick", false)) {
doAction("display-history");
>>>>>>>
public boolean onSingleTapConfirmed(MotionEvent e) {
if(prefs.getBoolean("history-onclick", false)) {
doAction("display-history");
<<<<<<<
private boolean isGesturesEnabled() {
return prefs.getBoolean("enable-gestures", true);
}
private boolean isAccessibilityServiceEnabled(Context context, Class<? extends AccessibilityService> service) {
AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
for (AccessibilityServiceInfo enabledService : enabledServices) {
ServiceInfo enabledServiceInfo = enabledService.getResolveInfo().serviceInfo;
if (enabledServiceInfo.packageName.equals(context.getPackageName()) && enabledServiceInfo.name.equals(service.getName()))
return true;
}
return false;
}
=======
>>>>>>>
/**
* Are we allowed to run our AccessibilityService?
* @param context
* @param service
* @return
*/
private boolean isAccessibilityServiceEnabled(Context context, Class<? extends AccessibilityService> service) {
AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
for (AccessibilityServiceInfo enabledService : enabledServices) {
ServiceInfo enabledServiceInfo = enabledService.getResolveInfo().serviceInfo;
if (enabledServiceInfo.packageName.equals(context.getPackageName()) && enabledServiceInfo.name.equals(service.getName()))
return true;
}
return false;
} |
<<<<<<<
this.searchEditText = (SearchEditText) findViewById(R.id.searchEditText);
this.loaderSpinner = findViewById(R.id.loaderBar);
this.launcherButton = findViewById(R.id.launcherButton);
this.clearButton = findViewById(R.id.clearButton);
=======
this.searchEditText = findViewById(R.id.searchEditText);
>>>>>>>
this.searchEditText = findViewById(R.id.searchEditText);
this.loaderSpinner = findViewById(R.id.loaderBar);
this.launcherButton = findViewById(R.id.launcherButton);
this.clearButton = findViewById(R.id.clearButton);
<<<<<<<
=======
final ImageView launcherButton = findViewById(R.id.launcherButton);
>>>>>>> |
<<<<<<<
=======
import fr.neamar.summon.QueryInterface;
import fr.neamar.summon.SummonApplication;
import fr.neamar.summon.db.DBHelper;
>>>>>>>
import fr.neamar.summon.db.DBHelper;
<<<<<<<
import fr.neamar.summon.lite.QueryInterface;
import fr.neamar.summon.lite.SummonApplication;
import fr.neamar.summon.misc.DBHelper;
=======
>>>>>>>
import fr.neamar.summon.lite.QueryInterface;
import fr.neamar.summon.lite.SummonApplication; |
<<<<<<<
import android.view.ViewGroup;
=======
>>>>>>>
<<<<<<<
import fr.neamar.kiss.pojo.Pojo;
import fr.neamar.kiss.pojo.TagDummyPojo;
=======
import fr.neamar.kiss.pojo.AppPojo;
import fr.neamar.kiss.preference.ExcludePreferenceScreen;
import fr.neamar.kiss.preference.PreferenceScreenHelper;
import fr.neamar.kiss.preference.SwitchPreference;
>>>>>>>
import fr.neamar.kiss.pojo.AppPojo;
import fr.neamar.kiss.pojo.Pojo;
import fr.neamar.kiss.pojo.TagDummyPojo;
import fr.neamar.kiss.preference.ExcludePreferenceScreen;
import fr.neamar.kiss.preference.PreferenceScreenHelper;
import fr.neamar.kiss.preference.SwitchPreference; |
<<<<<<<
import android.os.Build;
import android.util.Log;
=======
>>>>>>>
import android.os.Build;
import android.util.Log;
<<<<<<<
boolean exceptionThrown = false;
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
search.setSourceBounds(v.getClipBounds());
}
search.putExtra(SearchManager.QUERY, searchPojo.query);
if (pojo.name.equals("Google")) {
// In the latest Google Now version, ACTION_WEB_SEARCH is broken when used with FLAG_ACTIVITY_NEW_TASK.
// Adding FLAG_ACTIVITY_CLEAR_TASK seems to fix the problem.
search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(search);
} catch (ActivityNotFoundException e) {
// This exception gets thrown if Google Search has been deactivated:
exceptionThrown = true;
}
}
if (exceptionThrown || !pojo.name.equals("Google")) {
String urlWithQuery = searchPojo.url.replace("{q}", searchPojo.query);
Uri uri = Uri.parse(urlWithQuery);
search = new Intent(Intent.ACTION_VIEW, uri);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(search);
}
catch (android.content.ActivityNotFoundException e) {
Log.w("SearchResult","Unable to run search for url: "+searchPojo.url);
}
}
=======
Uri uri = Uri.parse(searchPojo.url + searchPojo.query);
Intent search = new Intent(Intent.ACTION_VIEW, uri);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(search);
>>>>>>>
String urlWithQuery = searchPojo.url.replace("{q}", searchPojo.query);
Uri uri = Uri.parse(urlWithQuery);
Intent search = new Intent(Intent.ACTION_VIEW, uri);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(search);
}
catch (android.content.ActivityNotFoundException e) {
Log.w("SearchResult","Unable to run search for url: "+searchPojo.url);
} |
<<<<<<<
import android.annotation.TargetApi;
import android.app.AlertDialog;
=======
>>>>>>>
import android.app.AlertDialog; |
<<<<<<<
=======
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
>>>>>>>
<<<<<<<
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
=======
import androidx.annotation.NonNull;
import org.xmlpull.v1.XmlPullParser;
>>>>>>>
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
<<<<<<<
if (packageName.equalsIgnoreCase("default") || DrawableUtils.isIconsPackAdaptive(packageName)) {
if (!packageName.equals(mSystemPack.getPackPackageName()))
mSystemPack = new SystemIconPack(packageName);
=======
if (iconsPackPackageName.equalsIgnoreCase("default") || DrawableUtils.isIconsPackAdaptive(iconsPackPackageName)) {
>>>>>>>
if (packageName.equalsIgnoreCase("default") || DrawableUtils.isIconsPackAdaptive(packageName)) {
if (!packageName.equals(mSystemPack.getPackPackageName()))
mSystemPack = new SystemIconPack(packageName);
<<<<<<<
mIconPack = new IconPackXML(packageName);
mIconPack.load(ctx.getPackageManager());
=======
XmlPullParser xpp = null;
try {
// search appfilter.xml into icons pack apk resource folder
iconPackres = pm.getResourcesForApplication(iconsPackPackageName);
int appfilterid = iconPackres.getIdentifier("appfilter", "xml", iconsPackPackageName);
if (appfilterid > 0) {
xpp = iconPackres.getXml(appfilterid);
}
if (xpp != null) {
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
//parse <iconback> xml tags used as backgroud of generated icons
if (xpp.getName().equals("iconback")) {
for (int i = 0; i < xpp.getAttributeCount(); i++) {
if (xpp.getAttributeName(i).startsWith("img")) {
String drawableName = xpp.getAttributeValue(i);
Bitmap iconback = loadBitmap(drawableName);
if (iconback != null) {
backImages.add(iconback);
}
}
}
}
//parse <iconmask> xml tags used as mask of generated icons
else if (xpp.getName().equals("iconmask")) {
if (xpp.getAttributeCount() > 0 && xpp.getAttributeName(0).equals("img1")) {
String drawableName = xpp.getAttributeValue(0);
maskImage = loadBitmap(drawableName);
}
}
//parse <iconupon> xml tags used as front image of generated icons
else if (xpp.getName().equals("iconupon")) {
if (xpp.getAttributeCount() > 0 && xpp.getAttributeName(0).equals("img1")) {
String drawableName = xpp.getAttributeValue(0);
frontImage = loadBitmap(drawableName);
}
}
//parse <scale> xml tags used as scale factor of original bitmap icon
else if (xpp.getName().equals("scale") && xpp.getAttributeCount() > 0 && xpp.getAttributeName(0).equals("factor")) {
factor = Float.parseFloat(xpp.getAttributeValue(0));
}
//parse <item> xml tags for custom icons
if (xpp.getName().equals("item")) {
String componentName = null;
String drawableName = null;
for (int i = 0; i < xpp.getAttributeCount(); i++) {
if (xpp.getAttributeName(i).equals("component")) {
componentName = xpp.getAttributeValue(i);
} else if (xpp.getAttributeName(i).equals("drawable")) {
drawableName = xpp.getAttributeValue(i);
}
}
if (!packagesDrawables.containsKey(componentName)) {
packagesDrawables.put(componentName, drawableName);
}
}
}
eventType = xpp.next();
}
}
} catch (Exception e) {
Log.e(TAG, "Error parsing appfilter.xml " + e);
}
}
private Bitmap loadBitmap(String drawableName) {
int id = iconPackres.getIdentifier(drawableName, "drawable", iconsPackPackageName);
if (id > 0) {
Drawable bitmap = iconPackres.getDrawable(id);
if (bitmap instanceof BitmapDrawable) {
return ((BitmapDrawable) bitmap).getBitmap();
}
}
return null;
}
@NonNull
private Drawable getDefaultAppDrawable(ComponentName componentName, UserHandle userHandle) {
try {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
LauncherApps launcher = (LauncherApps) ctx.getSystemService(Context.LAUNCHER_APPS_SERVICE);
List<LauncherActivityInfo> icons = launcher.getActivityList(componentName.getPackageName(), userHandle.getRealHandle());
for (LauncherActivityInfo info : icons) {
if (info.getComponentName().equals(componentName)) {
Drawable icon = info.getBadgedIcon(0);
// Handle the adaptive icons
if(DrawableUtils.isIconsPackAdaptive(iconsPackPackageName)) {
return DrawableUtils.handleAdaptiveIcons(ctx, icon);
}
else {
return icon;
}
}
}
// This should never happen, let's just return the first icon
return icons.get(0).getBadgedIcon(0);
} else {
return pm.getActivityIcon(componentName);
}
} catch (NameNotFoundException | IndexOutOfBoundsException e) {
Log.e(TAG, "Unable to found component " + componentName.toString() + e);
return new ColorDrawable(Color.WHITE);
}
>>>>>>>
mIconPack = new IconPackXML(packageName);
mIconPack.load(ctx.getPackageManager());
<<<<<<<
String iconsPackPackageName = mIconPack != null ? mIconPack.getPackPackageName() : mSystemPack.getPackPackageName();
return new File(getIconsCacheDir(), iconsPackPackageName + "_" + key.hashCode() + ".png");
=======
return new File(getIconsCacheDir(), iconsPackPackageName + "_" + key.hashCode() + ".png");
>>>>>>>
String iconsPackPackageName = getIconPack().getPackPackageName();
return new File(getIconsCacheDir(), iconsPackPackageName + "_" + key.hashCode() + ".png");
<<<<<<<
public Drawable getCustomIcon(String componentName, long customIcon) {
if (customIcon == 0)
return null;
try {
FileInputStream fis = new FileInputStream(customIconFileName(componentName, customIcon));
BitmapDrawable drawable =
new BitmapDrawable(this.ctx.getResources(), BitmapFactory.decodeStream(fis));
fis.close();
return drawable;
} catch (Exception e) {
Log.e(TAG, "Unable to get custom icon " + e);
}
return null;
}
private void removeStoredDrawable(@NonNull File drawableFile) {
try {
//noinspection ResultOfMethodCallIgnored
drawableFile.delete();
} catch (Exception e) {
Log.e(TAG, "stored drawable " + drawableFile + " can't be deleted!", e);
}
}
public void changeAppIcon(AppResult appResult, Drawable drawable) {
long customIconId = KissApplication.getApplication(ctx).getDataHandler().setCustomAppIcon(appResult.getComponentName());
storeDrawable(customIconFileName(appResult.getComponentName(), customIconId), drawable);
appResult.setCustomIcon(customIconId, drawable);
}
public void restoreAppIcon(AppResult appResult) {
long customIconId = KissApplication.getApplication(ctx).getDataHandler().removeCustomAppIcon(appResult.getComponentName());
removeStoredDrawable(customIconFileName(appResult.getComponentName(), customIconId));
appResult.clearCustomIcon();
}
=======
// Before we fixed the cache path actually returning a folder, a lot of icons got dumped
// directly in ctx.getCacheDir() so we need to clean it
private void clearOldCache() {
File newCacheDir = new File(this.ctx.getCacheDir(), "icons");
if (!newCacheDir.isDirectory()) {
File[] fileList = ctx.getCacheDir().listFiles();
if (fileList != null) {
int count = 0;
for (File file : fileList) {
if (file.isFile())
count += file.delete() ? 1 : 0;
}
Log.i(TAG, "Removed " + count + " cache file(s) from the old path");
}
}
}
>>>>>>>
// Before we fixed the cache path actually returning a folder, a lot of icons got dumped
// directly in ctx.getCacheDir() so we need to clean it
private void clearOldCache() {
File newCacheDir = new File(this.ctx.getCacheDir(), "icons");
if (!newCacheDir.isDirectory()) {
File[] fileList = ctx.getCacheDir().listFiles();
if (fileList != null) {
int count = 0;
for (File file : fileList) {
if (file.isFile())
count += file.delete() ? 1 : 0;
}
Log.i(TAG, "Removed " + count + " cache file(s) from the old path");
}
}
}
public Drawable getCustomIcon(String componentName, long customIcon) {
if (customIcon == 0)
return null;
try {
FileInputStream fis = new FileInputStream(customIconFileName(componentName, customIcon));
BitmapDrawable drawable =
new BitmapDrawable(this.ctx.getResources(), BitmapFactory.decodeStream(fis));
fis.close();
return drawable;
} catch (Exception e) {
Log.e(TAG, "Unable to get custom icon " + e);
}
return null;
}
private void removeStoredDrawable(@NonNull File drawableFile) {
try {
//noinspection ResultOfMethodCallIgnored
drawableFile.delete();
} catch (Exception e) {
Log.e(TAG, "stored drawable " + drawableFile + " can't be deleted!", e);
}
}
public void changeAppIcon(AppResult appResult, Drawable drawable) {
long customIconId = KissApplication.getApplication(ctx).getDataHandler().setCustomAppIcon(appResult.getComponentName());
storeDrawable(customIconFileName(appResult.getComponentName(), customIconId), drawable);
appResult.setCustomIcon(customIconId, drawable);
}
public void restoreAppIcon(AppResult appResult) {
long customIconId = KissApplication.getApplication(ctx).getDataHandler().removeCustomAppIcon(appResult.getComponentName());
removeStoredDrawable(customIconFileName(appResult.getComponentName(), customIconId));
appResult.clearCustomIcon();
} |
<<<<<<<
// add views to view hierarchy
for (ViewHolder viewHolder : favoritesViews) {
assert viewHolder.view != null;
mainActivity.favoritesBar.addView(viewHolder.view);
viewHolder.view.setOnDragListener(this);
viewHolder.view.setOnTouchListener(this);
viewHolder.view.setVisibility(View.VISIBLE);
}
if (notificationPrefs != null) {
int dotColor;
if (isExternalFavoriteBarEnabled()) {
dotColor = UIColors.getPrimaryColor(mainActivity);
} else {
dotColor = Color.WHITE;
=======
// We don't have enough data in our current ViewHolder, add a new one
if(i >= currentFavCount) {
favoritesBar.addView(viewHolder.view);
}
else {
// Check if view is different
View currentView = favoritesBar.getChildAt(i);
if(currentView != viewHolder.view) {
if(viewHolder.view.getParent() != null) {
((ViewGroup) viewHolder.view.getParent()).removeView(viewHolder.view);
}
favoritesBar.addView(viewHolder.view, i);
};
>>>>>>>
// We don't have enough data in our current ViewHolder, add a new one
if(i >= currentFavCount) {
favoritesBar.addView(viewHolder.view);
}
else {
// Check if view is different
View currentView = favoritesBar.getChildAt(i);
if(currentView != viewHolder.view) {
if(viewHolder.view.getParent() != null) {
((ViewGroup) viewHolder.view.getParent()).removeView(viewHolder.view);
}
favoritesBar.addView(viewHolder.view, i);
};
<<<<<<<
KissApplication.getApplication(mainActivity).getDataHandler().setFavoritePosition(mainActivity, draggedApp.result.getPojoId(), potentialNewIndex);
}
=======
draggedView.post(() -> {
// Signals to a View that the drag and drop operation has concluded.
// If event result is set, this means the dragged view was dropped in target
if (event.getResult()) {
KissApplication.getApplication(mainActivity).getDataHandler().setFavoritePosition(mainActivity, draggedApp.result.getPojoId(), leftSide ? pos - 1 : pos);
draggedView.post(() -> draggedView.setVisibility(View.VISIBLE));
mainActivity.onFavoriteChange();
} else {
draggedView.setVisibility(View.VISIBLE);
}
});
>>>>>>>
draggedView.post(() -> {
// Signals to a View that the drag and drop operation has concluded.
// If event result is set, this means the dragged view was dropped in target
if (event.getResult()) {
KissApplication.getApplication(mainActivity).getDataHandler().setFavoritePosition(mainActivity, draggedApp.result.getPojoId(), potentialNewIndex);
draggedView.setVisibility(View.VISIBLE);
mainActivity.onFavoriteChange();
} else {
draggedView.setVisibility(View.VISIBLE);
}
}); |
<<<<<<<
import fr.neamar.summon.lite.R;
=======
import android.widget.Toast;
import fr.neamar.summon.R;
>>>>>>>
import fr.neamar.summon.lite.R;
import android.widget.Toast; |
<<<<<<<
private LinkedBlockingDeque<EventData> eventQueue = new LinkedBlockingDeque<>();
private boolean stop = false;
private Thread eventThread = new Thread(() -> {
=======
private final LinkedBlockingDeque<EventData> eventQueue = new LinkedBlockingDeque<>();
boolean stop = false;
Thread eventThread = new Thread(() -> {
>>>>>>>
private final LinkedBlockingDeque<EventData> eventQueue = new LinkedBlockingDeque<>();
private boolean stop = false;
private Thread eventThread = new Thread(() -> { |
<<<<<<<
import static com.willwinder.universalgcodesender.model.UGSEvent.ControlState.COMM_CHECK;
import static com.willwinder.universalgcodesender.model.UGSEvent.ControlState.COMM_DISCONNECTED;
import static com.willwinder.universalgcodesender.model.UGSEvent.ControlState.COMM_IDLE;
import static com.willwinder.universalgcodesender.model.UGSEvent.ControlState.COMM_SENDING;
import static com.willwinder.universalgcodesender.model.UGSEvent.ControlState.COMM_SENDING_PAUSED;
=======
>>>>>>> |
<<<<<<<
import com.willwinder.ugs.nbp.core.control.RunActionService;
import com.willwinder.ugs.nbp.core.services.PendantService;
=======
import com.willwinder.ugs.nbp.core.services.OverrideActionService;
import com.willwinder.ugs.nbp.core.services.PendantService;
>>>>>>>
import com.willwinder.ugs.nbp.core.services.OverrideActionService;
import com.willwinder.ugs.nbp.core.services.PendantService;
<<<<<<<
logger.info("Loading ActionService...");
Lookup.getDefault().lookup(RunActionService.class);
logger.info("Loading MacroService...");
=======
System.out.println("Loading OverrideActionService...");
Lookup.getDefault().lookup(OverrideActionService.class);
System.out.println("Loading MacroService...");
>>>>>>>
logger.info("Loading OverrideActionService...");
Lookup.getDefault().lookup(OverrideActionService.class);
logger.info("Loading MacroService..."); |
<<<<<<<
import com.willwinder.ugs.nbp.jog.actions.UseSeparateStepSizeAction;
import com.willwinder.universalgcodesender.model.UnitUtils;
import com.willwinder.universalgcodesender.services.JogService;
import org.mockito.Mockito;
=======
>>>>>>>
<<<<<<<
JogService jogService = Mockito.mock(JogService.class);
when(jogService.getUnits()).thenReturn(UnitUtils.Units.INCH);
jogPanel = new JogPanel(jogService, new UseSeparateStepSizeAction().getMenuPresenter());
=======
jogPanel = new JogPanel();
>>>>>>>
jogPanel = new JogPanel(); |
<<<<<<<
if (backend.getSettings().isDisplayStateColor()) {
Color background = ThemeColors.GREY;
String text = Utils.getControllerStateText(state);
if (state == ControllerState.ALARM) {
background = ThemeColors.RED;
} else if (state == ControllerState.HOLD) {
background = ThemeColors.ORANGE;
} else if (state == ControllerState.DOOR) {
background = ThemeColors.ORANGE;
} else if (state == ControllerState.RUN) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.JOG) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.HOME) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.CHECK) {
background = ThemeColors.LIGHT_BLUE;
} else if (state == ControllerState.IDLE) {
background = ThemeColors.GREY;
}
this.activeStatePanel.setBackground(background);
this.activeStateValueLabel.setText(text.toUpperCase());
=======
Color background = ThemeColors.GREY;
String text = Utils.getControllerStateText(state);
if (state == ControllerState.ALARM) {
background = ThemeColors.RED;
} else if (state == ControllerState.HOLD) {
background = ThemeColors.ORANGE;
} else if (state == ControllerState.DOOR) {
background = ThemeColors.ORANGE;
} else if (state == ControllerState.RUN) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.JOG) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.CHECK) {
background = ThemeColors.LIGHT_BLUE;
} else if (state == ControllerState.IDLE) {
background = ThemeColors.GREY;
>>>>>>>
Color background = ThemeColors.GREY;
String text = Utils.getControllerStateText(state);
if (state == ControllerState.ALARM) {
background = ThemeColors.RED;
} else if (state == ControllerState.HOLD) {
background = ThemeColors.ORANGE;
} else if (state == ControllerState.DOOR) {
background = ThemeColors.ORANGE;
} else if (state == ControllerState.RUN) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.JOG) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.HOME) {
background = ThemeColors.GREEN;
} else if (state == ControllerState.CHECK) {
background = ThemeColors.LIGHT_BLUE;
} else if (state == ControllerState.IDLE) {
background = ThemeColors.GREY; |
<<<<<<<
@Test
public void processSleepCommand() {
String command = "$SLP";
List<String> args = GcodePreprocessorUtils.splitCommand(command);
assertEquals(1, args.size());
assertEquals("$SLP", args.get(0));
}
=======
@Test
public void testSplitCommand() {
List<String> splitted = GcodePreprocessorUtils.splitCommand("G53F100S1300");
assertEquals(3, splitted.size());
assertEquals("G53", splitted.get(0));
assertEquals("F100", splitted.get(1));
assertEquals("S1300", splitted.get(2));
splitted = GcodePreprocessorUtils.splitCommand("G53G90.1S1300");
assertEquals(3, splitted.size());
assertEquals("G90.1", splitted.get(1));
splitted = GcodePreprocessorUtils.splitCommand("G53G90_1S1300");
assertEquals(4, splitted.size());
assertEquals("G90", splitted.get(1));
assertEquals("1", splitted.get(2));
}
>>>>>>>
@Test
public void processSleepCommand() {
String command = "$SLP";
List<String> args = GcodePreprocessorUtils.splitCommand(command);
assertEquals(1, args.size());
assertEquals("$SLP", args.get(0));
}
@Test
public void testSplitCommand() {
List<String> splitted = GcodePreprocessorUtils.splitCommand("G53F100S1300");
assertEquals(3, splitted.size());
assertEquals("G53", splitted.get(0));
assertEquals("F100", splitted.get(1));
assertEquals("S1300", splitted.get(2));
splitted = GcodePreprocessorUtils.splitCommand("G53G90.1S1300");
assertEquals(3, splitted.size());
assertEquals("G90.1", splitted.get(1));
splitted = GcodePreprocessorUtils.splitCommand("G53G90_1S1300");
assertEquals(4, splitted.size());
assertEquals("G90", splitted.get(1));
assertEquals("1", splitted.get(2));
} |
<<<<<<<
boolean G91Mode = false;
long lastResponse = Long.MIN_VALUE;
=======
// boolean G91Mode = false;
>>>>>>>
// boolean G91Mode = false;
long lastResponse = Long.MIN_VALUE; |
<<<<<<<
import com.willwinder.universalgcodesender.uielements.LengthLimitedDocument;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
=======
import java.awt.*;
>>>>>>>
import com.willwinder.universalgcodesender.uielements.LengthLimitedDocument;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.*;
<<<<<<<
.addContainerGap(27, Short.MAX_VALUE))
=======
.addContainerGap(45, Short.MAX_VALUE))
>>>>>>>
.addContainerGap(27, Short.MAX_VALUE))
<<<<<<<
.addContainerGap(10, Short.MAX_VALUE))
=======
.addContainerGap(23, Short.MAX_VALUE))
>>>>>>>
.addContainerGap(23, Short.MAX_VALUE))
<<<<<<<
private void showCommandTableCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showCommandTableCheckBoxActionPerformed
showCommandTable(showCommandTableCheckBox.isSelected());
}//GEN-LAST:event_showCommandTableCheckBoxActionPerformed
private void showCommandTable(Boolean enabled) {
if (enabled && (backend.isConnected() && !backend.isIdle())) {
MainWindow.displayErrorDialog(Localization.getString("mainWindow.error.showTableActive"));
showCommandTableCheckBox.setSelected(false);
return;
}
this.commandTable.clear();
this.bottomTabbedPane.setEnabledAt(1, enabled);
commandTableScrollPane.setEnabled(enabled);
if (!enabled) {
this.bottomTabbedPane.setSelectedIndex(0);
} else {
this.bottomTabbedPane.setSelectedIndex(1);
}
}
private void executeCustomGcode(String str)
=======
public void executeCustomGcode(String str)
>>>>>>>
private void showCommandTableCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showCommandTableCheckBoxActionPerformed
showCommandTable(showCommandTableCheckBox.isSelected());
}//GEN-LAST:event_showCommandTableCheckBoxActionPerformed
private void showCommandTable(Boolean enabled) {
if (enabled && (backend.isConnected() && !backend.isIdle())) {
MainWindow.displayErrorDialog(Localization.getString("mainWindow.error.showTableActive"));
showCommandTableCheckBox.setSelected(false);
return;
}
this.commandTable.clear();
this.bottomTabbedPane.setEnabledAt(1, enabled);
commandTableScrollPane.setEnabled(enabled);
if (!enabled) {
this.bottomTabbedPane.setSelectedIndex(0);
} else {
this.bottomTabbedPane.setSelectedIndex(1);
}
}
public void executeCustomGcode(String str)
<<<<<<<
private String getNewline() {
return "\r\n";
/*
if (lineBreakNR.isSelected())
return "\n\r";
else if (lineBreakRN.isSelected())
return "\r\n";
else if (lineBreakN.isSelected())
return "\n";
else
return "wtfbbq";
*/
}
=======
void clearTable() {
this.commandTable.clear();
}
>>>>>>>
void clearTable() {
this.commandTable.clear();
} |
<<<<<<<
RunApp.start(S.beforeLast(className, "."));
}
public static Network network() {
return network;
}
private static boolean isItPackageName(String s) {
if (s.length() < 4) {
return false;
}
if (s.contains(" ") || s.contains("\t") || !s.contains(".")) {
return false;
}
if (Character.isUpperCase(s.charAt(0))) {
return false;
}
return isFullyQualifiedClassname(s);
}
private static boolean isFullyQualifiedClassname(String s) {
if (s == null) return false;
String[] parts = s.split("[\\.]");
if (parts.length == 0) return false;
for (String part : parts) {
CharacterIterator iter = new StringCharacterIterator(part);
// Check first character (there should at least be one character for each part) ...
char c = iter.first();
if (c == CharacterIterator.DONE) return false;
if (!Character.isJavaIdentifierStart(c) && !Character.isIdentifierIgnorable(c)) return false;
c = iter.next();
// Check the remaining characters, if there are any ...
while (c != CharacterIterator.DONE) {
if (!Character.isJavaIdentifierPart(c) && !Character.isIdentifierIgnorable(c)) return false;
c = iter.next();
}
}
return true;
=======
RunApp.start(null, Version.appVersion(), S.beforeLast(className, "."));
>>>>>>>
RunApp.start(null, Version.appVersion(), S.beforeLast(className, "."));
}
public static Network network() {
return network;
<<<<<<<
public static void start(String appNameOrScanPackage) throws Exception {
if (isItPackageName(appNameOrScanPackage)) {
RunApp.start(appNameOrScanPackage);
} else {
// it must be an application name
StackTraceElement[] sa = new Throwable().getStackTrace();
E.unexpectedIf(sa.length < 2, "Whoops!");
StackTraceElement ste = sa[1];
String className = ste.getClassName();
E.unexpectedIf(!className.contains("."), "The main class must have package name to use Act");
RunApp.start(appNameOrScanPackage, Version.appVersion(), S.beforeLast(className, "."));
}
=======
public static void start(String appName) throws Exception {
StackTraceElement[] sa = new RuntimeException().getStackTrace();
E.unexpectedIf(sa.length < 2, "Whoops!");
StackTraceElement ste = sa[1];
String className = ste.getClassName();
E.unexpectedIf(!className.contains("."), "The main class must have package name to use Act");
RunApp.start(appName, Version.appVersion(), S.beforeLast(className, "."));
>>>>>>>
public static void start(String appName) throws Exception {
StackTraceElement[] sa = new RuntimeException().getStackTrace();
E.unexpectedIf(sa.length < 2, "Whoops!");
StackTraceElement ste = sa[1];
String className = ste.getClassName();
E.unexpectedIf(!className.contains("."), "The main class must have package name to use Act");
RunApp.start(appName, Version.appVersion(), S.beforeLast(className, ".")); |
<<<<<<<
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
=======
>>>>>>>
<<<<<<<
private ConcurrentMap<App, CookieResolver> resolvers = new ConcurrentHashMap<>();
private volatile CookieResolver theResolver = null;
=======
private CookieResolver theResolver = null;
>>>>>>>
private volatile CookieResolver theResolver = null;
<<<<<<<
return getResolver(context.app());
=======
App app = context.app();
if (theResolver == null) {
theResolver = new CookieResolver(app);
}
return theResolver;
>>>>>>>
return getResolver(context.app());
<<<<<<<
public static class CookieResolver {
=======
static class CookieResolver extends LogSupport {
>>>>>>>
public static class CookieResolver extends LogSupport { |
<<<<<<<
protected final void setValue(String value) {
if (MiscUtil.isEmptyString(value)) {
return;
}
setValueInternal(value);
if (myOnValueSetAction != null) {
myOnValueSetAction.run();
}
}
protected abstract void setValueInternal(String value);
=======
>>>>>>> |
<<<<<<<
=======
private static class ParagonInfoReader extends ZLXMLReaderAdapter {
private final Context myContext;
private int myCounter;
ParagonInfoReader(Context context) {
myContext = context;
}
@Override
public boolean dontCacheAttributeValues() {
return true;
}
@Override
public boolean startElementHandler(String tag, ZLStringMap attributes) {
if ("dictionary".equals(tag)) {
final String id = attributes.getValue("id");
final String title = attributes.getValue("title");
final PackageInfo info = new PackageInfo(
String.valueOf(++myCounter),
attributes.getValue("package"),
".Start",
attributes.getValue("title"),
Intent.ACTION_VIEW,
null,
attributes.getValue("pattern")
);
if (PackageUtil.canBeStarted(myContext, info.getDictionaryIntent("test"), false)) {
ourInfos.put(info, FLAG_SHOW_AS_DICTIONARY | FLAG_INSTALLED_ONLY);
}
}
return false;
}
}
>>>>>>>
<<<<<<<
private static Intent getDictionaryIntent(String text, boolean singleWord) {
return getDictionaryIntent(getCurrentDictionaryInfo(singleWord), text);
}
public static Intent getDictionaryIntent(PackageInfo dictionaryInfo, String text) {
final Intent intent = new Intent(dictionaryInfo.IntentAction);
if (dictionaryInfo.PackageName != null) {
String cls = dictionaryInfo.ClassName;
if (cls != null) {
if (cls.startsWith(".")) {
cls = dictionaryInfo.PackageName + cls;
}
intent.setComponent(new ComponentName(
dictionaryInfo.PackageName, cls
));
}
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
text = dictionaryInfo.IntentDataPattern.replace("%s", text);
if (dictionaryInfo.IntentKey != null) {
return intent.putExtra(dictionaryInfo.IntentKey, text);
} else {
return intent.setData(Uri.parse(text));
}
}
public static class PopupFrameMetric {
public final int Height;
public final int Gravity;
PopupFrameMetric(DisplayMetrics metrics, int selectionTop, int selectionBottom) {
final int screenHeight = metrics.heightPixels;
final int topSpace = selectionTop;
final int bottomSpace = metrics.heightPixels - selectionBottom;
final boolean showAtBottom = bottomSpace >= topSpace;
final int space = (showAtBottom ? bottomSpace : topSpace) - metrics.densityDpi / 12;
final int maxHeight = Math.min(metrics.densityDpi * 20 / 12, screenHeight * 2 / 3);
final int minHeight = Math.min(metrics.densityDpi * 10 / 12, screenHeight * 2 / 3);
Height = Math.max(minHeight, Math.min(maxHeight, space));
Gravity = showAtBottom ? android.view.Gravity.BOTTOM : android.view.Gravity.TOP;
}
}
=======
>>>>>>>
public static class PopupFrameMetric {
public final int Height;
public final int Gravity;
PopupFrameMetric(DisplayMetrics metrics, int selectionTop, int selectionBottom) {
final int screenHeight = metrics.heightPixels;
final int topSpace = selectionTop;
final int bottomSpace = metrics.heightPixels - selectionBottom;
final boolean showAtBottom = bottomSpace >= topSpace;
final int space = (showAtBottom ? bottomSpace : topSpace) - metrics.densityDpi / 12;
final int maxHeight = Math.min(metrics.densityDpi * 20 / 12, screenHeight * 2 / 3);
final int minHeight = Math.min(metrics.densityDpi * 10 / 12, screenHeight * 2 / 3);
Height = Math.max(minHeight, Math.min(maxHeight, space));
Gravity = showAtBottom ? android.view.Gravity.BOTTOM : android.view.Gravity.TOP;
}
}
<<<<<<<
if (info instanceof OpenDictionaryPackageInfo) {
Log.d("FBReader", "DictionaryUtil - work with Open Dictionary API :" + text);
final OpenDictionaryPackageInfo openDictionary = (OpenDictionaryPackageInfo)info;
openDictionary.Flyout.showTranslation(activity, text, frameMetrics);
return;
}
final Intent intent = getDictionaryIntent(info, text);
=======
final Intent intent = info.getDictionaryIntent(text);
>>>>>>>
if (info instanceof OpenDictionaryPackageInfo) {
Log.d("FBReader", "DictionaryUtil - work with Open Dictionary API :" + text);
final OpenDictionaryPackageInfo openDictionary = (OpenDictionaryPackageInfo)info;
openDictionary.Flyout.showTranslation(activity, text, frameMetrics);
return;
}
final Intent intent = info.getDictionaryIntent(text); |
<<<<<<<
String litresRel = null;
int catalogType = NetworkCatalogItem.CATALOG_OTHER;
for (ATOMLink link : entry.Links) {
=======
boolean litresCatalogue = false;
NetworkCatalogItem.CatalogType catalogType = NetworkCatalogItem.CatalogType.OTHER;
for (ATOMLink link: entry.Links) {
>>>>>>>
String litresRel = null;
NetworkCatalogItem.CatalogType catalogType = NetworkCatalogItem.CatalogType.OTHER;
for (ATOMLink link : entry.Links) { |
<<<<<<<
private final Accessibility myAccessibility;
public final int CatalogType;
=======
public final int Visibility;
private final CatalogType myCatalogType;
>>>>>>>
private final Accessibility myAccessibility;
private final CatalogType myCatalogType;
<<<<<<<
* Creates new NetworkCatalogItem instance with <code>Accessibility.ALWAYS</code> accessibility and <code>CATALOG_OTHER</code> type.
=======
* Creates new NetworkCatalogItem instance with <code>VISIBLE_ALWAYS</code> visibility and <code>CatalogType.OTHER</code> type.
>>>>>>>
* Creates new NetworkCatalogItem instance with <code>Accessibility.ALWAYS</code> accessibility and <code>CatalogType.OTHER</code> type.
<<<<<<<
public NetworkCatalogItem(INetworkLink link, String title, String summary, String cover, Map<Integer, String> urlByType, Accessibility accessibility) {
this(link, title, summary, cover, urlByType, accessibility, CATALOG_OTHER);
=======
public NetworkCatalogItem(INetworkLink link, String title, String summary, String cover, Map<Integer, String> urlByType, int visibility) {
this(link, title, summary, cover, urlByType, visibility, CatalogType.OTHER);
>>>>>>>
public NetworkCatalogItem(INetworkLink link, String title, String summary, String cover, Map<Integer, String> urlByType, Accessibility accessibility) {
this(link, title, summary, cover, urlByType, accessibility, CatalogType.OTHER);
<<<<<<<
myAccessibility = accessibility;
CatalogType = catalogType;
=======
Visibility = visibility;
myCatalogType = catalogType;
>>>>>>>
myAccessibility = accessibility;
myCatalogType = catalogType;
<<<<<<<
public ZLBoolean3 getVisibility() {
final NetworkAuthenticationManager mgr = Link.authenticationManager();
switch (myAccessibility) {
default:
=======
public final CatalogType getCatalogType() {
return myCatalogType;
}
public int getVisibility() {
if (Visibility == VISIBLE_ALWAYS) {
return ZLBoolean3.B3_TRUE;
}
if (Visibility == VISIBLE_LOGGED_USER) {
if (Link.authenticationManager() == null) {
>>>>>>>
public final CatalogType getCatalogType() {
return myCatalogType;
}
public ZLBoolean3 getVisibility() {
final NetworkAuthenticationManager mgr = Link.authenticationManager();
switch (myAccessibility) {
default: |
<<<<<<<
private final RootTree myRootTree;
=======
private final Map<ZLFile,Book> myBooks =
Collections.synchronizedMap(new HashMap<ZLFile,Book>());
private final RootTree myRootTree;
>>>>>>>
private final RootTree myRootTree;
<<<<<<<
myRootTree = new RootTree(collection);
new FavoritesTree(myRootTree);
new RecentBooksTree(myRootTree);
new AuthorListTree(myRootTree);
new FirstLevelTree(myRootTree, ROOT_BY_TITLE);
new FirstLevelTree(myRootTree, ROOT_BY_TAG);
new FileFirstLevelTree(myRootTree);
}
public void init() {
Collection.addListener(new IBookCollection.Listener() {
public void onBookEvent(BookEvent event, Book book) {
switch (event) {
case Added:
addBookToLibrary(book);
synchronized (myStatusLock) {
if ((myStatusMask & STATUS_LOADING) == 0 ||
Collection.size() % 16 == 0) {
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
}
}
break;
}
}
public void onBuildEvent(BuildEvent event) {
switch (event) {
case Started:
//setStatus(myStatusMask | STATUS_LOADING);
break;
case Completed:
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
//setStatus(myStatusMask & ~STATUS_LOADING);
break;
}
}
});
final Thread initializer = new Thread() {
public void run() {
setStatus(myStatusMask | STATUS_LOADING);
int count = 0;
for (Book book : Collection.books()) {
addBookToLibrary(book);
if (++count % 16 == 0) {
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
}
}
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
setStatus(myStatusMask & ~STATUS_LOADING);
}
};
initializer.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2);
initializer.start();
=======
myRootTree = new RootTree(Collection);
new FavoritesTree(myRootTree);
new RecentBooksTree(myRootTree);
new FirstLevelTree(myRootTree, LibraryTree.ROOT_BY_AUTHOR);
new FirstLevelTree(myRootTree, LibraryTree.ROOT_BY_TITLE);
new FirstLevelTree(myRootTree, LibraryTree.ROOT_BY_TAG);
new FileFirstLevelTree(myRootTree);
>>>>>>>
myRootTree = new RootTree(collection);
new FavoritesTree(myRootTree);
new RecentBooksTree(myRootTree);
new AuthorListTree(myRootTree);
new FirstLevelTree(myRootTree, LibraryTree.ROOT_BY_TITLE);
new FirstLevelTree(myRootTree, LibraryTree.ROOT_BY_TAG);
new FileFirstLevelTree(myRootTree);
}
public void init() {
Collection.addListener(new IBookCollection.Listener() {
public void onBookEvent(BookEvent event, Book book) {
switch (event) {
case Added:
addBookToLibrary(book);
synchronized (myStatusLock) {
if ((myStatusMask & STATUS_LOADING) == 0 ||
Collection.size() % 16 == 0) {
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
}
}
break;
}
}
public void onBuildEvent(BuildEvent event) {
switch (event) {
case Started:
//setStatus(myStatusMask | STATUS_LOADING);
break;
case Completed:
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
//setStatus(myStatusMask & ~STATUS_LOADING);
break;
}
}
});
final Thread initializer = new Thread() {
public void run() {
setStatus(myStatusMask | STATUS_LOADING);
int count = 0;
for (Book book : Collection.books()) {
addBookToLibrary(book);
if (++count % 16 == 0) {
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
}
}
Library.this.fireModelChangedEvent(ChangeListener.Code.BookAdded);
setStatus(myStatusMask & ~STATUS_LOADING);
}
};
initializer.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2);
initializer.start();
<<<<<<<
=======
for (Author a : authors) {
final AuthorTree authorTree = getFirstLevelTree(LibraryTree.ROOT_BY_AUTHOR).getAuthorSubTree(a);
if (seriesInfo == null) {
authorTree.getBookSubTree(book, false);
} else {
authorTree.getSeriesSubTree(seriesInfo.Title).getBookInSeriesSubTree(book);
}
}
>>>>>>>
<<<<<<<
getFirstLevelTree(ROOT_BY_TITLE).getTitleSubTree(letter);
tree.getBookWithAuthorsSubTree(book);
=======
getFirstLevelTree(LibraryTree.ROOT_BY_TITLE).getTitleSubTree(letter);
tree.getBookSubTree(book, true);
>>>>>>>
getFirstLevelTree(LibraryTree.ROOT_BY_TITLE).getTitleSubTree(letter);
tree.getBookWithAuthorsSubTree(book);
<<<<<<<
getFirstLevelTree(ROOT_BY_TITLE).getBookWithAuthorsSubTree(book);
=======
getFirstLevelTree(LibraryTree.ROOT_BY_TITLE).getBookSubTree(book, true);
>>>>>>>
getFirstLevelTree(LibraryTree.ROOT_BY_TITLE).getBookWithAuthorsSubTree(book);
<<<<<<<
synchronized (this) {
final SearchResultsTree found = (SearchResultsTree)getFirstLevelTree(ROOT_FOUND);
if (found != null && book.matches(found.getPattern())) {
found.getBookWithAuthorsSubTree(book);
}
=======
final SearchResultsTree found =
(SearchResultsTree)getFirstLevelTree(LibraryTree.ROOT_FOUND);
if (found != null && book.matches(found.getPattern())) {
found.getBookSubTree(book, true);
>>>>>>>
synchronized (this) {
final SearchResultsTree found = (SearchResultsTree)getFirstLevelTree(LibraryTree.ROOT_FOUND);
if (found != null && book.matches(found.getPattern())) {
found.getBookWithAuthorsSubTree(book);
}
<<<<<<<
=======
private void refreshInTree(String rootId, Book book) {
final FirstLevelTree tree = getFirstLevelTree(rootId);
if (tree != null) {
int index = tree.indexOf(new BookTree(Collection, book, true));
if (index >= 0) {
tree.removeBook(book, false);
new BookTree(tree, book, true, index);
}
}
}
>>>>>>>
<<<<<<<
Collection.saveBook(book, true);
myBooks.remove(book.getId());
removeFromTree(ROOT_FOUND, book);
removeFromTree(ROOT_BY_TITLE, book);
removeFromTree(ROOT_BY_SERIES, book);
removeFromTree(ROOT_BY_TAG, book);
=======
myBooks.remove(book.File);
refreshInTree(LibraryTree.ROOT_FAVORITES, book);
removeFromTree(LibraryTree.ROOT_FOUND, book);
removeFromTree(LibraryTree.ROOT_BY_TITLE, book);
removeFromTree(LibraryTree.ROOT_BY_SERIES, book);
removeFromTree(LibraryTree.ROOT_BY_AUTHOR, book);
removeFromTree(LibraryTree.ROOT_BY_TAG, book);
>>>>>>>
Collection.saveBook(book, true);
myBooks.remove(book.getId());
removeFromTree(LibraryTree.ROOT_FOUND, book);
removeFromTree(LibraryTree.ROOT_BY_TITLE, book);
removeFromTree(LibraryTree.ROOT_BY_SERIES, book);
removeFromTree(LibraryTree.ROOT_BY_TAG, book);
<<<<<<<
=======
private void build() {
// Step 0: get database books marked as "existing"
final FileInfoSet fileInfos = new FileInfoSet(myDatabase);
final Map<Long,Book> savedBooksByFileId = myDatabase.loadBooks(fileInfos, true);
final Map<Long,Book> savedBooksByBookId = new HashMap<Long,Book>();
for (Book b : savedBooksByFileId.values()) {
savedBooksByBookId.put(b.getId(), b);
}
// Step 1: set myDoGroupTitlesByFirstLetter value,
// add "existing" books into recent and favorites lists
if (savedBooksByFileId.size() > 10) {
final HashSet<String> letterSet = new HashSet<String>();
for (Book book : savedBooksByFileId.values()) {
final String letter = TitleTree.firstTitleLetter(book);
if (letter != null) {
letterSet.add(letter);
}
}
myDoGroupTitlesByFirstLetter = savedBooksByFileId.values().size() > letterSet.size() * 5 / 4;
}
for (Book book : Collection.favorites()) {
getFirstLevelTree(LibraryTree.ROOT_FAVORITES).getBookSubTree(book, true);
}
fireModelChangedEvent(ChangeListener.Code.BookAdded);
// Step 2: check if files corresponding to "existing" books really exists;
// add books to library if yes (and reload book info if needed);
// remove from recent/favorites list if no;
// collect newly "orphaned" books
final Set<Book> orphanedBooks = new HashSet<Book>();
final Set<ZLPhysicalFile> physicalFiles = new HashSet<ZLPhysicalFile>();
int count = 0;
for (Book book : savedBooksByFileId.values()) {
synchronized (this) {
final ZLPhysicalFile file = book.File.getPhysicalFile();
if (file != null) {
physicalFiles.add(file);
}
if (file != book.File && file != null && file.getPath().endsWith(".epub")) {
continue;
}
if (book.File.exists()) {
boolean doAdd = true;
if (file == null) {
continue;
}
if (!fileInfos.check(file, true)) {
try {
book.readMetaInfo();
book.save();
} catch (BookReadingException e) {
doAdd = false;
}
file.setCached(false);
}
if (doAdd) {
addBookToLibrary(book);
if (++count % 16 == 0) {
fireModelChangedEvent(ChangeListener.Code.BookAdded);
}
}
} else {
myRootTree.removeBook(book, true);
fireModelChangedEvent(ChangeListener.Code.BookRemoved);
orphanedBooks.add(book);
}
}
}
fireModelChangedEvent(ChangeListener.Code.BookAdded);
myDatabase.setExistingFlag(orphanedBooks, false);
// Step 3: collect books from physical files; add new, update already added,
// unmark orphaned as existing again, collect newly added
final Map<Long,Book> orphanedBooksByFileId = myDatabase.loadBooks(fileInfos, false);
final Set<Book> newBooks = new HashSet<Book>();
final List<ZLPhysicalFile> physicalFilesList = collectPhysicalFiles();
for (ZLPhysicalFile file : physicalFilesList) {
if (physicalFiles.contains(file)) {
continue;
}
collectBooks(
file, fileInfos,
savedBooksByFileId, orphanedBooksByFileId,
newBooks,
!fileInfos.check(file, true)
);
file.setCached(false);
}
// Step 4: add help file
try {
final ZLFile helpFile = getHelpFile();
Book helpBook = savedBooksByFileId.get(fileInfos.getId(helpFile));
if (helpBook == null) {
helpBook = new Book(helpFile);
}
addBookToLibrary(helpBook);
fireModelChangedEvent(ChangeListener.Code.BookAdded);
} catch (BookReadingException e) {
// that's impossible
e.printStackTrace();
}
// Step 5: save changes into database
fileInfos.save();
myDatabase.executeAsATransaction(new Runnable() {
public void run() {
for (Book book : newBooks) {
book.save();
}
}
});
myDatabase.setExistingFlag(newBooks, true);
}
private volatile boolean myBuildStarted = false;
public synchronized void startBuild() {
if (myBuildStarted) {
fireModelChangedEvent(ChangeListener.Code.StatusChanged);
return;
}
myBuildStarted = true;
setStatus(myStatusMask | STATUS_LOADING);
final Thread builder = new Thread("Library.build") {
public void run() {
try {
build();
} finally {
setStatus(myStatusMask & ~STATUS_LOADING);
}
}
};
builder.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2);
builder.start();
}
>>>>>>>
<<<<<<<
synchronized (this) {
for (Book book : Collection.books(pattern)) {
if (newSearchResults == null) {
if (oldSearchResults != null) {
oldSearchResults.removeSelf();
=======
final List<Book> booksCopy;
synchronized (myBooks) {
booksCopy = new ArrayList<Book>(myBooks.values());
}
for (Book book : booksCopy) {
if (book.matches(pattern)) {
synchronized (this) {
if (newSearchResults == null) {
if (oldSearchResults != null) {
oldSearchResults.removeSelf();
}
newSearchResults = new SearchResultsTree(myRootTree, LibraryTree.ROOT_FOUND, pattern);
fireModelChangedEvent(ChangeListener.Code.Found);
>>>>>>>
synchronized (this) {
for (Book book : Collection.books(pattern)) {
if (newSearchResults == null) {
if (oldSearchResults != null) {
oldSearchResults.removeSelf();
<<<<<<<
=======
public void addBookToRecentList(Book book) {
Collection.addBookToRecentList(book);
}
public boolean isBookInFavorites(Book book) {
if (book == null) {
return false;
}
final LibraryTree rootFavorites = getFirstLevelTree(LibraryTree.ROOT_FAVORITES);
for (FBTree tree : rootFavorites.subTrees()) {
if (tree instanceof BookTree && book.equals(((BookTree)tree).Book)) {
return true;
}
}
return false;
}
public void addBookToFavorites(Book book) {
if (isBookInFavorites(book)) {
return;
}
final LibraryTree rootFavorites = getFirstLevelTree(LibraryTree.ROOT_FAVORITES);
rootFavorites.getBookSubTree(book, true);
Collection.setBookFavorite(book, true);
}
public void removeBookFromFavorites(Book book) {
if (getFirstLevelTree(LibraryTree.ROOT_FAVORITES).removeBook(book, false)) {
Collection.setBookFavorite(book, false);
fireModelChangedEvent(ChangeListener.Code.BookRemoved);
}
}
>>>>>>>
<<<<<<<
Collection.removeBook(book, (removeMode & REMOVE_FROM_DISK) != 0);
=======
myBooks.remove(book.File);
if (getFirstLevelTree(LibraryTree.ROOT_RECENT).removeBook(book, false)) {
final List<Long> ids = myDatabase.loadRecentBookIds();
ids.remove(book.getId());
myDatabase.saveRecentBookIds(ids);
}
getFirstLevelTree(LibraryTree.ROOT_FAVORITES).removeBook(book, false);
>>>>>>>
Collection.removeBook(book, (removeMode & REMOVE_FROM_DISK) != 0); |
<<<<<<<
fbReader.addAction(ActionCode.SPEAK, new SpeakAction(this, fbReader));
=======
fbReader.addAction(ActionCode.CANCEL, new CancelAction(this, fbReader));
}
@Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
final String pattern = intent.getStringExtra(SearchManager.QUERY);
final Handler successHandler = new Handler() {
public void handleMessage(Message message) {
showTextSearchControls(true);
}
};
final Handler failureHandler = new Handler() {
public void handleMessage(Message message) {
UIUtil.showErrorMessage(FBReader.this, "textNotFound");
}
};
final Runnable runnable = new Runnable() {
public void run() {
final FBReaderApp fbReader = (FBReaderApp)FBReaderApp.Instance();
fbReader.TextSearchPatternOption.setValue(pattern);
if (fbReader.getTextView().search(pattern, true, false, false, false) != 0) {
successHandler.sendEmptyMessage(0);
} else {
failureHandler.sendEmptyMessage(0);
}
}
};
UIUtil.wait("search", runnable, this);
} else {
super.onNewIntent(intent);
}
>>>>>>>
fbReader.addAction(ActionCode.SPEAK, new SpeakAction(this, fbReader));
fbReader.addAction(ActionCode.CANCEL, new CancelAction(this, fbReader));
}
@Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
final String pattern = intent.getStringExtra(SearchManager.QUERY);
final Handler successHandler = new Handler() {
public void handleMessage(Message message) {
showTextSearchControls(true);
}
};
final Handler failureHandler = new Handler() {
public void handleMessage(Message message) {
UIUtil.showErrorMessage(FBReader.this, "textNotFound");
}
};
final Runnable runnable = new Runnable() {
public void run() {
final FBReaderApp fbReader = (FBReaderApp)FBReaderApp.Instance();
fbReader.TextSearchPatternOption.setValue(pattern);
if (fbReader.getTextView().search(pattern, true, false, false, false) != 0) {
successHandler.sendEmptyMessage(0);
} else {
failureHandler.sendEmptyMessage(0);
}
}
};
UIUtil.wait("search", runnable, this);
} else {
super.onNewIntent(intent);
} |
<<<<<<<
Intent intent = getIntent();
myIds = intent.getStringArrayListExtra(FBReader.CATALOGS_ID_LIST);
=======
final Intent intent = getIntent();
myIds = intent.getStringArrayListExtra(IDS_LIST);
>>>>>>>
final Intent intent = getIntent();
myIds = intent.getStringArrayListExtra(FBReader.CATALOGS_ID_LIST);
<<<<<<<
setResultIds(catalogItem);
=======
myIsChanged = true;
setResult(... Intent)
>>>>>>>
setResultIds(catalogItem); |
<<<<<<<
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.*;
=======
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
>>>>>>>
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
<<<<<<<
popup.setTouchInterceptor(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
popup.dismiss();
return true;
}
});
final ImageView coverView = (ImageView)bookView.findViewById(R.id.book_popup_cover);
if (coverView != null) {
final ZLAndroidImageData imageData = (ZLAndroidImageData)element.getImageData();
if (imageData != null) {
coverView.setImageBitmap(imageData.getFullSizeBitmap());
}
}
final OPDSBookItem item = element.getItem();
final TextView headerView = (TextView)bookView.findViewById(R.id.book_popup_header_text);
final StringBuilder text = new StringBuilder();
for (OPDSBookItem.AuthorData author : item.Authors) {
text.append("<p><i>").append(author.DisplayName).append("</i></p>");
}
text.append("<h3>").append(item.Title).append("</h3>");
headerView.setText(Html.fromHtml(text.toString()));
final TextView descriptionView = (TextView)bookView.findViewById(R.id.book_popup_description_text);
descriptionView.setText(item.getSummary());
descriptionView.setMovementMethod(new LinkMovementMethod());
final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button");
=======
final ImageView coverView = (ImageView)bookView.findViewById(R.id.book_popup_cover);
if (coverView != null) {
final ZLAndroidImageData imageData = (ZLAndroidImageData)element.getImageData();
if (imageData != null) {
coverView.setImageBitmap(imageData.getFullSizeBitmap());
}
}
final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button");
>>>>>>>
// popup.setTouchInterceptor(new View.OnTouchListener() {
// public boolean onTouch(View v, MotionEvent event) {
// popup.dismiss();
// return true;
// }
// });
final ImageView coverView = (ImageView)bookView.findViewById(R.id.book_popup_cover);
if (coverView != null) {
final ZLAndroidImageData imageData = (ZLAndroidImageData)element.getImageData();
if (imageData != null) {
coverView.setImageBitmap(imageData.getFullSizeBitmap());
}
}
final OPDSBookItem item = element.getItem();
final TextView headerView = (TextView)bookView.findViewById(R.id.book_popup_header_text);
final StringBuilder text = new StringBuilder();
for (OPDSBookItem.AuthorData author : item.Authors) {
text.append("<p><i>").append(author.DisplayName).append("</i></p>");
}
text.append("<h3>").append(item.Title).append("</h3>");
headerView.setText(Html.fromHtml(text.toString()));
final TextView descriptionView = (TextView)bookView.findViewById(R.id.book_popup_description_text);
descriptionView.setText(item.getSummary());
descriptionView.setMovementMethod(new LinkMovementMethod());
final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button"); |
<<<<<<<
import org.geometerplus.android.util.UIUtil;
=======
import org.geometerplus.android.util.AndroidUtil;
import org.geometerplus.android.fbreader.FBReader;
>>>>>>>
import org.geometerplus.android.util.UIUtil;
import org.geometerplus.android.fbreader.FBReader; |
<<<<<<<
builder.setGroup(String.valueOf(bid));
builder.setGroupSummary(true);
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
=======
>>>>>>> |
<<<<<<<
private OPDSBookItem myItem;
private NetworkImage myCover;
public void setData(OPDSBookItem item) {
final String bookUrl = item.getUrl(UrlInfo.Type.Book);
String coverUrl = item.getUrl(UrlInfo.Type.Image);
if (coverUrl == null) {
coverUrl = item.getUrl(UrlInfo.Type.Thumbnail);
}
if (bookUrl == null || coverUrl == null) {
myItem = null;
myCover = null;
} else {
myItem = item;
myCover = new NetworkImage(coverUrl);
myCover.synchronize();
}
}
=======
private final FBView myView;
BookElement(FBView view) {
myView = view;
}
>>>>>>>
private final FBView myView;
private OPDSBookItem myItem;
private NetworkImage myCover;
BookElement(FBView view) {
myView = view;
}
public void setData(OPDSBookItem item) {
final String bookUrl = item.getUrl(UrlInfo.Type.Book);
String coverUrl = item.getUrl(UrlInfo.Type.Image);
if (coverUrl == null) {
coverUrl = item.getUrl(UrlInfo.Type.Thumbnail);
}
if (bookUrl == null || coverUrl == null) {
myItem = null;
myCover = null;
} else {
myItem = item;
myCover = new NetworkImage(coverUrl);
myCover.synchronize();
}
} |
<<<<<<<
=======
switchWakeLock(
getZLibrary().BatteryLevelToTurnScreenOffOption.getValue() <
FBReaderApp.Instance().getBatteryLevel()
);
myStartTimer = true;
final int brightnessLevel =
getZLibrary().ScreenBrightnessLevelOption.getValue();
if (brightnessLevel != 0) {
setScreenBrightness(brightnessLevel);
} else {
setScreenBrightnessAuto();
}
if (getZLibrary().DisableButtonLightsOption.getValue()) {
setButtonLight(false);
}
registerReceiver(myBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
try {
sendBroadcast(new Intent(getApplicationContext(), KillerCallback.class));
} catch (Throwable t) {
}
>>>>>>>
switchWakeLock(
getZLibrary().BatteryLevelToTurnScreenOffOption.getValue() <
FBReaderApp.Instance().getBatteryLevel()
);
myStartTimer = true;
final int brightnessLevel =
getZLibrary().ScreenBrightnessLevelOption.getValue();
if (brightnessLevel != 0) {
setScreenBrightness(brightnessLevel);
} else {
setScreenBrightnessAuto();
}
if (getZLibrary().DisableButtonLightsOption.getValue()) {
setButtonLight(false);
}
registerReceiver(myBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); |
<<<<<<<
private final List<?> myNullList = Collections.singletonList(null);
private LibraryTree getTagTree(Tag tag) {
if (tag == null || tag.Parent == null) {
return getFirstLevelTree(LibraryTree.ROOT_BY_TAG).getTagSubTree(tag);
} else {
return getTagTree(tag.Parent).getTagSubTree(tag);
}
}
=======
public static ZLResourceFile getHelpFile() {
final Locale locale = Locale.getDefault();
ZLResourceFile file = ZLResourceFile.createResourceFile(
"data/help/MiniHelp." + locale.getLanguage() + "_" + locale.getCountry() + ".fb2"
);
if (file.exists()) {
return file;
}
file = ZLResourceFile.createResourceFile(
"data/help/MiniHelp." + locale.getLanguage() + ".fb2"
);
if (file.exists()) {
return file;
}
return ZLResourceFile.createResourceFile("data/help/MiniHelp.en.fb2");
}
private void collectBooks(
ZLFile file, FileInfoSet fileInfos,
Map<Long,Book> savedBooksByFileId, Map<Long,Book> orphanedBooksByFileId,
Set<Book> newBooks,
boolean doReadMetaInfo
) {
final long fileId = fileInfos.getId(file);
if (savedBooksByFileId.get(fileId) != null) {
return;
}
try {
final Book book = orphanedBooksByFileId.get(fileId);
if (book != null) {
if (doReadMetaInfo) {
book.readMetaInfo();
}
addBookToLibrary(book);
fireModelChangedEvent(ChangeListener.Code.BookAdded);
newBooks.add(book);
return;
}
} catch (BookReadingException e) {
// ignore
}
try {
final Book book = new Book(file);
addBookToLibrary(book);
fireModelChangedEvent(ChangeListener.Code.BookAdded);
newBooks.add(book);
return;
} catch (BookReadingException e) {
// ignore
}
if (file.isArchive()) {
for (ZLFile entry : fileInfos.archiveEntries(file)) {
collectBooks(
entry, fileInfos,
savedBooksByFileId, orphanedBooksByFileId,
newBooks,
doReadMetaInfo
);
}
}
}
private List<ZLPhysicalFile> collectPhysicalFiles() {
final Queue<ZLFile> dirQueue = new LinkedList<ZLFile>();
final HashSet<ZLFile> dirSet = new HashSet<ZLFile>();
final LinkedList<ZLPhysicalFile> fileList = new LinkedList<ZLPhysicalFile>();
dirQueue.offer(new ZLPhysicalFile(new File(Paths.BooksDirectoryOption().getValue())));
while (!dirQueue.isEmpty()) {
for (ZLFile file : dirQueue.poll().children()) {
if (file.isDirectory()) {
if (!dirSet.contains(file)) {
dirQueue.add(file);
dirSet.add(file);
}
} else {
file.setCached(true);
fileList.add((ZLPhysicalFile)file);
}
}
}
return fileList;
}
>>>>>>>
<<<<<<<
synchronized (this) {
final SearchResultsTree found = (SearchResultsTree)getFirstLevelTree(LibraryTree.ROOT_FOUND);
if (found != null && book.matches(found.getPattern())) {
found.getBookWithAuthorsSubTree(book);
}
=======
final SearchResultsTree found =
(SearchResultsTree)getFirstLevelTree(LibraryTree.ROOT_FOUND);
if (found != null && book.matches(found.getPattern())) {
found.createBookWithAuthorsSubTree(book);
>>>>>>>
synchronized (this) {
final SearchResultsTree found = (SearchResultsTree)getFirstLevelTree(LibraryTree.ROOT_FOUND);
if (found != null && book.matches(found.getPattern())) {
found.createBookWithAuthorsSubTree(book);
}
<<<<<<<
tree.removeBook(book, false);
}
}
=======
tree.removeBook(book);
}
}
>>>>>>>
tree.removeBook(book);
}
}
<<<<<<<
=======
private void build() {
// Step 0: get database books marked as "existing"
final FileInfoSet fileInfos = new FileInfoSet(myDatabase);
final Map<Long,Book> savedBooksByFileId = myDatabase.loadBooks(fileInfos, true);
final Map<Long,Book> savedBooksByBookId = new HashMap<Long,Book>();
for (Book b : savedBooksByFileId.values()) {
savedBooksByBookId.put(b.getId(), b);
}
// Step 1: set myDoGroupTitlesByFirstLetter value,
// add "existing" books into recent and favorites lists
if (savedBooksByFileId.size() > 10) {
final HashSet<String> letterSet = new HashSet<String>();
for (Book book : savedBooksByFileId.values()) {
final String letter = TitleTree.firstTitleLetter(book);
if (letter != null) {
letterSet.add(letter);
}
}
myDoGroupTitlesByFirstLetter = savedBooksByFileId.values().size() > letterSet.size() * 5 / 4;
}
fireModelChangedEvent(ChangeListener.Code.BookAdded);
// Step 2: check if files corresponding to "existing" books really exists;
// add books to library if yes (and reload book info if needed);
// remove from recent/favorites list if no;
// collect newly "orphaned" books
final Set<Book> orphanedBooks = new HashSet<Book>();
final Set<ZLPhysicalFile> physicalFiles = new HashSet<ZLPhysicalFile>();
int count = 0;
for (Book book : savedBooksByFileId.values()) {
synchronized (this) {
final ZLPhysicalFile file = book.File.getPhysicalFile();
if (file != null) {
physicalFiles.add(file);
}
if (file != book.File && file != null && file.getPath().endsWith(".epub")) {
continue;
}
if (book.File.exists()) {
boolean doAdd = true;
if (file == null) {
continue;
}
if (!fileInfos.check(file, true)) {
try {
book.readMetaInfo();
book.save();
} catch (BookReadingException e) {
doAdd = false;
}
file.setCached(false);
}
if (doAdd) {
addBookToLibrary(book);
if (++count % 16 == 0) {
fireModelChangedEvent(ChangeListener.Code.BookAdded);
}
}
} else {
fireModelChangedEvent(ChangeListener.Code.BookRemoved);
orphanedBooks.add(book);
}
}
}
fireModelChangedEvent(ChangeListener.Code.BookAdded);
myDatabase.setExistingFlag(orphanedBooks, false);
// Step 3: collect books from physical files; add new, update already added,
// unmark orphaned as existing again, collect newly added
final Map<Long,Book> orphanedBooksByFileId = myDatabase.loadBooks(fileInfos, false);
final Set<Book> newBooks = new HashSet<Book>();
final List<ZLPhysicalFile> physicalFilesList = collectPhysicalFiles();
for (ZLPhysicalFile file : physicalFilesList) {
if (physicalFiles.contains(file)) {
continue;
}
collectBooks(
file, fileInfos,
savedBooksByFileId, orphanedBooksByFileId,
newBooks,
!fileInfos.check(file, true)
);
file.setCached(false);
}
// Step 4: add help file
try {
final ZLFile helpFile = getHelpFile();
Book helpBook = savedBooksByFileId.get(fileInfos.getId(helpFile));
if (helpBook == null) {
helpBook = new Book(helpFile);
}
addBookToLibrary(helpBook);
fireModelChangedEvent(ChangeListener.Code.BookAdded);
} catch (BookReadingException e) {
// that's impossible
e.printStackTrace();
}
// Step 5: save changes into database
fileInfos.save();
myDatabase.executeAsATransaction(new Runnable() {
public void run() {
for (Book book : newBooks) {
book.save();
}
}
});
myDatabase.setExistingFlag(newBooks, true);
}
private volatile boolean myBuildStarted = false;
public synchronized void startBuild() {
if (myBuildStarted) {
fireModelChangedEvent(ChangeListener.Code.StatusChanged);
return;
}
myBuildStarted = true;
setStatus(myStatusMask | STATUS_LOADING);
final Thread builder = new Thread("Library.build") {
public void run() {
try {
build();
} finally {
setStatus(myStatusMask & ~STATUS_LOADING);
}
}
};
builder.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2);
builder.start();
}
>>>>>>> |
<<<<<<<
import org.n52.iceland.ds.ConnectionProvider;
import org.n52.iceland.exception.CodedException;
import org.n52.iceland.exception.ows.NoApplicableCodeException;
import org.n52.iceland.exception.ows.OwsExceptionReport;
import org.n52.iceland.util.CollectionHelper;
import org.n52.iceland.util.http.HTTPStatus;
import org.n52.sos.ds.hibernate.entities.values.AbstractValue;
=======
import org.n52.sos.ds.hibernate.entities.observation.legacy.AbstractValuedLegacyObservation;
>>>>>>>
import org.n52.sos.ds.hibernate.entities.observation.legacy.AbstractValuedLegacyObservation;
import org.n52.iceland.ds.ConnectionProvider;
import org.n52.iceland.exception.CodedException;
import org.n52.iceland.exception.ows.NoApplicableCodeException;
import org.n52.iceland.exception.ows.OwsExceptionReport;
import org.n52.iceland.util.CollectionHelper;
import org.n52.iceland.util.http.HTTPStatus;
<<<<<<<
*
* @author <a href="mailto:[email protected]">Carsten Hollmann</a>
=======
*
* @author Carsten Hollmann <[email protected]>
>>>>>>>
*
* @author <a href="mailto:[email protected]">Carsten Hollmann</a>
<<<<<<<
public AbstractValue nextEntity() throws OwsExceptionReport {
return seriesValuesResult.next();
=======
public AbstractValuedLegacyObservation<?> nextEntity() throws OwsExceptionReport {
return (AbstractValuedLegacyObservation<?>) seriesValuesResult.next();
>>>>>>>
public AbstractValuedLegacyObservation<?> nextEntity() throws OwsExceptionReport {
return (AbstractValuedLegacyObservation<?>) seriesValuesResult.next(); |
<<<<<<<
final NetworkCatalogTree catalogTree = (NetworkCatalogTree)tree;
final NetworkCatalogItem item = catalogTree.Item;
if (item.URLByType.get(NetworkCatalogItem.URL_CATALOG) != null) {
=======
final NetworkCatalogItem item = ((NetworkCatalogTree)tree).Item;
if (!(item instanceof NetworkURLCatalogItem)) {
>>>>>>>
final NetworkCatalogItem item = ((NetworkCatalogTree)tree).Item;
if (!(item instanceof NetworkURLCatalogItem)) {
<<<<<<<
final NetworkCatalogTree catalogTree = (NetworkCatalogTree)tree;
final NetworkCatalogItem item = catalogTree.Item;
final boolean isLoading =
NetworkView.Instance().containsItemsLoadingRunnable(tree.getUniqueKey());
=======
final NetworkCatalogItem item = ((NetworkCatalogTree)tree).Item;
final NetworkURLCatalogItem urlItem =
item instanceof NetworkURLCatalogItem ? (NetworkURLCatalogItem)item : null;
>>>>>>>
final NetworkCatalogItem item = ((NetworkCatalogTree)tree).Item;
final NetworkURLCatalogItem urlItem =
item instanceof NetworkURLCatalogItem ? (NetworkURLCatalogItem)item : null;
<<<<<<<
private boolean consumeByVisibility(final NetworkBaseActivity activity, final NetworkCatalogTree tree, final int actionCode) {
switch (tree.Item.getVisibility()) {
=======
private boolean consumeByVisibility(final NetworkBaseActivity activity, final NetworkTree tree, final int actionCode) {
final NetworkCatalogItem item = ((NetworkCatalogTree)tree).Item;
switch (item.getVisibility()) {
>>>>>>>
private boolean consumeByVisibility(final NetworkBaseActivity activity, final NetworkTree tree, final int actionCode) {
final NetworkCatalogItem item = ((NetworkCatalogTree)tree).Item;
switch (item.getVisibility()) {
<<<<<<<
=======
final NetworkCatalogTree catalogTree = (NetworkCatalogTree)tree;
final NetworkCatalogItem item = catalogTree.Item;
>>>>>>>
final NetworkCatalogItem item = catalogTree.Item; |
<<<<<<<
PendingIntent replyPendingIntent = PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
builder.addAction(new android.app.Notification.Action.Builder(R.drawable.ic_reply,
=======
if (replyIntent != null) {
WearableExtender extender = new WearableExtender();
PendingIntent replyPendingIntent = PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_reply,
>>>>>>>
PendingIntent replyPendingIntent = PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(new android.app.Notification.Action.Builder(R.drawable.ic_reply, |
<<<<<<<
public static interface CredentialsCreator {
Credentials createCredentials(String scheme, AuthScope scope, boolean quietMode);
boolean credentialsExist(AuthScope scope);
void removeCredentials(AuthScope scope);
}
public static abstract class BasicCredentialsCreator implements ZLNetworkManager.CredentialsCreator {
final private HashMap<AuthScope, Credentials> myCredentialsMap = new HashMap<AuthScope, Credentials> ();
=======
public static abstract class CredentialsCreator {
>>>>>>>
public static abstract class CredentialsCreator {
final private HashMap<AuthScope, Credentials> myCredentialsMap = new HashMap<AuthScope, Credentials> ();
<<<<<<<
public Credentials createCredentials(String scheme, AuthScope scope, boolean quietMode) {
if (!"basic".equalsIgnoreCase(scope.getScheme()) && !"digest".equalsIgnoreCase(scope.getScheme())) {
=======
public Credentials createCredentials(String scheme, AuthScope scope) {
final String authScheme = scope.getScheme();
if (!"basic".equalsIgnoreCase(authScheme) &&
!"digest".equalsIgnoreCase(authScheme)) {
>>>>>>>
public Credentials createCredentials(String scheme, AuthScope scope, boolean quietMode) {
final String authScheme = scope.getScheme();
if (!"basic".equalsIgnoreCase(authScheme) &&
!"digest".equalsIgnoreCase(authScheme)) { |
<<<<<<<
abstract protected void navigate();
abstract protected boolean canNavigate();
BroadcastReceiver myBatteryInfoReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
ZLApplication.Instance().myBatteryLevel = intent.getIntExtra("level", 100);
}
};
=======
>>>>>>>
BroadcastReceiver myBatteryInfoReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
ZLApplication.Instance().myBatteryLevel = intent.getIntExtra("level", 100);
}
}; |
<<<<<<<
private final boolean isCoverageEnabled;
=======
private final int totalAllowedRetryQuota;
private final int retryPerTestCaseQuota;
>>>>>>>
private final int totalAllowedRetryQuota;
private final int retryPerTestCaseQuota;
private final boolean isCoverageEnabled;
<<<<<<<
boolean fallbackToScreenshots,
boolean isCoverageEnabled) {
=======
boolean fallbackToScreenshots,
int totalAllowedRetryQuota,
int retryPerTestCaseQuota) {
>>>>>>>
boolean fallbackToScreenshots,
int totalAllowedRetryQuota,
int retryPerTestCaseQuota,
boolean isCoverageEnabled) {
<<<<<<<
this.isCoverageEnabled = isCoverageEnabled;
=======
this.totalAllowedRetryQuota = totalAllowedRetryQuota;
this.retryPerTestCaseQuota = retryPerTestCaseQuota;
>>>>>>>
this.totalAllowedRetryQuota = totalAllowedRetryQuota;
this.retryPerTestCaseQuota = retryPerTestCaseQuota;
this.isCoverageEnabled = isCoverageEnabled;
<<<<<<<
public boolean isCoverageEnabled() {
return isCoverageEnabled;
}
=======
public int getTotalAllowedRetryQuota() {
return totalAllowedRetryQuota;
}
public int getRetryPerTestCaseQuota() {
return retryPerTestCaseQuota;
}
>>>>>>>
public int getTotalAllowedRetryQuota() {
return totalAllowedRetryQuota;
}
public int getRetryPerTestCaseQuota() {
return retryPerTestCaseQuota;
}
public boolean isCoverageEnabled() {
return isCoverageEnabled;
} |
<<<<<<<
=======
@Parameter(names = { "--total-allowed-retry-quota" }, description = "Amount of re-executions of failing tests allowed.", converter = IntegerConverter.class)
public int totalAllowedRetryQuota = 0;
@Parameter(names = { "--retry-per-test-case-quota" }, description = "Max number of time each testCase is attempted again " +
"before declaring it as a failure.", converter = IntegerConverter.class)
public int retryPerTestCaseQuota = 1;
@Parameter(names = { "--auto-grant-runtime-permissions" }, description = "Grant all runtime permissions", arity = 1)
public Boolean autoGrantRuntimePermissions = true;
>>>>>>>
<<<<<<<
=======
private static void overrideDefaultsIfSet(ForkBuilder forkBuilder, CommandLineArgs parsedArgs) {
if (parsedArgs.sdk != null) {
forkBuilder.withAndroidSdk(parsedArgs.sdk);
}
if (parsedArgs.output != null) {
forkBuilder.withOutputDirectory(parsedArgs.output);
}
if (parsedArgs.testClassRegex != null) {
forkBuilder.withTestClassRegex(parsedArgs.testClassRegex);
}
if (parsedArgs.testPackage != null) {
forkBuilder.withTestPackage(parsedArgs.testPackage);
}
if (parsedArgs.testOutputTimeout > -1) {
forkBuilder.withTestOutputTimeout(parsedArgs.testOutputTimeout);
}
if (parsedArgs.totalAllowedRetryQuota > 0) {
forkBuilder.withTotalAllowedRetryQuota(parsedArgs.totalAllowedRetryQuota);
}
if(parsedArgs.retryPerTestCaseQuota > -1){
forkBuilder.withRetryPerTestCaseQuota(parsedArgs.retryPerTestCaseQuota);
}
if(parsedArgs.autoGrantRuntimePermissions != null){
forkBuilder.withAutoGrantRuntimePermissions(parsedArgs.autoGrantRuntimePermissions);
}
}
>>>>>>> |
<<<<<<<
import net.imagej.ops.special.UnaryComputerOp;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessibleInterval;
=======
import net.imagej.ops.special.computer.UnaryComputerOp;
>>>>>>>
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessibleInterval; |
<<<<<<<
=======
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
>>>>>>>
import java.util.Set;
import java.util.TreeSet;
<<<<<<<
import com.carolinarollergirls.scoreboard.core.Clients.Client;
import com.carolinarollergirls.scoreboard.core.Clients.Device;
=======
import com.carolinarollergirls.scoreboard.core.Timeout;
>>>>>>>
import com.carolinarollergirls.scoreboard.core.Timeout;
<<<<<<<
newPaths.add((String)p);
=======
newPaths.add((String) p);
>>>>>>>
newPaths.add((String) p);
<<<<<<<
sbClient.write();
String key = (String)json.get("key");
=======
String key = (String) json.get("key");
>>>>>>>
sbClient.write();
String key = (String) json.get("key");
<<<<<<<
connection.sendMessage(JSON.std
.with(JSON.Feature.WRITE_NULL_PROPERTIES)
.composeString()
.addObject(json)
.finish());
=======
connection.sendMessage(
JSON.std.with(JSON.Feature.WRITE_NULL_PROPERTIES).composeString().addObject(json).finish());
>>>>>>>
connection.sendMessage(
JSON.std.with(JSON.Feature.WRITE_NULL_PROPERTIES).composeString().addObject(json).finish());
<<<<<<<
for (String k: changed) {
if (watchedPaths.covers(k) && !k.endsWith("Secret")) {
=======
for (String k : changed) {
if (watchedPaths.covers(k)) {
>>>>>>>
for (String k : changed) {
if (watchedPaths.covers(k) && !k.endsWith("Secret")) { |
<<<<<<<
=======
import com.carolinarollergirls.scoreboard.core.Period;
>>>>>>>
import com.carolinarollergirls.scoreboard.core.Period;
<<<<<<<
if (prop == Value.TRIP_SCORE && flag != Flag.COPY) {
tripScoreTimerTask.cancel();
if ((Integer) value > 0) {
// If points arrive during an initial trip and we are not in overtime, assign
// the points to the first scoring trip instead.
if (getCurrentTrip().getNumber() == 1 && !getScoreBoard().isInOvertime()) {
getCurrentTrip().set(ScoringTrip.Value.ANNOTATION,
"Points were added without Trip +1\n" + get(ScoringTrip.Value.ANNOTATION));
execute(Command.ADD_TRIP);
}
if (scoreBoard.isInJam()) {
tripScoreTimer.purge();
tripScoreTimerTask = new TimerTask() {
@Override
public void run() {
execute(Command.ADD_TRIP);
}
};
tripScoreTimer.schedule(tripScoreTimerTask, 4000);
}
=======
if (prop == Value.TRIP_SCORE && source != Source.COPY && (Integer) value > 0) {
// If points arrive during an initial trip and we are not in overtime, assign the points to the first scoring trip instead.
if (getCurrentTrip().getNumber() == 1 && !getScoreBoard().isInOvertime()) {
getCurrentTrip().set(ScoringTrip.Value.ANNOTATION,"Points were added without Trip +1\n" + get(ScoringTrip.Value.ANNOTATION));
execute(Command.ADD_TRIP);
}
if (scoreBoard.isInJam()) {
tripScoreTimerTask.cancel();
tripScoreTimer.purge();
tripScoreTimerTask = new TimerTask() {
@Override
public void run() {
execute(Command.ADD_TRIP);
}
};
tripScoreTimer.schedule(tripScoreTimerTask, 4000);
>>>>>>>
if (prop == Value.TRIP_SCORE && source != Source.COPY) {
tripScoreTimerTask.cancel();
if ((Integer) value > 0) {
// If points arrive during an initial trip and we are not in overtime, assign
// the points to the first scoring trip instead.
if (getCurrentTrip().getNumber() == 1 && !getScoreBoard().isInOvertime()) {
getCurrentTrip().set(ScoringTrip.Value.ANNOTATION,
"Points were added without Trip +1\n" + get(ScoringTrip.Value.ANNOTATION));
execute(Command.ADD_TRIP);
}
if (scoreBoard.isInJam()) {
tripScoreTimer.purge();
tripScoreTimerTask = new TimerTask() {
@Override
public void run() {
execute(Command.ADD_TRIP);
}
};
tripScoreTimer.schedule(tripScoreTimerTask, 4000);
}
<<<<<<<
public ScoringTrip getCurrentTrip() { return (ScoringTrip)get(Value.CURRENT_TRIP); }
public boolean cancelTripAdvancement() { return tripScoreTimerTask.cancel(); }
=======
public ScoringTrip getCurrentTrip() { return (ScoringTrip) get(Value.CURRENT_TRIP); }
>>>>>>>
public ScoringTrip getCurrentTrip() { return (ScoringTrip) get(Value.CURRENT_TRIP); }
public boolean cancelTripAdvancement() { return tripScoreTimerTask.cancel(); } |
<<<<<<<
import com.carolinarollergirls.scoreboard.event.ConditionalScoreBoardListener;
import com.carolinarollergirls.scoreboard.event.OrderedScoreBoardEventProvider.IValue;
import com.carolinarollergirls.scoreboard.event.ScoreBoardEventProviderImpl;
import com.carolinarollergirls.scoreboard.event.ScoreBoardEvent;
import com.carolinarollergirls.scoreboard.event.ScoreBoardListener;
import com.carolinarollergirls.scoreboard.penalties.PenaltyCodesManager;
import com.carolinarollergirls.scoreboard.event.ScoreBoardEvent.AddRemoveProperty;
import com.carolinarollergirls.scoreboard.event.ScoreBoardEvent.CommandProperty;
import com.carolinarollergirls.scoreboard.event.ScoreBoardEvent.PermanentProperty;
import com.carolinarollergirls.scoreboard.event.ScoreBoardEvent.ValueWithId;
import com.carolinarollergirls.scoreboard.rules.Rule;
import com.carolinarollergirls.scoreboard.utils.ScoreBoardClock;
import com.carolinarollergirls.scoreboard.utils.ValWithId;
import com.carolinarollergirls.scoreboard.utils.Version;
import com.carolinarollergirls.scoreboard.core.Clients;
=======
>>>>>>>
import com.carolinarollergirls.scoreboard.core.Clients;
<<<<<<<
public Clients getClients() { return (Clients)get(Child.CLIENTS, ""); }
@Override
public Clock getClock(String id) { return (Clock)getOrCreate(Child.CLOCK, id); }
=======
public Clock getClock(String id) { return (Clock) getOrCreate(Child.CLOCK, id); }
>>>>>>>
public Clients getClients() { return (Clients) get(Child.CLIENTS, ""); }
@Override
public Clock getClock(String id) { return (Clock) getOrCreate(Child.CLOCK, id); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.