我们正在使用新的Java打印API,用于PrinterJob.printDialog(attributes)向用户显示对话框.
想要下次保存用户的设置,我想这样做:
PrintRequestAttributeSet attributes = loadAttributesFromPreferences();
if (printJob.printDialog(attributes)) {
// print, and then...
saveAttributesToPreferences(attributes);
}
Run Code Online (Sandbox Code Playgroud)
但是,我通过这样做发现,有时候(我还没弄清楚)属性是如何在内部获得一些不良数据,然后当你打印时,你会得到一个什么都没有的白页.然后代码将中毒的设置保存到首选项中,并且所有后续的打印运行也会中毒设置.此外,练习的整个点,使新运行的设置与用户为上一次运行选择的设置相同,将被取消,因为新对话框似乎不使用旧设置.
所以我想知道是否有正确的方法来做到这一点.当然,Sun并不打算用户每次启动应用程序时都必须选择打印机,页面大小,方向和边距设置.
编辑以显示存储方法的实现:
private PrintRequestAttributeSet loadAttributesFromPreferences()
{
PrintRequestAttributeSet attributes = null;
byte[] marshaledAttributes = preferences.getByteArray(PRINT_REQUEST_ATTRIBUTES_KEY, null);
if (marshaledAttributes != null)
{
try
{
@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
ObjectInput objectInput = new ObjectInputStream(new ByteArrayInputStream(marshaledAttributes));
attributes = (PrintRequestAttributeSet) objectInput.readObject();
}
catch (IOException e)
{
// Can occur due to invalid object data e.g. InvalidClassException, StreamCorruptedException
Logger.getLogger(getClass()).warn("Error trying to read print attributes from preferences", e);
}
catch (ClassNotFoundException …Run Code Online (Sandbox Code Playgroud) 我们目前正在使用Guava作为其不可变的集合,但我很惊讶地发现他们的地图没有方法可以轻松创建新的地图并进行微小的修改.最重要的是,他们的构建器不允许为键分配新值或删除键.
因此,如果我只想修改一个值,这就是我希望能够做到的:
ImmutableMap<Guid, ImmutableMap<String, Integer>> originalMap = /* get the map */;
ImmutableMap<Guid, ImmutableMap<String, Integer>> modifiedMap =
originalMap.cloneAndPut(key, value);
Run Code Online (Sandbox Code Playgroud)
这就是Guava期待我做的事情:
ImmutableMap<Guid, ImmutableMap<String, Integer>> originalMap = /* get the map */;
Map<Guid, ImmutableMap<String, Integer>> mutableCopy = new LinkedHashMap<>(originalMap);
mutableCopy.put(key, value);
originalMap = ImmutableMap.copyOf(mutableCopy);
/* put the map back */
Run Code Online (Sandbox Code Playgroud)
通过这样做,我得到了我想要的修改的地图的新副本.原始副本不受影响,我将使用原子引用将事物放回去,因此整个设置是线程安全的.
这很慢.
这里有很多浪费的复制品.假设地图中有1,024个桶.当你可以按原样使用那些不可变的桶并且只克隆其中一个时,那就是你不必要地重新创建的1,023个桶(也是每个两次).
所以我想:
是否有一种Guava实用方法埋在某处用于此类事情?(它不在地图或ImmutableMap.Builder中.)
有没有其他Java库可以做到这一点?我的印象是Clojure有这样的东西但我们还没准备好转换语言......
我从Java 8u5更新到8u45,一些以前工作的代码不再编译.问题是,发生这种情况的时间有一半,这是故意的改变,所以我无法弄清楚它是否是一个错误.
(我也测试了u25,每个版本都和u45一样.)
但实质上,它与方法的多个返回点有关.例如:
import java.sql.Connection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class CompilerIssue
{
public Set<String> test(int value)
{
return perform(connection -> {
if (value % 2 == 0)
{
return Collections.<String>emptySet();
}
else
{
return new HashSet<>(10);
}
});
}
<V> V perform(BusinessLogic<V> logic)
{
// would usually get a connection
return null;
}
interface BusinessLogic<V>
{
V execute(Connection connection) throws Exception;
}
}
Run Code Online (Sandbox Code Playgroud)
javac给出:
Error:(12, 23) java: incompatible types: inferred type does not conform to upper …Run Code Online (Sandbox Code Playgroud) 参加以下测试:
public static class Scripted {
public void setThing(List<?> list) {
System.out.println("Set via list");
}
public void setThing(Object[] array) {
System.out.println("Set array");
}
}
@Test
public void testScripting() throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.getContext().setAttribute("s", new Scripted(), ScriptContext.ENGINE_SCOPE);
engine.eval("s.thing = Array(1, 2, 3);");
}
Run Code Online (Sandbox Code Playgroud)
随着使用Java 7的Rhino版本运行,如果你运行它,你将得到如下的异常:
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: The choice of Java constructor setThing matching JavaScript argument types (object) is ambiguous; candidate constructors are:
void setThing(java.util.List)
void setThing(java.lang.Object[]) (<Unknown source>#1) in <Unknown source> at line number 1
Run Code Online (Sandbox Code Playgroud)
该 …
我无法解释这一点,但我在其他人的代码中发现了这种现象:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.stream.Stream;
import org.junit.Test;
public class TestDidWeBreakJavaAgain
{
@Test
public void testIoInSerialStream()
{
doTest(false);
}
@Test
public void testIoInParallelStream()
{
doTest(true);
}
private void doTest(boolean parallel)
{
Stream<String> stream = Stream.of("1", "2", "3");
if (parallel)
{
stream = stream.parallel();
}
stream.forEach(name -> {
try
{
Files.createTempFile(name, ".dat");
}
catch (IOException e)
{
throw new UncheckedIOException("Failed to create temp file", e);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
在启用安全管理器的情况下运行时,仅仅调用parallel()流,或者parallelStream()从集合中获取流时,似乎可以保证所有执行I/O的尝试都会抛出SecurityException.(最有可能的,它调用任何方法可以抛出 …
我有一个网页,其中显示了与服务器一起使用的SSL证书的详细信息.我认为toString()可能没问题,但它看起来像这样:
[0] Version: 3
SerialNumber: 117262955582477610212812061435665386300
IssuerDN: CN=localhost
Start Date: Wed Jun 13 15:15:05 EST 2012
Final Date: Tue Jun 08 15:15:05 EST 2032
SubjectDN: CN=localhost
Public Key: DSA Public Key
y: 6ef96c2ace616280c5453dda2[TRUNCATED BY ME]
Signature Algorithm: SHA1withDSA
Signature: 302c021450b1557d879a25ccf6b89e7ac6de8dc6
0b13df7e0214559cdc810cdb1faa3a645da837cd
5efdeb81d62e
Extensions:
critical(true) 2.5.29.17 value = DER Sequence
Tagged [7] IMPLICIT
DER Octet String[4]
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是扩展的模糊表示.我更愿意看到"subjectAltNames"和替代名称列表,就像我在浏览证书信息时在网络浏览器中看到的那样.
有办法做到这一点吗?我在班级路径上有完整的BouncyCastle,所以我希望我能在那里找到它,但我似乎无法找到它.
最糟糕的是,我知道我可以花时间自己搞清楚所有的点点滴滴,但我不知道是否会错过某人可能期望在那里找到的扩展.
我们有一个系统,我们正在处理XML文件,其中文件本身太大而无法放入内存中.
作为处理的一部分,我们希望快速扫描以记录相关元素的偏移量,以便稍后,我们可以立即查找这些元素并解析我们想要的部分(因为文件的较小片段将适合内存) ,我们可以负担得起使用DOM或其他任何部分.)
显然,我们可以从头开始编写自己的XML解析器,但在创建另一个XML解析器之前,我想看看是否还有其他可用选项.
以下是我们已经了解的事项列表.
使用StAX应该可以工作,但不能.这是一个演示.我做了一个XML示例,其中有超过一个字节的字符,以证明一旦开始传递这些字符,返回的字节偏移量就不正确.请注意,即使API中的方法名为getCharacterOffset(),文档也会说如果传入字节流,它会返回字节偏移量 - 这就是此代码正在执行的操作.
@Test
public void testByteOffsetsFromStreamParser() throws Exception {
// byte counts are size required for UTF-8, I checked using Ishida's tool.
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<root>\n"
" <leaf>\u305A\u308C\u306A\u3044\u3067\u307B\u3057\u3044</leaf>\n" +
" <leaf>\u305A\u308C\u306A\u3044\u3067\u307B\u3057\u3044</leaf>\n" +
" <leaf>\u305A\u308C\u306A\u3044\u3067\u307B\u3057\u3044</leaf>\n" +
"</root>\n";
byte[] xmlBytes = xml.getBytes("UTF-8");
assertThat(xmlBytes.length, is(equalTo(171))); // = 171 from above
String implToTest = "com.sun.xml.internal.stream.XMLInputFactoryImpl";
//String implToTest = "com.ctc.wstx.stax.WstxInputFactory";
XMLInputFactory factory =
Class.forName(implToTest).asSubclass(XMLInputFactory.class).newInstance();
factory.setProperty("javax.xml.stream.isCoalescing", false);
factory.setProperty("javax.xml.stream.supportDTD", false);
XMLEventReader reader = factory.createXMLEventReader(
new ByteArrayInputStream(xmlBytes));
try { …Run Code Online (Sandbox Code Playgroud)带有屏幕菜单栏的简单玩具应用程序可以像这样在Java FX 8中编写:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(final String[] args) throws Exception {
launch(Main.class, args);
}
@Override
public void start(Stage stage) throws Exception {
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem newNotebookMenuItem = new MenuItem("New Notebook...");
newNotebookMenuItem.setAccelerator(KeyCombination.keyCombination("Meta+N"));
newNotebookMenuItem.setOnAction(event -> { System.out.println("Action fired"); });
fileMenu.getItems().add(newNotebookMenuItem);
menuBar.getMenus().add(fileMenu);
menuBar.setUseSystemMenuBar(true);
VBox root = new VBox();
root.getChildren().add(menuBar);
Scene scene = …Run Code Online (Sandbox Code Playgroud) 使用 BouncyCastle 库(虽然我猜这个库有点不相关)我经常遇到指定为 ASN.1 标识符的算法 ID。例如,证书的签名算法可能是"1.2.840.113549.1.1.11".
有没有一种正确的方法可以将其转换为某种人类可读的形式,而不需要找到我可以得到的每个 ID 并手动构建一个巨大的查找表?
自Java 1.5以来,javac一直在寻找第三方罐子的清单来寻找其他罐子.这会导致许多不良副作用:
-Xlint:-path)所以我想知道是否有人知道魔术调用来禁用它.假设Sun没有给我们带来另一个我们不想要的功能,一旦我们拥有它就无法关闭.
java ×10
asn.1 ×1
bouncycastle ×1
certificate ×1
classpath ×1
generics ×1
guava ×1
immutability ×1
jar ×1
java-8 ×1
java-stream ×1
javac ×1
javafx ×1
javafx-8 ×1
lambda ×1
macos ×1
manifest ×1
map ×1
overloading ×1
parsing ×1
preferences ×1
printing ×1
rhino ×1
ssl ×1
stax ×1
swing ×1
xml ×1