Import "someObj.proto" was not found or had errors - java

I need to import a .proto file defined in a jar in our central maven.
Here's my build.gralde:
apply plugin: 'com.google.protobuf'
buildscript {
repositories {
maven {
url 'http://abc.def.com/content/groups/public/'
}
maven {
url 'http://abc.def.com/content/repositories/snapshot/'
}
}
dependencies {
classpath 'def.abc.someObj:someObj-proto:1.2'
}
}
protobuf {
generatedFilesBaseDir="$projectDir/src/"
}
sourceSets {
main {
// this tells the plugin where your project specific
// protofiles are located
proto {
srcDir 'src/main/resources/proto/'
}
java {
srcDir 'src/main/java'
}
}
}
Here's my other.proto file:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.def.abc";
import "google/protobuf/any.proto";
import "someObj.proto";
whenever I try to compile, it's always complaining at
Import "someObj.proto" was not found or had errors.
I've downloaded the jar file from this maven, and clearly saw that this someObj.proto is in there.
Any ideas please?
Thanks!

Related

JavaFx Application Class not found in Gradle jar

I am trying to build a jar with the following build.gradle:
plugins {
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.10'
}
application {
mainClass.set("edu.hm.dako.auditLogServer.AdminGuiStarter")
}
jar.enabled = true
javafx {
version = "18"
modules = ['javafx.controls', 'javafx.fxml']
}
sourceSets {
main {
resources {
srcDirs = ["src/main/java"]
includes = ["**/*.fxml"]
}
}
}
dependencies {
implementation project(':common')
implementation project(':communication')
implementation 'org.openjfx:javafx:18'
implementation group: 'org.apache.commons', name: 'commons-configuration2', version: '2.8.0'
implementation group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.4'
}
repositories {
mavenCentral()
}
jar {
manifest {
attributes "Main-Class": "edu.hm.dako.auditLogServer.AdminGuiStarter"
}
archiveBaseName = 'AdminGradle'
archiveVersion = '0.1.0'
}
The Main class of the project is following:
package edu.hm.dako.auditLogServer;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class AdminGuiStarter extends Application{
#Override
public void start(Stage stage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("AdminGui.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
}
}
// bitte über gradle starten, da sonst JavaFx Runtime components fehlen
public static void main(String[] args) {
launch();
}
}
When I then try to execute the jar, I get this error: java.lang.NoClassDefFoundError: javafx/application/Application
How can I fix this so that the jar will execute successful? When I run the Application via Gradle run, everything works fine.

Gradle append zip archive

I need to add file to existing zip archive. I tried to use Gradle Zip Task but it overwrite my archive.
I have now solved the problem as follows
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Paths
import java.util.function.Consumer
task AddToZip() {
doLast {
FileSystem fs = FileSystems.newFileSystem(Paths.get("$pathToZip"), null)
Files.walk(Paths.get("$rootDir/dir")).forEach(new Consumer<java.nio.file.Path>() {
#Override
void accept(java.nio.file.Path path) {
java.nio.file.Path dest = fs.getPath(path.toString().substring("$rootDir".length()))
if (path.toFile().isDirectory()) {
Files.createDirectory(dest)
return
}
Files.copy(path, dest)
}
})
fs.close()
}
}
Is there any other way to solve this problem?
You could use Project.zipTree(...) to create a FileTree from the original zip. This can then be passed to Zip.from(...)
task addToZip(type:Zip) {
from zipTree('path/to/original.zip')
from 'path/to/additional/file.txt'
archiveFileName = "updated.zip"
destinationDirectory = file("$buildDir/zips")
}
See Project.zipTree(...)
See AbstractCopyTask.from(...)

Spring Boot Application Could not initialize class org.apache.logging.log4j.util.PropertiesUtil

I am trying to implement the hello world web application using spring boot, gradle and tomcat by following "Building a RESTful Web Service" but have been unable to run make it run so far.
The code is pretty much the same as the one provided on the website, I have wasted hours debugging it thinking there was a bug in the provided code but I still can't figure out what's wrong.
I am using Eclipse Java EE IDE for Web Developers, Version: Neon.3 Release (4.6.3), Build id: 20170314-1500
Any idea what could be the issue?
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.2.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'gs-rest-service'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Greeting.java
package App;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
GreetingController.java
package App;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
Application.java
package App;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
System.getProperties().put("server.port", 8486);
SpringApplication.run(Application.class, args);
}
}
Stacktrace
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:71)
at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:60)
at org.apache.commons.logging.LogFactory$Log4jLog.<clinit>(LogFactory.java:199)
at org.apache.commons.logging.LogFactory$Log4jDelegate.createLog(LogFactory.java:166)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:109)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:99)
at org.springframework.boot.SpringApplication.<clinit>(SpringApplication.java:198)
at App.Application.main(Application.java:9)
When using the authorisation manager, this message can also be the result of a missing grant (or file) in the catalina.policy or security.policy (-Djava.security.policy).
For example add:
grant codeBase "file:${catalina.base}/webapps/${APPLICATION_NAME}/-" {
permission java.security.AllPermission;
};
Apparently setting the port number using System.getProperties().put("server.port", 8486); the NoClassDefFoundError exception.
However creating a application.properties file mentioned by #Nitishkumar Singh in the resources folder to specify the port number to use solved the issue.
Add this dependency:
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.11.0'
And try again.
Could not initialize class org.apache.logging.log4j.util.PropertiesUtil.
I met the same problem as you. Automated deployment to Tomcat by using Jenkins always occurs. Probably some jar don't exclusion dependecy 'org.apache.logging.log4j'. But springbooot 2.0.1.RELEASE uses logback by default. On org.springframework.boot.web.servlet.support.SpringBootServletInitializer:
public void onStartup(ServletContext servletContext) throws ServletException {
this.logger = LogFactory.getLog(this.getClass());
WebApplicationContext rootAppContext = this.createRootApplicationContext(servletContext);
if (rootAppContext != null) {
servletContext.addListener(new ContextLoaderListener(rootAppContext) {
public void contextInitialized(ServletContextEvent event) {
}
});
} else {
this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not return an application context");
}
}
public static Log getLog(String name) {
switch(logApi) {
case LOG4J:
return LogFactory.Log4jDelegate.createLog(name);
case SLF4J_LAL:
return LogFactory.Slf4jDelegate.createLocationAwareLog(name);
case SLF4J:
return LogFactory.Slf4jDelegate.createLog(name);
default:
return LogFactory.JavaUtilDelegate.createLog(name);
}
}

Error file not generated with log4j

I am running a gradle project and I an trying to have log4j both log to the console as well as to a file. While the error is logged to the console, no file is logged to. I have my log4j.properties in the src/main/resources. I have tried moving the properties files to the src folder as well as to just about every folder suggested on SO without success. I have tried both rollingFile and File within the log4j as well. Is there something wrong with by log4j.properties file, or am I not placing the file in the correct spot?
Here are my current files
log4j.properties
# root level configurations
log4j.rootLogger=INFO,console,rollingFile
# configuration for console outputs
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# configuration for file output (into a file named messages.log)
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=/home/cbolles/devel/testing/gradle_testing/messages.log
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
build.gradle
apply plugin: 'java'
repositories {
jcenter()
}
dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.8.2'
compile 'org.slf4j:slf4j-log4j12:1.7.18'
testCompile 'junit:junit:4.12'
}
task(runSimple, dependsOn: 'classes', type: JavaExec) {
main = 'com.bolles.ErrorTester'
classpath = sourceSets.main.runtimeClasspath
args 'mrhaki'
systemProperty 'simple.message', 'Hello '
}
defaultTasks 'runSimple'
LogTesting.java
package com.bolles;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogTesting
{
private static final Logger log = LogManager.getLogger(LogTesting.class);
public static void reportError(Exception e, boolean consoleLog)
{
String errorMessage = "";
if(e.getMessage() != null)
{
errorMessage = e.getMessage();
}
StringWriter stackTraceWriter = new StringWriter();
e.printStackTrace( new PrintWriter(stackTraceWriter));
String stackTrace = stackTraceWriter.toString();
log.error(errorMessage);
log.log(Level.ERROR, errorMessage + "\n" + stackTrace);
}
}
ErrorTester.java
package com.bolles;
public class ErrorTester
{
public static void nullStringTest()
{
String errorString = null;
try
{
System.out.print(errorString);
}
catch(Exception e)
{
LogTesting.reportError(e, true);
}
}
public static void main(String[] args)
{
nullStringTest();
}
}
None of the other answers seem to work for my issue.
The apparent problem seems to be that you are using log4j's LogManager and Logger classes. Make the following changes to your LogTesting class (slf4j is already among your dependencies as I see)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
private static final Logger log = LoggerFactory.getLogger(LogTesting.class);
...
log.error(errorMessage);
//log.log(Level.ERROR, errorMessage + "\n" + stackTrace); //no such method in slf4j
and it should write the error in the file too as expected.
(also you seem to need to modify the ErrorTester class because currently there is no exception thrown from there so LogTesting.reportError() is not called)

When I compile Java(fx) application for Android, with the SoundPool use, the java compiler says "package android.media does not exist"

In a Java application for Android, made in JavaFX under Eclipse Neon2, I want to use the android media SoundPool class.
To do that, I have added, in the Java Build Path:
the android-sdks platform : android-25 (called android.jar).
the jfxdvk-8.60.8.jar
Then, for instance, I create a SoundPool instance as follows:
import android.media.SounPool;
import android.media.MediaPlayer;
...
SoundPool sp = new SoundPool(MAX_STREAMS,AudioManager.STREAM_MUSIC,0);
The syntax is correct and the Eclipse editor does not notice any error.
But, when compiling the file, I have two errors "package android.media does not exist import android.media.AudioManager" and "package android.media does not exist import android.media.SoundPool;", and then, (it is a consequence), "cannot find symbols" at "AudioManager.STREAM_MUSIC" and at "new SoundPool" of the previous line code.
I don't understand these errors because I have added, in my JavaBuild Path, this android-sdks platform: android.jar (android-25) ad the Eclipse editor can fetch these two imports.
Thanks in advance for your response
Further information:
Errors raised on java compilation:
[sts] -----------------------------------------------------
[sts] Starting Gradle build for the following tasks:
[sts] androidInstall
[sts] -----------------------------------------------------
:validateManifest
:collectMultiDexComponents
:compileJavaC:\Users\pascal\workspaceNeon\JFX_withGluon_11.0gAvecSoundPoolKO\src\main\java\com\gluonapplication\GluonApplication.java:3: error: package android.media does not exist
import android.media.AudioManager;
^
C:\Users\pascal\workspaceNeon\JFX_withGluon_11.0gAvecSoundPoolKO\src\main\java\com\gluonapplication\GluonApplication.java:4: error: package android.media does not exist
import android.media.SoundPool;
^
C:\Users\pascal\workspaceNeon\JFX_withGluon_11.0gAvecSoundPoolKO\src\main\java\com\gluonapplication\GluonApplication.java:635: error: cannot find symbol
static SoundPool androidSoundPoolApplication = null;
----------------------
Related code:
package com.gluonapplication;
import android.media.AudioManager;
import android.media.SoundPool;
import com.gluonhq.charm.down.Services; // line 3
import com.gluonhq.charm.down.plugins.AccelerometerService; // line 4
......
final static int MAX_STREAMS = 10;
static SoundPool androidSoundPoolApplication = null; // line 635
And the build.gradle:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.javafxports:jfxmobile-plugin:1.3.2'
}
}
apply plugin: 'org.javafxports.jfxmobile'
repositories {
jcenter()
maven {
url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
}
}
mainClassName = 'com.gluonapplication.GluonApplication'
dependencies {
compile 'com.gluonhq:charm:4.3.0'
}
jfxmobile {
downConfig {
version '3.2.0'
plugins 'accelerometer', 'compass', 'device', 'orientation', 'storage', 'vibration', 'display', 'magnetometer', 'lifecycle', 'statusbar', 'position'
}
android {
applicationPackage = 'com.gluonapplication'
manifest = 'src/android/AndroidManifest.xml'
androidSdk = 'C:/Users/pascal/AppData/Local/Android/sdk'
resDirectory = 'src/android/res'
compileSdkVersion = '25'
buildToolsVersion = '25.0.1'
}
ios {
infoPList = file('src/ios/Default-Info.plist')
forceLinkClasses = [
'com.gluonhq.**.*',
'javax.annotations.**.*',
'javax.inject.**.*',
'javax.json.**.*',
'org.glassfish.json.**.*'
]
}
}

Categories