I'm using Spotless with Gradle. I've configured it to use Eclipse's JDT Code Formatter:
spotless {
groovyGradle {
greclipse("4.21.0").configFile("${rootDir}/config/spotless/eclipe_groovy_formatter.xml")
}
java {
eclipse("4.21.0").configFile("${rootDir}/config/spotless/eclipe_jdt_formatter.xml")
endWithNewline()
importOrder("", "javax", "java")
indentWithSpaces(2)
lineEndings(LineEnding.UNIX)
removeUnusedImports()
trimTrailingWhitespace()
}
}
The content of eclipe_jdt_formatter.xml is just:
<?xml version="1.0" encoding="UTF-8" ?>
<profiles version="12">
<profile kind="CodeFormatterProfile" name="Fulgore Team" version="12">
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="80" />
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="false" />
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="100" />
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert" />
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert" />
</profile>
</profiles>
The problem is that I would like to configure the correct setting(s) within the (Eclipse) XML file in order to have the enum values each on its own line.
For instance, this is how it's currently formatting the source code:
public enum Type {
VALUE, OTHER, ANOTHER,
}
...but I would like:
public enum Type {
VALUE,
OTHER,
ANOTHER,
}
If anyone knows the combination of settings I can use within the XML file to accomplish this I would really appreciate it. I've tried a couple of combinations from .formatter and/or .indent without luck.
Try <setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="49"/>
Related
I'm using VS Code for Java development and working with other developers who use IntelliJ. I'd like to use the Organize Imports command (Shift+Alt+O) to clean up my imports, but I don't want to fight over import order with every commit. So I'd like to configure VS Code to organize the imports in the same order as IntelliJ's default. Does anybody have a configuration that would do this?
If this is not possible, is there a workspace configuration I can apply to both VS Code and IntelliJ so that the two IDEs will agree, even if they aren't agreeing on IntelliJ's default?
We were able to get it the almost identical with the following config tweaks.
VS Code:
{
"java.completion.importOrder": [
"",
"javax",
"java",
"#"
]
}
IntelliJ
The only difference from the IntelliJ default is a new line between import javax... and import java....
It's possible to get VS Code and IntelliJ to agree on a standard format, as long as that standard format:
Puts static imports at the top*
Separates all specific sections with empty lines
Puts everything not in its own specific section in a catch-all section at the end*
Never uses wildcard imports
Not actually true; static imports can be positioned in VS Code with '#', and everything else can be position in VS Code with ''.
IntelliJ's default settings don't work for this, but it is flexible enough to be reconfigured. Here are the files to add to a project to make just that project set up consistent rules for both IDEs (make sure they are not excluded in .gitignore).
Rule: The following groups separated by empty lines: Static imports, java.*, javax.*, everything else.
.vscode/settings.json:
{
"java.completion.importOrder": ["java", "javax"],
}
.idea/codeStyles/codeStyleConfig.xml:
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>
.idea/codeStyles/Project.xml
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
<option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="" withSubpackages="true" static="true" />
<emptyLine />
<package name="java" withSubpackages="true" static="false" />
<emptyLine />
<package name="javax" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="false" />
</value>
</option>
</JavaCodeStyleSettings>
</code_scheme>
</component>
I got custom checkstyle.xml file with entry for MethodCount like this:
<module name="MethodCount">
<property name="maxTotal" value="20"/>
<property name="maxPrivate" value="10"/>
<property name="maxPublic" value="10"/>
<property name="severity" value="error"/>
</module>
However this creates a problem for huge model classes with getters and setters, which are provided by another web service. Can i somehow exclude this methods? Or is this considered a bad practice to not count those?
You can create suppression.xml file:
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="\w*(Dto.java|Entity.java)\b" checks="MethodCount"/>
</suppressions>
And point it in checkstyle.xml
<module name="SuppressionFilter">
<property name="file" value="./suppression.xml"/>
</module>
Then you will suppress check MethodCount for files ending with Entity.java or Dto.java
AFAIK you cannot suppress only getters/setters. Generally, for data structures like entities or dtos it is not a problem for having more than 5 fields with getters and setters.
But if you have real objects adding setter/getters for each field is considering a bad practice.
Not very sure if it's what you need but you can ignore getter and setter methods from inspections:
Goto Settings (CTRL+Alt+S),
then Editor->Inspections->Java->Class metrics->Class with too many methods
I have the XML file which starts like this:
<?xml version="1.0" encoding="UTF-8"?>
<interface name="AccountAPING" owner="BDP" version="1.0.0" date="now()" namespace="com.betfair.account.api"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<description>Account API-NG</description>
...
afterward there are various blocks, such as:
<operation name="getDeveloperAppKeys" since="1.0.0">
<description>
Get all application keys owned by the given developer/vendor
</description>
<parameters>
<request/>
<simpleResponse type="list(DeveloperApp)">
<description>
A list of application keys owned by the given developer/vendor
</description>
</simpleResponse>
<exceptions>
<exception type="AccountAPINGException">
<description>Generic exception that is thrown if this operation fails for any reason.</description>
</exception>
</exceptions>
</parameters>
</operation>
........
<simpleType name="Status" type="string">
<validValues>
<value name="SUCCESS">
<description>Sucess status</description>
</value>
</validValues>
</simpleType>
........
<dataType name="TimeRange">
<description>TimeRange</description>
<parameter name="from" type="dateTime" mandatory="false">
<description>from, format: ISO 8601)</description>
</parameter>
<parameter name="to" type="dateTime" mandatory="false">
<description>to, format: ISO 8601</description>
</parameter>
</dataType>
How can I generate Java code from this using maven? I tried using "maven-jaxb2-plugin", but it can't parse this structure.
Please note
This is an XML file not not an xsd
I'm using Netbeans
First of all, you need the schema (xsd) that describes your xml sample. Without that schema you can not use Jaxb. You don't have a schema for the sample you shown xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" is not the schema for your xml.
You can use free on-line tools to generate schemas from xml, but you can't rely on this tools without review the automated schema.
To generate Java code from a schema file use XJC, see here. Open a command prompt to the folder where you put your xsd file, and then generate java code you'll just need to type:
$ xjc nameOfSchemaFile.xsd
xjc is included with Java SDK.
MyBatis documentation shows a way to build a SqlSessionFactory through XML configuration file or a Configuration object through Java code. It also mentions passing properties that will override what is specified in the XML file.
I am trying use the properties facility to supply a data source URL in addition to the XML configuration, but the property does not get set.
Here's the configuration XML I am using (removed all the aliases and mappings for brevity):
<configuration>
<typeAliases>
<typeAlias alias="Item" type="com.example.project.Item"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:C:/path_to_db_file_in_the_filesystem"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/project/mappers/ItemMapper.xml"/>
</mappers>
</configuration>
The XML file works fine for everything, but I need to supply the url through Java code (through the code, it is obtained from another configuration file so it has to be dynamically supplied to MyBatis). I know I can do it all in code, but that will be unnecessary work so I would like to avoid that route if possible.
Based on the description in the manual, I removed the url line from the XML file and came up with the following code:
String resource = "com/example/project/MyBatisConfiguration.xml";
Reader reader = Resources.getResourceAsReader(resource);
Properties props = new Properties();
props.setProperty("url", url);
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader, props);
The code builds the SqlSessionFactory, but I get the "url cannot be null" exception, indicating that the property was not successfully overwritten. I think the name of the property should be in a special format, but I could not find out what that format is.
Thanks a lot in advance for all the help.
In your configuration XML you can insert a placeholder for the datasource URL like that:
<property name="url" value="${url}"/>
Then the build() method of SqlSessionFactoryBuilder replaces "${url}" in the XML with the value of property "url" provided by props.
Any idea why this error is happening and how to fix it? I'm getting this error when trying to parse/load a config file:
Error
Warning: validation was turned on but an org.xml.sax.ErrorHandler was not
set, which is probably not what is desired. Parser will use a default
ErrorHandler to print the first 10 errors. Please call
the 'setErrorHandler' method to fix this.
Error: URI=null Line=3: Document root element "persistence", must match DOCTYPE root "null".
Error: URI=null Line=3: Document is invalid: no grammar found.
null
[]
null
Main code
public static void main(String[] args) throws ConfigurationException {
config = new XMLPropertiesConfiguration(new File("META-INF/vamola.xml"));
System.out.println(config.getString("persitence-unit.provider"));
System.out.println(config.getList("persistence-unit.properties.name"));
}
XML FILE
<?xml version="1.0"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="dbBank" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>br.ufg.inf.server.Account</class>
<class>br.ufg.inf.server.UserBank</class>
<properties>
<property name="toplink.jdbc.user" value="derby" />
<property name="toplink.jdbc.password" value="senha" />
<property name="toplink.jdbc.url" value="jdbc:derby://192.168.80.125:1527/db/master/dbBank;create=true"/>
<property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
<property name="toplink.ddl-generation" value="create-tables" />
<property name="toplink.logging.level" value="OFF" />
<property name="toplink.target-database" value="Derby" />
</properties>
</persistence-unit>
</persistence>
If your parsing an XML document with validation turned on, you need to specify either a DTD or an XML schema in a DOCTYPE at the start of your XML document. Your parser is basically complaining that it doesn't know how to validate your document because no grammer has been specified to validate the mark up.
You already have an XML schema, so you probably want:
<!DOCTYPE schema PUBLIC "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
If you want to turn off validation, you need something like:
spf.setValidating(false); (Where spf is a SaxParserFactory)
The exception says that an ErrorHandler wasn't set. This means that the parser uses its built-in error handler, which simply writes messages to the console. If you actually want to validate, you need to create an ErrorHandler implementation and attach it to the DocumentBuilder.
For more information, read this: http://www.kdgregory.com/index.php?page=xml.parsing (error handlers are about 1/3 of the way down).
Or, as other responses have suggested, you can just turn validation off.
The XML document defines the default namespace http://java.sun.com/xml/ns/persistence and includes a url, where the schema can be found (xsi:schemaLocation attribute, first value is the namespace, second the url or path).
Please double-check if this url is accessible at the time you parse it. An alternative is to download the schema, put it on the file system and modify the xsi:schemaLocation value.